2013-10-08 71 views
1

請解決我的查詢 Case語句

create trigger DeleteProduct 
Before delete on Product 
BEGIN 
    select CASE WHEN ((SELECT Inventory.InventoryID FROM Inventory WHERE Inventory.ProductID = OLD.ProductID and Inventory.Quantity=0) ISNULL) 
    THEN  
      RAISE(ABORT,'Error code 82') 
    Else 
      DELETE from inventory where inventory.ProductID=OLD.ProductID; 
    END; 

END; 

ERROR近DELETE語句

+0

你確定你需要這個觸發?你可以通過外鍵約束中的'on delete cascade'獲得期望的行爲嗎? – SingleNegationElimination

回答

2

你不能把如下語句DELETE成像CASE這樣的表達。

在一般情況下,你可以通過觸發使用條件的WHEN clause

CREATE TRIGGER DeleteProductError 
BEFORE DELETE ON Product 
WHEN NOT EXISTS (SELECT InventoryID 
       FROM Inventory 
       WHERE ProductID = OLD.ProductID 
        AND Quantity = 0) 
BEGIN 
    SELECT RAISE(ABORT, 'Error code 82'); 
END; 

CREATE TRIGGER DeleteProduct 
BEFORE DELETE ON Product 
WHEN EXISTS (SELECT InventoryID 
      FROM Inventory 
      WHERE ProductID = OLD.ProductID 
       AND Quantity = 0) 
BEGIN 
    DELETE FROM Inventory 
    WHERE ProductID = OLD.ProductID; 
END; 
+0

這個答案解決了我的問題。但我想如果其他與查詢。如果火災刪除查詢否則如果火災更新查詢其他火災刪除查詢.. – Chaitanya

+0

SQLite沒有if/else。通過使用複雜的'WHERE'條件,可以構建一個巧妙的語句序列(請參閱LS_dev的回答者),但SQLite是一個嵌入式數據庫,並不旨在執行可以在主機編程語言。 –

1

試試這個:

CREATE TRIGGER DeleteProduct 
BEFORE DELETE ON Product 
BEGIN 
    SELECT CASE WHEN (SELECT Inventory.InventoryID FROM Inventory WHERE Inventory.ProductID = OLD.ProductID and Inventory.Quantity=0) IS NULL 
    THEN RAISE(ABORT,'Error code 82') 
    END; 
    -- If RAISE was called, next isntructions are not executed. 
    DELETE from inventory where inventory.ProductID=OLD.ProductID; 
END;