用户登录
用户注册

分享至

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

  • 作者: 三木子雨
  • 来源: 51数据库
  • 2022-12-06

问题描述

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

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)    
软件
前端设计
程序设计
Java相关