在TSQL更新中使用IF语句。

时间:2021-06-07 09:26:04

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:

我想更新表中的两列。第二列的值依赖于第一个列;如果第一个是Null,第二个值是“false”,否则它是“true”。我可以在TSQL中做这个吗?或者我需要在我的代码中单独算出这些值,然后将SQL修改为suit。我在寻找类似的东西:

DECLARE @NewColumnValue as nvarchar(10);
SELECT @NewColumnValue = ColumnY From TableY
UPDATE TableX  
SET Column1 = @NewColumnValue,
Column2 = (IF (@NewColumnValue IS NULL) THEN 'False' ELSE 'True');

1 个解决方案

#1


17  

You are looking for the CASE expression:

您正在寻找案例表达式:

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

#1


17  

You are looking for the CASE expression:

您正在寻找案例表达式:

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