2015-05-25 37 views
1

假設我有@Product表。我想從另一個臨時表@TempProducts更新此表。比方說,我有,使用MERGE更新同一行多次

DECLARE @Products TABLE(Id INT, Name NVARCHAR(255), Description NVARCHAR(255)); 
DECLARE @TempProducts TABLE(RowNumber int, Id INT, Name NVARCHAR(255), Description NVARCHAR(255)); 

INSERT INTO @Products(Id,Name,Description) VALUES(1,'Name1','Desc1'); 

INSERT INTO @TempProducts(RowNumber,Id,Name,Description) VALUES(1,1,'NewName1',NULL); 
INSERT INTO @TempProducts(RowNumber,Id,Name,Description) VALUES(2,1,NULL,'NewDesc1'); 

我想從@TempProducts這樣,如果值是NULL,則沒有另外更新的版本?@Products。我的最終輸出應該是,

Id Name  Description 
--------------------------- 
1 NewName1 NewDesc1 

它應該更新RowNumber的順序。所以,我想,

MERGE @Products P 
USING (SELECT TOP (100000) Id, Name, Description FROM @TempProducts ORDER BY RowNumber) TP 
    ON P.Id = TP.Id 
WHEN MATCHED THEN 
UPDATE SET Name = ISNULL(TP.Name,P.Name), 
     Description = ISNULL(TP.Description,P.Description) 
     -- OUTPUT INSERTED.Id, INSERTED.Name ---- 
     ; 

它給了我

Msg 8672, Level 16, State 1, Line 25 
The MERGE statement attempted to UPDATE or DELETE the same row more than once. This happens when a target row matches more than one source row. A MERGE statement cannot UPDATE/DELETE the same row of the target table multiple times. Refine the ON clause to ensure a target row matches at most one source row, or use the GROUP BY clause to group the source rows. 

這工作,但我需要把OUTPUT子句和排序依據。

UPDATE P 
    SET Name = ISNULL(TP.Name,P.Name), 
     Description = ISNULL(TP.Description,P.Description) 
FROM @Products P 
     INNER JOIN @TempProducts TP 
      ON P.Id = TP.Id 

回答

3

這將在輸出的情況下工作..

UPDATE P 
    SET Name = ISNULL(TP.Name,P.Name), 
     Description = ISNULL(TP.Description,P.Description) 
     Output inserted.Id,inserted.Name 
FROM @Products P 
     INNER JOIN @TempProducts TP 
      ON P.Id = TP.Id 
+0

感謝。我需要使用Order By – user960567

+0

我應該使用CTE嗎? – user960567

+0

您要在哪一列排序以及哪個表格 –