小编典典

在CASE语句中插入INTO

sql

我想知道是否有可能在SQL代码的CASE语句中包含INSERT INTO语句。

这是我要执行的操作的粗略伪代码:

SELECT (CASE (SELECT SomeValue FROM SomeTable)
            WHEN NULL THEN
                INSERT INTO OtherTable VALUES (1, 2, 3)
                (SELECT NewlyInsertedValue FROM OtherTable)
            ELSE
                (SELECT SomeOtherValue FROM WeirdTable)
        END),
       Column1,
       Column2
FROM BigTable

阅读 36

收藏
2021-04-07

共1个答案

小编典典

您将需要用IF...THEN语句代替。大概是这样的(不确定db2的语法):

SELECT @SomeValue = SomeValue FROM SomeTable

IF @SomeValue IS NULL
    INSERT INTO OtherTable VALUES (1, 2, 3)
    SELECT NewlyInsertedValue FROM OtherTable;
ELSE
    INSERT INTO OtherTable VALUES (1, 2, 3)
    SELECT SomeOtherValue FROM WeirdTable;
END IF;
2021-04-07