![](/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.