SQL Server(00):根据子查询更新语句(update … from)
测试环境准备
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;
posted on 2018-09-05 16:13 springsnow 阅读(8376) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通