在SQL Server中使用子查詢更新語句
測試環(huán)境準備
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 ); --如果兩個條件都不匹配,將源表指定列的值插入到目標表中。此語句必須以分號結(jié)束
清除測試數(shù)據(jù)
select * from #table1; select * from #table2; drop table #table1; drop table #table2;
到此這篇關(guān)于在SQL Server中使用子查詢更新語句的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SqlServer生成連續(xù)數(shù)字根據(jù)指定的數(shù)字操作
這篇文章主要介紹了SqlServer生成連續(xù)數(shù)字根據(jù)指定的數(shù)字操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10安裝sql server2008后再安裝sql 2005找不到本地服務(wù)器的解決方法
這篇文章主要介紹了安裝sql server2008后再安裝sql 2005找不到本地服務(wù)器的解決方法,需要的朋友可以參考下2015-01-01MSSQL批量替換語句 在SQL SERVER中批量替換字符串的方法
在SQL SERVER中批量替換字符串的方法2010-04-04sqlserver數(shù)據(jù)庫使用存儲過程和dbmail實現(xiàn)定時發(fā)送郵件
這篇文章主要介紹了sqlserver數(shù)據(jù)庫存儲過程和Job實現(xiàn)定時從數(shù)據(jù)庫發(fā)送郵件的功能,大家參考使用吧2014-01-01sqlserver清空service broker中的隊列的語句分享
在我們開發(fā)service broker應用時候,可能用于測試或者客戶端沒有配置正確等導致服務(wù)端隊列存在很多垃圾隊列,不便于我們排查錯誤,我們可以使用SQL腳本來清空服務(wù)端這些垃圾數(shù)據(jù)2011-08-08利用腳本自動安裝SQLServer的實現(xiàn)步驟分析
在工作中,經(jīng)常被要求一天安裝個10臺、8臺的SQL Server。2010-11-11SQL Server日期時間加減函數(shù)(DATEDIFF、DateAdd)的使用
日期時間是常用的函數(shù),本文主要介紹了SQL Server日期時間加減函數(shù)(DATEDIFF、DateAdd)的使用,感興趣的可以了解一下2023-10-10