使用 SQL 更新层次结构中的父记录

Use SQL to update parent records in hierarchy

我有一个 table 具有父子层次结构。我正在尝试编写一个更新语句,在给定设备 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

一个选项使用递归查询构建层次结构树,然后使用连接更新相关行。假设您要更新 ID 3 及其所有父代:

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

您可以使用递归通用 Table 表达式,然后在 UPDATE 语句的 WHERE 中使用 EXISTS,看看 id 在层次结构中找到:

CREATE TABLE dbo.[Equipment]
(
    [id] [int] NOT NULL,
    [Parentid] [int] NULL,
    [ActiveInExecution] [bit] NULL,
);
GO

INSERT INTO dbo.Equipment (id,
                       Parentid,
                       ActiveInExecution)
VALUES (1,NULL,0),
       (2, 1  ,0),
       (3, 2  ,0),
       (4,NULL,0),
       (5, 4  ,0),
       (6, 5  ,0);
GO

WITH rCTE AS(
    SELECT E.id,
           E.Parentid,
           E.ActiveInExecution
    FROM dbo.Equipment E
    WHERE E.id IN (3,5,6)
    UNION ALL
    SELECT E.id,
           E.Parentid,
           E.ActiveInExecution
    FROM dbo.Equipment E
         JOIN rCTE r ON E.Parentid = r.id)
UPDATE E
SET ActiveInExecution = 1
FROM dbo.Equipment E
WHERE EXISTS(SELECT 1
             FROM rCTE r
             WHERE r.id = E.id);
GO

SELECT *
FROM dbo.Equipment;