使用UPDATE与MERGE不匹配

时间:2014-09-22 17:03:29

标签: sql-server-2008 tsql

如果我正在通过以下查询进行更新。我可以将t2.co1包装在COALESCE函数中,以便为源查询中找不到的行提供替代值。

    UPDATE
        t1
    SET
        t1.col1 = COALESCE(t2.col1,0)
    FROM
        table AS t1
    LEFT JOIN
        other_table AS t2
    ON
        t1.id = t2.id

我最近发现了MERGE语句 - 但后来发现你不能在WHEN NOT MATCHED条款上做更新。有没有办法用MERGE做到这一点,还是我应该坚持使用上面的?

2 个答案:

答案 0 :(得分:1)

至于我,我喜欢使用MERGE,但我同意对你特定的简单案例毫无意义。但是,如果我们考虑到这是简化的示例,我们可以使用MERGE来解决此任务。在您的情况下,当源表(col1)中没有匹配项时,您需要在目标表(@table)中将@other_table的值设置为0。我们在这里:

-- Setting up test tables and data
DECLARE @table TABLE (
     id     INT
    ,col1   INT
)
INSERT INTO @table (id, col1) VALUES (1, 101)
INSERT INTO @table (id, col1) VALUES (2, 102)
INSERT INTO @table (id, col1) VALUES (3, 103)
INSERT INTO @table (id, col1) VALUES (4, 104)

-- Target table before update
SELECT * FROM @table

DECLARE @other_table TABLE (
     id     INT
    ,col1   INT
)
INSERT INTO @other_table (id, col1) VALUES (1, 201)
INSERT INTO @other_table (id, col1) VALUES (2, 202)
INSERT INTO @other_table (id, col1) VALUES (3, 203)

-- Merging target and source tables
MERGE INTO @table AS t1
   USING @other_table AS t2
        ON  t1.id = t2.id

WHEN MATCHED
THEN
   UPDATE
      SET   col1 = t2.col1

WHEN NOT MATCHED BY SOURCE
THEN
   UPDATE
      SET   col1 = 0
;

-- Target table after update using merge
SELECT * FROM @table

恢复 - 当您确实需要合并时使用MERGE,当您只需要更新时使用UPDATE

答案 1 :(得分:0)

SQL SERVER中合并的简单示例

CREATE TABLE #targetTable(id int,name varchar(50))
CREATE TABLE #sourceTable(id int,name varchar(50))

INSERT INTO #sourceTable values(1,'John');
INSERT INTO #sourceTable values(1,'Albrt');
INSERT INTO #sourceTable values(1,'Roy');

MERGE #targetTable AS [target]
USING #sourceTable AS [source]
ON [target].id = [source].id
WHEN NOT MATCHED THEN
INSERT (id, Name)
VALUES (source.id, source.Name);

select * from #targetTable as T
drop table #targetTable
drop table #sourceTable