SQLServer(00):根据子查询更新语句(update…from)

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

SQLServer(00):根据⼦查询更新语句(update…from)测试环境准备
create table #table1
( id int , name varchar(20) );
go
create table #table2
( id int , name varchar(20) );
go
insert into #table1 ( id, name ) values ( 1, 'a' ), ( 2, null ), ( 3, 'c' ), ( 4, 'd' ), ( 5, 'e' );
insert into #table2 ( id, name ) values ( 1, 'a1' ), ( 2, 'b1' ), ( 3, 'c1' );
1、⽬标表在from⼦句中,⽬标表可以加表别名
----join连接⽅式(推荐)
update a
set =
from #table1 a inner join #table2 b on b.id = a.id
where is null;
----或⼦查询⽅式
update a
set = ( select from #table2 b where a.id = b.id )
from #table1 a
where is null;
2、⽬标表不在from⼦句中,⽬标表不能加表别名
---update … from(推荐)
update #table1
set # =
from #table2 b
where #table1.id = b.id and # is null;
--或⼦查询⽅式
update #table1
set name = ( select from #table2 b where #table1.id = b.id )
where name is null;
3、merge更新
merge #table1 a --要更新的⽬标表
using #table2 b --源表
on a.id = b.id and is null--更新条件(即主键)
when matched --如果匹配,将源表指定列的值更新到⽬标表中
then update set =
when not matched
then insert values ( id, name ); --如果两个条件都不匹配,将源表指定列的值插⼊到⽬标表中。

此语句必须以分号结束清除测试数据
select*from #table1;
select*from #table2;
drop table #table1;
drop table #table2;。

相关文档
最新文档