标签:
很多人都知道ORACLE中有Merge關鍵字,其實SQL Server從2008版本開始也支持Merge了。
從而也可以像ORACLE一樣在一條SQL語句中同時進行Update、Insert、Delete操作。
下面來一個簡單的例子,直接上代碼了,
數量準備:
IF OBJECT_ID('TestA','U') IS NOT NULL DROP TABLE TestA GO IF OBJECT_ID('TestB','U') IS NOT NULL DROP TABLE TestB GO CREATE TABLE TestA(ID INT,Title NVARCHAR(200)) GO CREATE TABLE TestB(ID INT,Title NVARCHAR(200)) GO INSERT INTO TestA(ID,Title) VALUES (1,N'A'),(2,N'B'),(3,N'C'),(4,N'D'),(5,N'E') GO INSERT INTO TestB(ID,Title) VALUES (1,N'一'),(3,N'三'),(5,N'五'),(7,N'七'),(9,N'九') GO現在的需求是,用TestB去更新TestA,ID相同的Update,ID不同的進行Insert
常規的實現方法是分兩步走:
UPDATE a SET a.Title = b.Title FROM TestA a INNER JOIN TestB b ON a.ID = b.ID; INSERT INTO TestA(ID,Title) SELECT a.ID,a.Title FROM TestB a WHERE NOT EXISTS(SELECT * FROM TestA WHERE ID = a.ID);有了Merge,則可以一句話搞定,而且效率還很高:
MERGE INTO TestA AS a USING TestB AS b ON (a.ID = b.ID) WHEN MATCHED THEN UPDATE SET a.Title = b.Title WHEN NOT MATCHED BY TARGET THEN INSERT(ID,Title) VALUES(b.ID,b.Title);
關於Merge的更多使用,還是請參考MSDN: 參考1、參考2
标签:
原文地址:http://blog.csdn.net/helloword4217/article/details/42275987