MSSQL 插入数据时候,如果存在则更新的方法分享

匿名 (未验证) 提交于 2019-12-03 00:05:01


ժҪ:
下文讲述MSSQL中,插入数据时,如果存在则更新,否则就插入数据的方法分享
实验环境:sql server 2017 
mssql中,我们可以采用 MERGE INTO 关键字实现此功能,
当两者匹配成功,则运行***语句,否则运行其它语句,达到插入数据时的判断操作,
具体操作方法如下所示: 

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]

转自:

 http://www.maomao365.com/?p=9679

相关阅读:

merge关键字实现增删改

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!