T-SQL 递归查询 - 怎么做?

2021-09-10 00:00:00 sql tsql sql-server

我有一个具有自引用关系的表,

I have a table with self referencing relation,

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=1 的所有记录及其子项的 UserId 从 100 更新为 101,所以我想要

I want to update UserId from 100 to 101 for all records with ID=1 and its children, so I want to have

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 中做到这一点?

How can I do it in T-SQL?

推荐答案

您可能想要使用 common table expression 它允许您生成递归查询.

You probably want to use a common table expression which allows you to generate recursive queries.

例如:

;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)    

相关文章