首页 > 解决方案 > 使用 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

标签: sqlsql-serversql-updatehierarchical-datarecursive-query

解决方案


一种选择是使用递归查询来构建层次结构树,然后使用连接来更新相关行。假设您要更新 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

推荐阅读