首页 > 数据库 > mssqlserver

sql sqlserver实现类似mysql中replace into功能

发布时间:2021-3-11 17:46

replace into 跟 insert 功能类似,不同点在于:replace into 首先尝试插入数据到表中 1、如果发现表中已经有此行数据(根据主键或者唯一索引判断)则先删除此行数据,然后插入新的数据。 2、 否则,直接插入新数据。


直接上代码

/*
MySQL
replace into 跟 insert 功能类似,不同点在于:replace into 首先尝试插入数据到表中
1、如果发现表中已经有此行数据(根据主键或者唯一索引判断)则先删除此行数据,然后插入新的数据。
2、 否则,直接插入新数据。
*/
Replace into table(id, update_time) values(1, now())

/*
MSSQL(2008+)
判断t_B记录在T_A就更新,否则就插入
*/
Merge Into table As a 
Using (select 1 As id,getdate() As update_time) as b  on a.id=b.id 
When Matched then 
    update set a.update_time=b.update_time
When Not Matched then 
    Insert(id,update_time) values(b.id,b.update_time);
     
--MySQL的
Replace into Table(id, update_time) 
    Select id,update_time From Other

--MSSQL的
Merge Into Table As a 
Using (Select id,update_time From Other) as b  on a.id=b.id 
When Matched then 
    update set a.update_time=b.update_time
When Not Matched then 
    Insert(id,update_time) values(b.id,b.update_time);


标签:[!--infotagslink--]

您可能感兴趣的文章: