简体   繁体   中英

Update Table/T-SQL

I have a table with 5 columns. 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. Also, if 1st and 2nd columns are null, I want to add "C1, C2" to 5th column and so on. 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 .

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:

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.

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.

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,
'><',''),'<>',',')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM