SQL INSERT(select)使用基于另一列值的CASE

时间:2011-08-16 13:44:18

标签: sql sql-server tsql

我有一个警报触发器,如果​​该警报触发器= 1,我希望另一列的值为NULL。出于示例目的,我将创建一个简单的表格,说明我要解释的内容。

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

1 个答案:

答案 0 :(得分:7)

您没有正确结束案例陈述。此外,括号是不必要的,并防止传递多个值。以下是您修改的示例代码:

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