sql - 使用 SQL 更新层次结构中的父记录
问题描述
我有一个具有父子层次结构的表。我正在尝试编写一个更新语句,该语句将在给定设备 ID 列表的情况下更新该 ID 的记录及其所有父记录。
CREATE TABLE [Equipment]
(
[id] [int] NOT NULL,
[Parentid] [int] NULL,
[ActiveInExecution] [bit] NULL,
)
所以我的想法是,如果我有一个 ID 列表,比如说 3、5、6,我应该能够将它们的所有活动位更新为 true(是的,我意识到在这种情况下 id 5 将是多余的)
我开始为此制作一个光标,但我觉得这太过分了。
任何帮助,将不胜感激。
谢谢。
id | parentid | active
---+----------+--------
1 | null | 0
2 | 1 | 0
3 | 2 | 0
4 | null | 0
5 | 4 | 0
6 | 5 | 0
解决方案
一种选择是使用递归查询来构建层次结构树,然后使用连接来更新相关行。假设您要更新 id3
及其所有父母:
with cte as (
select * from equipment where id = 3
union all
select e.*
from equipment e
inner join cte c on c.parentid = e.id
)
update e
set e.activeInExecution = 1
from equipment e
inner join cte c on c.id = e.id
推荐阅读
- javascript - 使用 vue.js,如何将活动标记设置为当前活动路径?
- python-2.7 - Windows搜索可以存在于多个子文件夹中的可执行文件,然后运行每个实例,必须是python 2.7
- sas - SAS 连接到 SQL Server dsn less
- maven - 为什么我会收到此 NoClassDefFound 错误?
- conditional-formatting - webi Rich Client 4.1中多个值的条件格式
- arrays - 仅对二维数组的第一维进行排序 Google Script
- scala - 当我将对象放入值时,scala Map中的编译时间错误
- c# - 用于 CRM REST 的 .NET Standard 2.0 Nuget 包
- asp.net-mvc - 如何在 ASP.NET、C# 和实体框架应用程序中使用两个数据库上下文
- javascript - 是否有可能的 javascript 函数返回新的 DOM 元素但使用 jQuery 创建