INSERT INTO in a CASE statement

后端 未结 2 1204
再見小時候
再見小時候 2021-01-18 03:23

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:



        
2条回答
  •  萌比男神i
    2021-01-18 04:05

    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

提交回复
热议问题