T-SQL 递归查询 - 怎么做? [英] T-SQL recursive query - how to do it?

查看:45
本文介绍了T-SQL 递归查询 - 怎么做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)    

这篇关于T-SQL 递归查询 - 怎么做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆