db2 在CASE语句中插入INTO

eni9jsuy  于 2022-11-07  发布在  DB2
关注(0)|答案(2)|浏览(293)

我想知道是否可以在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
pbgvytdp

pbgvytdp1#

您需要使用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;
3qpi33ja

3qpi33ja2#

你可以这样做两个语句。
somevalue is null时首先插入other

INSERT INTO othertable 
SELECT 1, 
       2, 
       3 
FROM   bigtable 
WHERE  somevalue IS NULL;

然后左联接到Somevalue上的两个表,nullnot null

SELECT Coalesce(othertable.newlyinsertedvalue, weirdtable.someothervalue) foo, 
       column1, 
       column2 
FROM   bigtable 
       LEFT OUTER JOIN othertable 
         ON somevalue IS NULL 
       LEFT OUTER JOIN weirdtable 
         ON somevalue IS NOT NULL

我猜您实际上必须将连接修改为类似于

LEFT OUTER JOIN othertable 
         ON somevalue IS NULL 
           and bigtable.id = othertable.id
       LEFT OUTER JOIN weirdtable 
         ON somevalue IS NOT NULL 
           and bigtable.id = weirdtable .id

注意:我不确定在DB2中Coalesce的等价物是什么

相关问题