if condition in sql server update query

前端 未结 5 862
日久生厌
日久生厌 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条回答
  •  萌比男神i
    2021-02-01 17:02

    The current answers are fine and should work ok, but what's wrong with the more simple, more obvious, and more maintainable:

    IF @flag = 1
        UPDATE table_name SET column_A = column_A + @new_value WHERE ID = @ID;
    ELSE
        UPDATE table_name SET column_B = column_B + @new_value WHERE ID = @ID;
    

    This is much easier to read albeit this is a very simple query.

    Here's a working example courtesy of @snyder: SqlFiddle.

提交回复
热议问题