[SQL]MERGE (Transact-SQL)
MERGE:根據與來源資料表聯結的結果,在目標資料表上執行插入、更新或刪除作業。
環境:SQL 2008 R2
以前我們判斷資料不存在就INSERT不然就UPDATE需要用IF來判斷有沒有值,如下,
USE AdventureWorks2008R2;
GO
--UPDATE OR INSERT
-- Update the row if it exists.
UPDATE Production.UnitMeasure
SET Name = 'NEW BBC NAME'
OUTPUT deleted.*, 'UPDATE', inserted.*
WHERE UnitMeasureCode = 'BBC'
-- Insert the row if the UPDATE statement failed.
IF (@@ROWCOUNT = 0 )
BEGIN
INSERT INTO Production.UnitMeasure (UnitMeasureCode, Name)
OUTPUT 'INSERT', inserted.*
VALUES ('BBC', 'NEW BBC NAME')
END
現在可改使用MERGE,一個SQL就解決了,如下,
USE AdventureWorks2008R2;
GO
--改用MERGE
MERGE Production.UnitMeasure AS target
USING (VALUES('BBC', 'NEW BBC NAME')
, ('ABC', 'NEW ABC NAME')
, ('CCC', 'NEW CCC NAME'))
AS source (UnitMeasureCode, Name)
ON (target.UnitMeasureCode = source.UnitMeasureCode)
WHEN MATCHED THEN
UPDATE SET Name = source.Name
WHEN NOT MATCHED THEN
INSERT (UnitMeasureCode, Name)
VALUES (source.UnitMeasureCode, source.Name)
OUTPUT deleted.*, $action, inserted.*;
Hi,
亂馬客Blog已移到了 「亂馬客 : Re:從零開始的軟體開發生活」
請大家繼續支持 ^_^