INSERT INTO in a CASE statement

后端 未结 2 1185
再見小時候
再見小時候 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条回答
  • 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

    0 讨论(0)
  • 2021-01-18 04:16

    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;
    
    0 讨论(0)
提交回复
热议问题