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)
推荐阅读
热点文章
检查拆分键盘
0
带有“上一个"的工具栏和“下一个"用于键盘输入AccessoryView
0
Activity 启动时显示软键盘
0
UIWebView 键盘 - 摆脱“上一个/下一个/完成"酒吧
0
在 iOS7 中边缘滑动时,使键盘与 UIView 同步动画
0
我的 iOS 应用程序中的键盘在 iPhone 6 上太高了.如何在 XCode 中调整键盘的分辨率?
0
android:inputType="textEmailAddress";- '@' 键和 '.com' 键?
0
禁用 iPhone 中键盘的方向
0
Android 2.3 模拟器上的印地语键盘问题
0
keyDown 没有被调用
0
