带有条件MATCH子句的SQL MERGE语句

时间:2014-06-12 01:28:12

标签: sql sql-server

正如您在下面的代码中所看到的,MERGE语句完全相同,除非基于IF语句,我正在更改将合并到目标表中的列。有没有更好的写作方式?随着@Event的增长,我不想复制和粘贴越来越多的这些因为它不可维护。

IF @Event = 1
BEGIN
    MERGE INTO SomeTable
    USING (
        -- Some Query
    ) AS A ON SomeTable.Id = A.Id
    WHEN MATCHED THEN
        UPDATE SET SomeTable.Column1 = SomeTable.Column1 + 1;
END
ELSE IF @Event = 2
BEGIN
    MERGE INTO SomeTable
    USING (
        -- Some Query
    ) AS A ON SomeTable.Id = A.Id
    WHEN MATCHED THEN
        UPDATE SET SomeTable.Column2 = SomeTable.Column2 + 1;
END

2 个答案:

答案 0 :(得分:1)

一个陈述是否优于两个,这可能是一个争论的问题。但是,你可以将这些结合起来:

MERGE INTO SomeTable
USING (
    -- Some Query
) AS A ON SomeTable.Id = A.Id
WHEN MATCHED THEN
    UPDATE SET SomeTable.Column1 = (CASE WHEN @Event = 1
                                         THEN SomeTable.Column1 + 1
                                         ELSE SomeTable.Column1
                                    END),
               SomeTable.Column2 = (CASE WHEN @Event = 2
                                         THEN SomeTable.Column2 + 1
                                         ELSE SomeTable.Column2
                                    END);

答案 1 :(得分:1)

你真的不需要一个Merge语句,是的,你可以更动态地编写你的UPDATE语句。像这样......

UPDATE ST
 SET ST.Column1 = CASE WHEN @Event = 1 
                     THEN ST.Column1 + 1 
                     ELSE ST.Column1 END
    ,ST.Column2 = CASE WHEN @Event = 2 
                     THEN ST.Column2 + 1 
                     ELSE ST.Column2 END
FROM SomeTable ST 
      INNER JOIN 
                (
                 -- Some Query
                ) AS A 
ON ST.Id = A.Id

您也可以阅读Use Caution with SQL Server's MERGE Statement