Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a IF Statement within a TSQL UPDATE

Tags:

tsql

I want to update two columns in a table. The value of the second column is dependant upon the first; If the first is Null the second's value is 'false', otherwise it is 'true'.
Can I do this within TSQL or do I need to work out the values separately in my code before hand and change the SQL to suit. I was looking for something like:

DECLARE @NewColumnValue as nvarchar(10);
SELECT @NewColumnValue = ColumnY From TableY
UPDATE TableX  
SET Column1 = @NewColumnValue,
Column2 = (IF (@NewColumnValue IS NULL) THEN 'False' ELSE 'True');
like image 455
Anthony K Avatar asked Nov 18 '08 08:11

Anthony K


People also ask

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!

How do you use a case statement in an update query?

The CASE expression allows a statement to return one of several possible results, depending on which of several condition tests evaluates to TRUE. You must include at least one WHEN clause within the CASE expression; subsequent WHEN clauses and the ELSE clause are optional.

How do you update values in a particular column in SQL with conditions?

First, specify the table name that you want to change data in the UPDATE clause. Second, assign a new value for the column that you want to update. In case you want to update data in multiple columns, each column = value pair is separated by a comma (,). Third, specify which rows you want to update in the WHERE clause.

Can we use WHERE with update?

WHERE clause can be used with SQL UPDATE to add conditions while modifying records. Without using any WHERE clause, the SQL UPDATE command can change all the records for the specific columns of the table.


1 Answers

You are looking for the CASE expression:

Column2 = CASE WHEN @NewColumnValue IS NULL THEN 'False' ELSE 'True' END
like image 86
Tomalak Avatar answered Sep 22 '22 12:09

Tomalak