表test
id  size pid status
1    0    0   0
2    0    0   0
3    0    0   0
4    1    1   0
5    1    1   0
6    1    4   0
要update一条纪录,就必须先递归update其所有子纪录(也就是pid=当前纪录ID的纪录)
如:把id=1的记录update的话,就要把id=4,5,6 一起update 
同时要把这几条记录的sum(size)统计出来因为以前学习得不多,现在不得不来求助了,望各位大大帮忙回答

解决方案 »

  1.   

    --生成测试数据
    create table BOM(ID INT,[size] int,PID INT,status int)
    insert into BOM select 1,0,0,0
    insert into BOM select 2,0,0,0 
    insert into BOM select 3,0,0,0
    insert into BOM select 4,1,1,0
    insert into BOM select 5,1,1,0 
    insert into BOM select 6,1,4,0 go--创建用户定义函数用于取每个父节点下子节点的采购配置信息
    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
    go--执行查询
    select ID from dbo.f_getChild(1)
    go--输出结果
    /*
    ID         
    ---------- 
    4
    5
    6
    */declare @id int 
    set @id = 1
    update BOM set status = 1 where id = @id
    update a
    set status = 1
    from bom a
    right join (select ID from dbo.f_getChild(@id)) b
    on a.id = b.id
    select * from bom
    select sum(size)  as [sum]
    from bom
    where id in (select @id as id  union all select ID from dbo.f_getChild(@id)) 
    /*ID         
    ---------- 
    4
    5
    6(所影响的行数为 3 行)
    (所影响的行数为 1 行)
    (所影响的行数为 3 行)ID          size        PID         status      
    ----------- ----------- ----------- ----------- 
    1           0           0           1
    2           0           0           0
    3           0           0           0
    4           1           1           1
    5           1           1           1
    6           1           4           1(所影响的行数为 6 行)sum         
    ----------- 
    3(所影响的行数为 1 行)
    */
    --删除测试数据
    drop function f_getChild
    drop table BOM