SQL INSERT (select) using CASE based on a different column value

I have an alarm trigger, and if this alarm trigger = 1, I want the value of the other column to be NULL. For example, I will create a simple table of what I'm trying to explain.

DECLARE @tmp TABLE ( ID INT, Value1 FLOAT, V1_Alarm BIT, Value2 FLOAT, V2_Alarm BIT) INSERT INTO @tmp SELECT ( ID, CASE WHEN V1_Alarm = 1 THEN NULL ELSE Value1, V1_Alarm, CASE WHEN V2_Alarm = 1 THEN NULL ELSE Value2 ) FROM SomeTable 
+4
source share
1 answer

You are not completing your case statements properly. In addition, parentheses are not needed and prevent multiple values ​​from being passed. Here is your sample code modified:

 DECLARE @tmp TABLE ( ID INT, Value1 FLOAT, V1_Alarm BIT, Value2 FLOAT, V2_Alarm BIT) INSERT INTO @tmp SELECT ID, CASE WHEN V1_Alarm = 1 THEN NULL ELSE Value1 END, V1_Alarm, CASE WHEN V2_Alarm = 1 THEN NULL ELSE Value2 END FROM SomeTable 
+6
source

All Articles