快速备份表 saleDetail
使用select into 可以快速创建表并将表数据同时插入新建表中
1 |
|
备份表数据还原,使用insert into 插入数据
1 | insert into [saleDetail] |
sqlserver 数据插入,若存在则更新,若没有则进行插入
1 |
|
merge into 目标表 a
using 源表 b
on a.条件字段1=b.条件字段1 and a.条件字段2=b.条件字段2 …
when matched update set a.字段1=b.字段1,
a.字段2=b.字段2
when not matched insert values (b.字段1,b.字段2)
when not matched by source
then delete
1 | 例子: |
create table targetTable(ID INT primary key identity(1,1),[name] varchar(50),age int)
create table sourceTable(ID INT primary key identity(1,1),[name] varchar(50),age int)
insert into targetTable([name],age) values(‘大卫’,40)
merge into targetTable as t
using sourceTable as S on t.ID=s.ID
when matched –更新 目标表中有ID,则更新
then update set t.[name]=S.[name]
when not matched –添加 目标表中没有ID,在原表中有,则插入相关数据
then insert values (s.[name],s.age)
when not matched by source –目标表存在,源表不存在,则删除
then delete;
```