Anthony K
Anthony K

Reputation: 2603

Using a IF Statement within a TSQL UPDATE

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');

Upvotes: 13

Views: 27699

Answers (1)

Tomalak
Tomalak

Reputation: 338148

You are looking for the CASE expression:

Column2 = CASE WHEN @NewColumnValue IS NULL THEN 'False' ELSE 'True' END

Upvotes: 32

Related Questions