if condition in sql server update query

前端 未结 5 801
日久生厌
日久生厌 2021-02-01 16:29

I have a SQL server table in which there are 2 columns that I want to update either of their values according to a flag sent to the stored procedure along with the new value, so

5条回答
  •  野性不改
    2021-02-01 17:08

    Since you're using SQL 2008:

    UPDATE
        table_Name
    
    SET
        column_A  
         = CASE
            WHEN @flag = '1' THEN @new_value
            ELSE 0
        END + column_A,
    
        column_B  
         = CASE
            WHEN @flag = '0' THEN @new_value
            ELSE 0
        END + column_B 
    WHERE
        ID = @ID
    

    If you were using SQL 2012:

    UPDATE
        table_Name
    SET
        column_A  = column_A + IIF(@flag = '1', @new_value, 0),
        column_B  = column_B + IIF(@flag = '0', @new_value, 0)
    WHERE
        ID = @ID
    

提交回复
热议问题