2013-10-08 40 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)