SQL Server中如何进行子查询,并实现更新
Admin 2022-08-02 群英技术资讯 771 次浏览
测试环境准备
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;
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
前言上一篇我们研究了如何利用索引在数据库里面调优,简要的介绍了索引的原理,更重要的分析了如何选择索引以及索引的利弊项,有兴趣的可以点击查看。本篇延续上一篇的...
在数据查询中,从2008开始SQLServer提供了一个新的数据类型hierarchyid,专门用来操作层次型数据结构。hierarchyid 类型对层次结构树中有关单个节点的信息进行逻...
MySQL8.0版本之后,加入了窗口函数功能,简化了数据分析工作中查询语句的书写。本文主要介绍了SQL窗口函数的使用方法,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
这篇文章主要介绍了SQL Server中避免触发镜像SUSPEND的N种方法,需要的朋友可以参考下
NOW() 函数返回当前系统的日期和时间,有不少朋友对于NOW函数比较感兴趣,下面小编给大家整理和分享了相关知识和资料,易于大家学习和理解,有需要的朋友可以借鉴参考,下面我们一起来了解一下吧。
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008