我有以下查询
WITH PersonCTE
AS
(
SELECT
[ParentId],
[Id],
[Name],
[LastDeleted],
[LastRestored],
[EntryTime]
FROM [dbo].[Backup]
WHERE [Id] = someguid
UNION ALL
SELECT
c.ParentId,
c.Id,
c.Name,
c.LastDeleted,
c.LastRestored,
c.EntryTime
FROM [dbo].[Backup] c
INNER JOIN PersonCTE s
ON c.ParentId = s.Id
)
SELECT *
FROM PersonCTE
之后需要进行此类更新:
UPDATE Backup
SET [LastRestored] = GETDATE
我希望能够仅为受影响结果的行设置LastRestored
到GETDATE
。
答案 0 :(得分:0)
SQL Server允许您在cte上运行更新,请参见下面的示例
DECLARE @t TABLE(id INT , today DATE NULL)
INSERT INTO @t (id,today)
VALUES(1,NULL),(2,NULL)
;WITH cte AS
(
SELECT * FROM @T WHERE today IS NULL
)
UPDATE cte SET today = GETDATE()
SELECT * FROM @t
-- in your query try this
WITH PersonCTE
AS
(
SELECT
[ParentId],
[Id],
[Name],
[LastDeleted],
[LastRestored],
[EntryTime]
FROM [dbo].[Backup]
WHERE [Id] = someguid
UNION ALL
SELECT
c.ParentId,
c.Id,
c.Name,
c.LastDeleted,
c.LastRestored,
c.EntryTime
FROM [dbo].[Backup] c
INNER JOIN PersonCTE s
ON c.ParentId = s.Id
)
update PersonCTE
SET [LastRestored] = GETDATE()