欢迎来到代码驿站!

MsSql

当前位置:首页 > 数据库 > MsSql

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

时间:2022-10-10 12:51:16|栏目:MsSql|点击:

测试环境准备

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 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子句中,目标表不能加表别名

---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更新

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一个字符串拆分多行显示或者多行数据合并成一个字符串

栏    目:MsSql

下一篇:没有了

本文标题:在SQL Server中使用子查询更新语句

本文地址:http://www.codeinn.net/misctech/215948.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有