开发者

INSERT INTO in a CASE statement

I'm wondering if it's possible to have a INSERT INTO statement within a CASE statement in SQL code.

Here's a rough pseudocode of what I'm trying to do:

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


You will need to accomplish with IF...THEN statements instead. Something roughly like this (not sure about syntax for 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;


You could do it two statements like so.

First insert into other when somevalue is null

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

Then left join to both tables on Somevalue being null or not 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 

My guess is that you will actually have to modify the joins to be something like

       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

Note: I'm not sure what the DB2 equivalent of Coalesce is

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜