日期:2014-05-16  浏览次数:20768 次

求个多个父子级嵌套的sql语句
比如有3列
ID      ParentID       Delete
1                                  0
2          1                     0
3          1                     0
4          2                     0

我要把所有根级ID为1的数据的Delete置为1,现在这里根级ID为1,其他行都是子级,也就是所有行都要把Delete置为1,请教下该怎么写
------解决方案--------------------

create table Test
(
ID int null,
ParentID int null,
[Delete] int null
)
insert Test
select 1,null,0 union all
select 2,1,0 union all
select 3,1,0 union all
select 4,2,0 


------解决方案--------------------

create procedure toupdatetb(@id int)
as
begin
    ;with cte as
    (
    select ID,ParentID,[Delete] from Test where ID=@id
    union all
    select t.ID,t.ParentID,t.[Delete] from testcte as tc
    join Test as t on t.ParentID=tc.ID
    )

    update Test set [Delete]=1
    where ID in(select ID from testcte)
end
go

exec toupdatetb 1