在SQL Server中使用子查詢更新語句
測(cè)試環(huán)境準(zhǔ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、目標(biāo)表在from子句中,目標(biāo)表可以加表別名
----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、目標(biāo)表不在from子句中,目標(biāo)表不能加表別名
---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 --要更新的目標(biāo)表
using #table2 b --源表
on a.id = b.id and a.name is null--更新條件(即主鍵)
when matched --如果匹配,將源表指定列的值更新到目標(biāo)表中
then update set a.name = b.name
when not matched
then insert values ( id, name ); --如果兩個(gè)條件都不匹配,將源表指定列的值插入到目標(biāo)表中。此語句必須以分號(hào)結(jié)束清除測(cè)試數(shù)據(jù)
select * from #table1; select * from #table2; drop table #table1; drop table #table2;
到此這篇關(guān)于在SQL Server中使用子查詢更新語句的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Sql注入原理簡(jiǎn)介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
所謂SQL注入,就是通過把SQL命令插入到Web表單遞交或輸入域名或頁面請(qǐng)求的查詢字符串,最終達(dá)到欺騙服務(wù)器執(zhí)行惡意的SQL命令。下面通過本文給大家分享sql 注入原理解析,感興趣的朋友一起看看吧2017-08-08
sqlserver 觸發(fā)器學(xué)習(xí)(實(shí)現(xiàn)自動(dòng)編號(hào))
前段時(shí)間需要用觸發(fā)器做個(gè)實(shí)現(xiàn)數(shù)據(jù)插入表時(shí)自動(dòng)編號(hào)的功能,于是再學(xué)習(xí)下觸發(fā)器,硬件備份共享于此,以供討論,以免遺忘2012-08-08
SQLServer 數(shù)據(jù)庫變成單個(gè)用戶后無法訪問問題的解決方法
今天不知怎么點(diǎn)錯(cuò)了東西,SQLServer中的一個(gè)數(shù)據(jù)庫變成單用戶了,而且無法訪問,下面是解決方法,有需要的朋友可以參考一下2013-10-10
微信小程序 滾動(dòng)選擇器(時(shí)間日期)詳解及實(shí)例代碼
這篇文章主要介紹了微信小程序 滾動(dòng)選擇器(時(shí)間日期)詳解及實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下2017-02-02
分頁存儲(chǔ)過程(二)在sqlserver中返回更加準(zhǔn)確的分頁結(jié)果
分頁存儲(chǔ)過程(二)在MS SQL Server中返回更加準(zhǔn)確的分頁結(jié)果2010-05-05

