一个选项使用递归查询来构建层次结构树,然后使用联接来更新相关行。假设您要更新id
我有一个具有父子层次结构的表。我正在尝试编写一个更新语句,在给定设备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
您可以使用递归的Common Table Expression,然后在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;
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