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


摘要:
下文讲述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]

相关阅读:
merge关键字实现增删改