create table Attributes
(
id int,
AttributeName nvarchar(255),
AttributeValue nvarchar(255)
)
insert into Attributes
values
(1, 'BuiltNo', '001')
,(1, 'ManagerName', 'x')
,(1, 'PlantAddress', 'NY')
,(2, 'BuiltNo', '002')
,(2, 'ManagerName', 'y')
,(2, 'PlantAddress', 'NSW')
,(3, 'BuiltNo', '003')
,(3, 'ManagerName', 'z')
,(3, 'PlantAddress', 'QLD')

我想更新BuiltNo,ManagerName以及PlantAddress在id = 1單個更新查詢中的位置。顯然我們不能where在同一個查詢中有兩個條件,因此尋找不同的解決方案。
update Attributes
set AttributeValue = '*001' where AttributeName = 'BuiltNo' ,
set AttributeValue = '*UpdatedValue' where AttributeName = 'ManagerName'
where id = 1
uj5u.com熱心網友回復:
您可以使用joinonvalues子句來指定要應用的條件和新值,例如:
update Attributes
set AttributeValue = NewAttributeValue
from dbo.Attributes
join (values
(1, 'BuiltNo', '*001'),
(1, 'ManagerName', '*UpdatedValue')
) modifications (id, AttributeName, NewAttributeValue)
on Attributes.id=modifications.id and Attributes.AttributeName=modifications.AttributeName;
產生結果:
| ID | 屬性名 | 屬性值 |
|---|---|---|
| 1 | 已建否 | *001 |
| 1 | 經理姓名 | *更新值 |
| 1 | 廠址 | 紐約 |
| 2 | 已建否 | 002 |
| 2 | 經理姓名 | 是的 |
| 2 | 廠址 | 新南威爾士州 |
| 3 | 已建否 | 003 |
| 3 | 經理姓名 | z |
| 3 | 廠址 | 昆士蘭州 |
uj5u.com熱心網友回復:
只是一個想法,傳遞一個JSON字串
例子
Declare @I int = 1
Declare @J varchar(max) = '{"BuiltNo":"*001","ManagerName":"*UpdatedValue" }'
Update A
set AttributeValue =B.Value
From Attributes A
Join ( Select * from openjson(@J) ) B
On A.id=@I and A.AttributeName=B.[key] collate SQL_Latin1_General_CP1_CI_AS
更新表

uj5u.com熱心網友回復:
用于case when簡單的方法。
UPDATE Attributes
SET AttributeValue = CASE
WHEN AttributeName = 'BuiltNo' THEN '*001'
WHEN AttributeName = 'UpdatedValue' THEN 'ManagerName'
END
WHERE id = 1 and AttributeName IN ('BuiltNo', 'UpdatedValue')
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/528465.html
標籤:sqlsql服务器
下一篇:運行程式時資料庫背景關系為空
