服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - Sql Server - 在SQL Server中使用子查询更新语句

在SQL Server中使用子查询更新语句

2022-09-16 17:14springsnow Sql Server

这篇文章介绍了在SQL Server中使用子查询更新语句的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

测试环境准备

?
1
2
3
4
5
6
7
8
9
10
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子句中,目标表可以加表别名

?
1
2
3
4
5
6
7
8
9
10
11
----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;

2、目标表不在from子句中,目标表不能加表别名

?
1
2
3
4
5
6
7
8
9
10
---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;

3、merge更新

?
1
2
3
4
5
6
7
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 ); --如果两个条件都不匹配,将源表指定列的值插入到目标表中。此语句必须以分号结束

清除测试数据

?
1
2
3
4
5
select * from #table1;
select * from #table2;
 
drop table #table1;
drop table #table2;

到此这篇关于在SQL Server中使用子查询更新语句的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/springsnow/p/9592758.html

延伸 · 阅读

精彩推荐