![](/img/trans.png)
[英]How to update the values on one column based on the data from other column SQL Server 2014
[英]SQL server - Update one column based on the values of other columns
如果您的列數是固定的,那么您可以使用CASE
語句。
樣本數據
create table data
(
A nvarchar(1),
B nvarchar(1),
C nvarchar(1),
D nvarchar(1),
E nvarchar(10)
);
insert into data (A, B, C, D) values
('Y', 'N', 'Y', 'Y'),
('N', 'N', 'N', 'Y'),
('N', 'Y', 'Y', 'N'),
('Y', 'Y', 'Y', 'N');
解決方案
update d
set d.E = substring(
case d.A when 'Y' then ',A' else '' end
+ case d.B when 'Y' then ',B' else '' end
+ case d.C when 'Y' then ',C' else '' end
+ case d.D when 'Y' then ',D' else '' end,
2, 100)
from data d;
結果
select * from data;
A B C D E
--- --- --- --- -------
Y N Y Y A,C,D
N N N Y D
N Y Y N B,C
Y Y Y N A,B,C
SQL 服務器現在支持CONCAT_WS()
,我建議:
update t
set E = concat_ws(',',
case d.A when 'Y' then 'A' end,
case d.B when 'Y' then 'B' end,
case d.C when 'Y' then 'C' end,
case d.D when 'Y' then 'D' end
);
但是,在可以計算時存儲這些信息似乎很愚蠢 - 並且始終是最新的:
alter table t add E as (concat_ws(',',
case d.A when 'Y' then 'A' end,
case d.B when 'Y' then 'B' end,
case d.C when 'Y' then 'C' end,
case d.D when 'Y' then 'D' end
)
);
計算列在查詢時計算。 它們始終是最新的,無需更新。
update table_name set E='A,C,D' where A='Y' and B='N' and C='Y' and D='Y'
如果您為表設置 id 列,則很容易更新
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.