测试环境准备 create table #table1 ( id int , name varchar(20) ); Go create table #t
测试环境准备
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' );
----join连接方式(推荐)
update a
set a.name = b.name
from #table1 a inner join #table2 b on b.id = a.id
where a.name is null;
----或子查询方式
update a
set a.name = ( select b.name from #table2 b where a.id = b.id )
from #table1 a
where a.name is null;
---update … from(推荐)
update #table1
set #table1.name = b.name
from #table2 b
where #table1.id = b.id and #table1.name is null;
--或子查询方式
update #table1
set name = ( select b.name from #table2 b where #table1.id = b.id )
where name is null;
merge #table1 a --要更新的目标表
using #table2 b --源表
on a.id = b.id and a.name is null--更新条件(即主键)
when matched --如果匹配,将源表指定列的值更新到目标表中
then update set a.name = b.name
when not matched
then insert values ( id, name ); --如果两个条件都不匹配,将源表指定列的值插入到目标表中。此语句必须以分号结束
清除测试数据
select * from #table1;
select * from #table2;
drop table #table1;
drop table #table2;
到此这篇关于在SQL Server中使用子查询更新语句的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持编程网。
--结束END--
本文标题: 在SQLServer中使用子查询更新语句
本文链接: https://www.lsjlt.com/news/149193.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0