2013-10-08 96 views
3

我有自參照關係的表,T-SQL遞歸查詢 - 怎麼做?

ID parentID UserId Title 
1 null  100 A 
2  1  100 B 
3  2  100 C 
4  2  100 D 
5  null 100 E 
6  5  100 F 

我想更新用戶ID從100至101與ID = 1和它的孩子們所有的記錄,所以我想有

ID parentID UserId Title 
1 null  101 A 
2  1  101 B 
3  2  101 C 
4  2  101 D 
5  null 100 E 
6  5  100 F 

我怎樣才能在T-SQL中做到這一點?

回答

10

您可能想要使用允許您生成遞歸查詢的common table expression

如:

;with cte as 
(
    select * from yourtable where id=1 
    union all 
    select t.* from cte 
     inner join yourtable t on cte.id = t.parentid 
) 
    update yourtable 
    set userid = 101 
    where id in (select id from cte)