至於我,我喜歡使用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合併的
不,你不能使用合併在這裏。合併根據與源表的連接結果對目標表執行插入,更新或刪除操作。 – NMK 2014-09-22 17:10:38
有沒有什麼你現有的查詢不能做到你想要的?如果不是,那麼使用你擁有的。 「MERGE」適用於您一次處理多件事情的相當複雜的流程。對於你的查詢,我建議的唯一的事情是添加'WHERE t1.col1 <> COALESCE(t2.col1,0)或t1.col IS NULL',所以你只更新你需要更新的地方。 – 2014-09-22 17:11:20