2014-09-22 48 views
0

如果我從下面的查詢更新。我可以將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子句進行UPDATE。有沒有辦法與MERGE做到這一點,或者我應該堅持使用上面?

+0

不,你不能使用合併在這裏。合併根據與源表的連接結果對目標表執行插入,更新或刪除操作。 – NMK 2014-09-22 17:10:38

+1

有沒有什麼你現有的查詢不能做到你想要的?如果不是,那麼使用你擁有的。 「MERGE」適用於您一次處理多件事情的相當複雜的流程。對於你的查詢,我建議的唯一的事情是添加'WHERE t1.col1 <> COALESCE(t2.col1,0)或t1.col IS NULL',所以你只更新你需要更新的地方。 – 2014-09-22 17:11:20

回答

0

至於我,我喜歡使用MERGE,但我同意它對你的特殊簡單情況沒有意義。但是如果我們考慮到這是簡化的例子,我們可以用MERGE來解決這個問題。在你的情況下,當它在源表(@other_table)中沒有匹配時,需要在目標表(@table)中將col1的值設置爲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當你只需要更新。在SQL Server合併的

0

簡單的例子

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 
相關問題