SQL Server中如何进行子查询,并实现更新
Admin 2022-08-02 群英技术资讯 934 次浏览
测试环境准备
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进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
这篇文章介绍了SQL Server的全文搜索功能,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
这篇文章主要为大家介绍了SQL Server的触发器,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
这篇文章介绍了SQL将一个表中的数据插入到另一个表中的方法,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
这篇文章主要介绍了Windows环境下实现批量执行Sql文件的相关资料,需要的朋友可以参考下
这篇文章介绍了SQL Server中的格式转换函数Cast、Convert,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008