在SQL Server中使用子查询更新语句
更新时间:2022年05月19日 14:04:46 作者:springsnow
这篇文章介绍了在SQL Server中使用子查询更新语句的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
测试环境准备
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中使用子查询更新语句的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
安装sql server2008后再安装sql 2005找不到本地服务器的解决方法
这篇文章主要介绍了安装sql server2008后再安装sql 2005找不到本地服务器的解决方法,需要的朋友可以参考下2015-01-01MSSQL批量替换语句 在SQL SERVER中批量替换字符串的方法
在SQL SERVER中批量替换字符串的方法2010-04-04sqlserver数据库使用存储过程和dbmail实现定时发送邮件
这篇文章主要介绍了sqlserver数据库存储过程和Job实现定时从数据库发送邮件的功能,大家参考使用吧2014-01-01sqlserver清空service broker中的队列的语句分享
在我们开发service broker应用时候,可能用于测试或者客户端没有配置正确等导致服务端队列存在很多垃圾队列,不便于我们排查错误,我们可以使用SQL脚本来清空服务端这些垃圾数据2011-08-08SQL Server日期时间加减函数(DATEDIFF、DateAdd)的使用
日期时间是常用的函数,本文主要介绍了SQL Server日期时间加减函数(DATEDIFF、DateAdd)的使用,感兴趣的可以了解一下2023-10-10
最新评论