iT邦幫忙

0

sqlserver select cte update 如何一次更新多個表格的欄位資料

sql

我的SQL

create table A (ID int,[Value] varchar(10));
create table B (ID int,A_ID int,Custom_value varchar(10));

with cte as (
	select * from A 
	left join B on A.ID = B.A_ID
	where A.ID = '1111'
)
update cte set [Value] = 'v1',Custom_value='v2'

假如只更新 [Value] 不會出錯,但想同時更新 Custom_value 就會報以下錯誤

Msg 4405, Level 16, State 1, Line 67
視圖或函數 'cte' 不可更新,因為修改會影響多個基表。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
純真的人
iT邦大師 1 級 ‧ 2020-11-19 10:27:56
最佳解答

多個表格更新在T-SQL裡面,當然是分開更新@@...

Declare @ID int = '1111'
Declare @Value1 nvarchar(50) = 'v1'
Declare @Value2 nvarchar(50) = 'v2'

update A
set [Value] = @Value1
where ID = @ID

update B
set Custom_value = @Value2
where A_ID = @ID

我要發表回答

立即登入回答