SQL Server中如何进行子查询
发布时间:2023-12-23 04:27:58 所属栏目:MsSql教程 来源:DaWei
导读: 这篇文章主要介绍了SQL Server中如何进行子查询,并实现更新相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇SQL Server中如何进行子查询,并实现更新文章都会
|
这篇文章主要介绍了SQL Server中如何进行子查询,并实现更新相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇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开窗函数是什么?怎样使用?
- sql-server – 实体框架缓存查询计划性能随着不同参数而降低
- sql中merge函数的用法是什么?
- sql-server – SQL Server ROWLOCK over SELECT如果不存在I
- Python 中支持的数据类型有哪些?
- sql-server-2008 – 错误地在表上运行了更新语句
- sql – Doctrine 2.1其中外键id =?,编辑:在Doctrine 2.2中
- sql-server – 在OVER的窗口函数中使用DISTINCT
- sql-server – 包含要使用文件流的二进制文件的现有表
- 命令行 – 学习SQL艰难的方法 – 在SQL Lite 3中使用.db创建
推荐文章
站长推荐
