更新多列在SQL Server 2008中使用CASE

时间:2013-01-15 21:40:08

标签: sql sql-server-2008

我有以下SQL语句:

 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

但我需要根据每个时间更新另一列,如下所示:

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

我知道这是错的。

有什么想法吗?

3 个答案:

答案 0 :(得分:2)

您可以使用COALESCE更轻松地设置第一列。您需要单独的CASE声明来设置[temp],而COALESCE不会帮助您。

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

答案 1 :(得分:1)

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,
       .....

答案 2 :(得分:1)

你的问题不明确。只需编写一个类似于您为一列编写的更新语句,但对于许多列,例如

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