简体   繁体   中英

UPDATE Multiple columns Using CASE in SQL Server 2008

I have the following SQL statement:

 update data 
  set [sub_st_pc]= 
    case 
          when [R 6] is not null  then [R 6] 
      when [R 5] is not null  then [R 5]
      when [R 4] is not null  then [R 4]
      when [R 3] is not null  then [R 3]
      when [R 2] is not null  then [R 2]
      else sub_st_pc
    end

but I need to update another column according to each when, something like this:

 when [R 6] is not null  then [R 6], [temp] = 6
 when [R 5] is not null  then [R 5], [temp] = 5

which I know it's wrong.

Any ideas?

You can use COALESCE to make setting the first column easier. You'll need a separate CASE statement to set [temp] , and COALESCE won't help you there.

update data 
set [sub_st_pc]= COALESCE([R 6], [R 5], [R 4], [R 3], [R 2], [sub_st_pc]),
    [temp] = case 
               when [R 6] is not null  then 6 
               when [R 5] is not null  then 5
               when [R 4] is not null  then 4
               when [R 3] is not null  then 3
               when [R 2] is not null  then 2
               else NULL
             end
update data 
  set [col1]= case when [R1] is not null  then [R1] else [col1] end,
      [col2]= case when [R2] is not null  then [R2] else [col2] end,
       .....

Your question is not clear. Just write an update statement similar to what you wrote for one column, but for many columns, eg

update Data
set Col1 = case when Col2 is not null then col2 else Col1 end,
Col2 = case when Col3 is not null then Col3 else Col2 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