MSSQL 插入数据时候,如果存在则更新的方法分享
程序员文章站
2022-05-04 13:05:14
摘要:下文讲述MSSQL中,插入数据时,如果存在则更新,否则就插入数据的方法分享实验环境:sql server 2017 mssql中,我们可以采用 MERGE INTO 关键字实现此功能,当两者匹配成功,则运行***语句,否则运行其它语句,达到插入数据时的判断操作,具体操作方法如下所示: 转自: ......
摘要:
下文讲述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]
转自:
相关阅读: