2011-05-13 136 views
7

我想知道是否有可能在SQL代碼中的CASE語句中具有INSERT INTO語句。在CASE語句中插入

這裏是什麼,我試圖做一個粗略的僞代碼:

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 

回答

9

您將需要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; 
+0

這就是問題所在。我不確定如何在DB2 – Connection 2011-05-13 19:21:21

+0

中複製類似的東西。從文檔開始?我已經爲您的代碼提供了一個合理的結構來完成您要做的事情。您可以深入瞭解確切語法的細節。我知道這個結構可以在SQL Server或MySql中工作。 – mellamokb 2011-05-13 19:22:59

0

你可以做到這一點的兩個語句,像這樣。

先插入到othersomevalue is null

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

然後左連接到兩個表上Somevaluenullnot 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 

注意:我不確定Coalesce的DB2等價物是