使用MERGE多次更新同一行

时间:2015-05-25 12:35:19

标签: sql sql-server sql-server-2012

我们说我有@Product表。我想从另一个临时表@TempProducts更新此表。让我们说我有,

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更新@Products,这样如果Value为NULL,则不要更新UPDATE。我的最终输出应该是,

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子句和OrderBy。

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

1 个答案:

答案 0 :(得分:3)

这适用于输出..

org/apache/xerces/jaxp/datatype/XMLGregorianCalendarImpl