摘要:
下文講述MSSQL中,插入數據時,若是存在則更新,不然就插入數據的方法分享
實驗環境:sql server 2017
mssql中,咱們能夠採用 MERGE INTO 關鍵字實現此功能,
當二者匹配成功,則運行***語句,不然運行其它語句,達到插入數據時的判斷操做,
具體操做方法以下所示: sql
create table [maomao365.com] (keyId int identity, info varchar(80) ) go insert into [maomao365.com] (info)values('sqlblog'), ('sqlserver'),('maomao365.com') ---merge into實現若是存在,則更新 ---若是不存在,則刪除 MERGE INTO [maomao365.com] a USING (SELECT 2 AS keyId_B, 'other' AS info_B ) b ON ( a.keyId = b.keyId_B) WHEN MATCHED THEN UPDATE SET a.info= b.info_B --更新 WHEN NOT MATCHED THEN INSERT (info) VALUES(b.info_B); ---插入 go select * from [maomao365.com] go MERGE INTO [maomao365.com] a USING (SELECT 20 AS keyId_B, 'new Info' AS info_B ) b ON ( a.keyId = b.keyId_B) WHEN MATCHED THEN UPDATE SET a.info= b.info_B --更新 WHEN NOT MATCHED THEN INSERT (info) VALUES(b.info_B); ---插入 go select * from [maomao365.com] go truncate table [maomao365.com] drop table [maomao365.com]
轉自:ide
http://www.maomao365.com/?p=9679sqlserver
相關閱讀:spa
merge關鍵字實現增刪改code