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, something like:
UPDATE table_Name SET CASE WHEN @flag = '1' THEN column_A += @new_value WHEN @flag = '0' THEN column_B += @new_value END AS Total WHERE ID = @ID
What is the correct SQL server code to do so??
To do a conditional update depending on whether the current value of a column matches the condition, you can add a WHERE clause which specifies this. The database will first find rows which match the WHERE clause and then only perform updates on those rows.
Yes! This works because MySQL doesn't update the row, if there is no change, as mentioned in docs: If you set a column to the value it currently has, MySQL notices this and does not update it. Yes!
Any T-SQL statement can be executed conditionally using IF… ELSE. If the condition evaluates to True, then T-SQL statements followed by IF condition in SQL server will be executed. If the condition evaluates to False, then T-SQL statements followed by ELSE keyword will be executed.
Something like this should work:
UPDATE table_Name SET column_A = CASE WHEN @flag = '1' THEN column_A + @new_value ELSE column_A END, column_B = CASE WHEN @flag = '0' THEN column_B + @new_value ELSE column_B END WHERE ID = @ID
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With