2015-02-09 107 views
0

我有以下查詢SQL服務器遞歸查詢更新

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 

我希望能夠設置LastRestoredGETDATE只受影響的結果的行。

+1

您是否嘗試過加入'Backup'你的CTE和執行更新? – Taryn 2015-02-09 17:47:47

回答

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() 
+0

謝謝。這是很棒的信息。我終於在工作中得到了一位朋友的幫助,並且遇到了複雜問題,因爲我只能使用兩個獨立的SP進行工作 - 一個用於遞歸結果的更新,另一個用於選擇結果。我不知道是否可以執行更新並在單個存儲過程中進行選擇。更新看起來是這樣的: – 2015-02-11 16:09:33

+0

與PersonCTE AS ( 選擇 [的ParentId], [ID], [名], [LastRestored], [EntryTime] FROM [DBO] [備份] WHERE [ID] = someguid UNION ALL SELECT c.ParentId, c.Id, c.Name, c.LastRestored, c.EntryTime FROM [DBO]。[備份]ç INNER JOIN PersonCTE小號 ON c.ParentId = s.Id ) UPDATE [dbo]。[Backup] SET [LastRestored] = GETDATE() WHERE [Id] IN( SELECT [Id] FROM PersonCTE – 2015-02-11 16:11:03