日期:2014-05-18  浏览次数:20505 次

列相加写成函数或存储过程
补充上一贴的http://topic.csdn.net/u/20090902/13/2148fb50-ab13-4eff-8175-96ff33b25b65.html

其实我是想修改这个函数,或改写成存储过程就得到那列相加的效果,因为原表结构不是那么单一的把列加起就完了,而是先筛选过,再来相加。
SQL code

create function f_getChild(@ID VARCHAR(10))
returns @t table(ID VARCHAR(10),PID VARCHAR(10),Level INT)
as
begin
    declare @i int
    set @i = 1
    insert into @t select ID,PID,@i from BOM where PID = @ID
    
    while @@rowcount<>0
    begin
        set @i = @i + 1
        
        insert into @t 
        select 
            a.ID,a.PID,@i 
        from 
            BOM a,@t b 
        where 
            a.PID=b.ID and b.Level = @i-1
    end
    return
end





能不能写到create function f_getChild(@ID VARCHAR(10))里直接就返回这个结果? 

或写成存储过程调用?

------解决方案--------------------
SQL code
create function f_getChild(@ID VARCHAR(10))
returns varchar(500)
as
begin
    declare @i int,@s varchar(500)
    declare  @t table(ID VARCHAR(10),PID VARCHAR(10),Level INT)
    set @i = 1
    insert into @t select ID,PID,@i from BOM where PID = @ID
    
    while @@rowcount<>0
    begin
        set @i = @i + 1
        
        insert into @t 
        select 
            a.ID,a.PID,@i 
        from 
            BOM a,@t b 
        where 
            a.PID=b.ID and b.Level = @i-1
    end
    select @s=isnull(@s+',','')+ltrim(ID) from @t
    return @s
end

------解决方案--------------------
探讨
就是这个意思,但要怎么调用呢?我执行了,是创建在标量函数里面在

------解决方案--------------------
探讨
就是这个意思,但要怎么调用呢?我执行了,是创建在标量函数里面在