[英]Update Table/T-SQL
I have a table with 5 columns. 我有一个5列的表格。 I want to update 5th column (NULL by default) based on values in columns 1 to 4. If 1st column is null, Add "c1" to 5th column If 2nd column is null, add "c2" to the 5th column and so on. 我想基于第1到第4列中的值更新第5列(默认情况下为NULL)。如果第1列为空,则将“ c1”添加到第5列中。如果第2列为空,则将“ c2”添加到第5列中,依此类推。 。 Also, if 1st and 2nd columns are null, I want to add "C1, C2" to 5th column and so on. 另外,如果第一和第二列为空,我想在第五列添加“ C1,C2”,依此类推。 How can I achieve that. 我该如何实现。
Here is what I have tried so far: 到目前为止,这是我尝试过的:
UPDATE TABLE
SET C5 =
Case
when C1 IS NULL then 'C!'
WHEN C2 IS NULL then 'C2'
WHEN C3 IS NULL THEN 'C3'
WHEN C4 IS NULL ThEN 'C4'
END
I would use this: 我会用这个:
UPDATE table
SET C5 = ISNULL(REPLACE(C1,C1,''),',C1')
+ISNULL(REPLACE(C2,C2,''),',C2')
+ISNULL(REPLACE(C3,C3,''),',C3')
+ISNULL(REPLACE(C4,C4,''),',C4')
etc. 等等
The idea is that you use REPLACE
to leave you with blank '' or NULL
, then use ISNULL
to add the field name if NULL
. 这个想法是,您使用REPLACE
留空''或NULL
,然后使用ISNULL
来添加字段名称(如果为NULL
。
You could craft the query in Excel pretty quickly, it will leave one errant comma at the end of the string, if that's a problem it can be easily dealt with: 您可以很快地在Excel中编写查询,它将在字符串的末尾留下一个错误的逗号,如果存在问题,可以很容易地解决:
UPDATE table
SET C5 = STUFF(ISNULL(REPLACE(C1,C1,''),',C1 ')
+ISNULL(REPLACE(C2,C2,''),',C2 ')
+ISNULL(REPLACE(C3,C3,''),',C3 ')
+ISNULL(REPLACE(C4,C4,''),',C4 '),1,2,'')
Update: Changed to using STUFF() function instead of LEFT() to eliminate errant comma, and added a space between listed items. 更新:更改为使用STUFF()函数而不是LEFT()来消除错误的逗号,并在列出的项目之间添加了一个空格。
UPDATE tbl
SET fifth = CASE
WHEN first IS NULL AND second IS NULL and third IS NULL and fourth IS NULL THEN "C1, C2, C3, C4"
WHEN .... -- all 15 cases
I haven't tested it but something like this should work: 我还没有测试过,但是类似的东西应该可以工作:
update table1 set c5 =
(case when c1 is null then 'C1,' else '' end ||
case when c2 is null then 'C2,' else '' end ||
case when c3 is null then 'C3,' else '' end ||
case when c4 is null then 'C4' else '' end)
I leave the exercise of trimming the trailing comma, if needed, to someone better at t-sql string manipulation. 如果需要,我将修剪尾随逗号的练习留给了精通t-sql字符串操作的人。
UPDATE t SET C5 =
REPLACE(REPLACE(
CASE C1 WHEN NULL THEN 'C1' ELSE '' END+'<>'+
CASE C2 WHEN NULL THEN 'C2' ELSE '' END+'<>'+
CASE C3 WHEN NULL THEN 'C3' ELSE '' END+'<>'+
CASE C4 WHEN NULL THEN 'C4' ELSE '' END,
'><',''),'<>',',')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.