Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if condition in sql server update query

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??

like image 702
MA9H Avatar asked Sep 08 '13 10:09

MA9H


People also ask

How do you UPDATE values based on conditions in SQL?

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.

Can we use if statement in UPDATE query?

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!

Can we use if condition in SQL query?

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.


2 Answers

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 
like image 54
Joachim Isaksson Avatar answered Sep 25 '22 17:09

Joachim Isaksson


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.

like image 23
Paul Fleming Avatar answered Sep 23 '22 17:09

Paul Fleming