日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 综合教程 >内容正文

综合教程

SQL Server根据子查询更新语句update

發布時間:2023/12/31 综合教程 33 生活家
生活随笔 收集整理的這篇文章主要介紹了 SQL Server根据子查询更新语句update 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

SQL Server(00):根據子查詢更新語句(update … from)

目錄

1、目標表在from子句中,目標表可以加表別名
2、目標表不在from子句中,目標表不能加表別名
3、merge更新


測試環境準備

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根据子查询更新语句update的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。