A  B  C  D
1  2  0  2
1  2  2  1
1  2  2  3
update table set A =5,B=5,C=5 where D =2这里我想更新三列 ,但是如果C列的值为0 时只更新AB两列。请问这条语句该怎么写?

解决方案 »

  1.   

    update table 
    set 
    a = 5,
    b = 5,
    c = (case when c = 0 then c else 5 end)
    where d = 2
      

  2.   


    update table set A =5,B=5,C=case when c = 0 then c else 5 end where D =2
      

  3.   

    不知道你要下面的哪个?
    create table tb(A int,B int,C int,D int)
    insert into tb values(1 ,2 ,0 ,2)
    insert into tb values(1 ,2 ,2 ,1)
    insert into tb values(1 ,2 ,2 ,3)
    goupdate tb
    set  
    a = 5,
    b = 5,
    c = (case when c = 0 then c else 5 end)
    where d = 2 
     
    select * from tb
    /*
    A           B           C           D           
    ----------- ----------- ----------- ----------- 
    5           5           0           2
    1           2           2           1
    1           2           2           3(所影响的行数为 3 行)
    */
    drop table tbcreate table tb(A int,B int,C int,D int)
    insert into tb values(1 ,2 ,0 ,2)
    insert into tb values(1 ,2 ,2 ,1)
    insert into tb values(1 ,2 ,2 ,3)
    goupdate tb
    set  
    a = 5,
    b = 5,
    c = (case when c = 0 then c else 5 end) 
    select * from tb
    /*
    A           B           C           D           
    ----------- ----------- ----------- ----------- 
    5           5           0           2
    5           5           5           1
    5           5           5           3(所影响的行数为 3 行)*/
    drop table tb
      

  4.   

    恩,用case ... when ...end 语句很好,忘了mssql是否能用decode语句,oracle里我常用