2013-01-01 103 views
2

我有一個完美的工作觸發器。正如我在更多的測試中添加的,我發現我想改變這個觸發器來動態地選擇基於當前數據庫的數據庫。在生產中,此觸發器駐留在數據庫rdata中,並與default進行對話。然而在測試中,觸發器駐留於test_rdata並與test_default對話。我如何修改下面的觸發動態地選擇正確的數據庫MySQL更改觸發器以使用動態數據庫名稱

DROP TRIGGER IF EXISTS `af_rdata_data_trigger_4` $$ 
CREATE TRIGGER af_rdata_data_trigger_4 
    AFTER INSERT on Results FOR EACH ROW 
    BEGIN 
     DECLARE project_id INT; 
     -- Do this first - another table may have already created it.. 
     INSERT INTO default.rdata_project (`user`,`result_number`, `created_on`) 
     VALUES (USER(), NEW.LBLDGRUNNO, NOW()) ON DUPLICATE KEY UPDATE last_update=NOW(); 
     -- Now push in our values 

     -- THIS IS WHAT NEEDS TO BE DYNAMIC!! 
     UPDATE default.rdata_project project JOIN Results 
     ON project.result_number = Results.LBLDGRUNNO SET 
      project.annual_total_cost = Results.FTOTCOST 
     WHERE project.result_number=NEW.LBLDGRUNNO; 

    END$$ 
DELIMITER ; 

謝謝了!

回答

0

您可以創建動態選擇使用存儲過程CALL該程序從TRIGGER聲明。請看下面的代碼例如:

DELIMITER $$ 

DROP PROCEDURE IF EXISTS `sp_UpdateProject`$$ 

CREATE PROCEDURE `sp_UpdateProject`(IN _dbName VARCHAR(100), IN _LBLDGRUNNO INT) 
BEGIN 
    SET @s = CONCAT("UPDATE ", _dbName, ".rdata_project project "); 
    SET @s = CONCAT(@s, "JOIN Results ON project.result_number = Results.LBLDGRUNNO "); 
    SET @s = CONCAT(@s, "SET project.annual_total_cost = Results.FTOTCOST "); 
    SET @s = CONCAT(@s, "WHERE project.result_number=", _LBLDGRUNNO,";"); 
    PREPARE stmt FROM @s; 
    EXECUTE stmt; 
    DEALLOCATE PREPARE stmt; 
END$$ 

DELIMITER ; 

DROP TRIGGER IF EXISTS `af_rdata_data_trigger_4` $$ 
CREATE TRIGGER af_rdata_data_trigger_4 
    AFTER INSERT ON Results FOR EACH ROW 
    BEGIN 
     DECLARE project_id INT; 
     -- Do this first - another table may have already created it.. 
     INSERT INTO default.rdata_project (`user`,`result_number`, `created_on`) 
     VALUES (USER(), NEW.LBLDGRUNNO, NOW()) ON DUPLICATE KEY UPDATE last_update=NOW(); 
     -- Now push in our values 

     -- THIS IS WHAT NEEDS TO BE DYNAMIC!! 
     CALL sp_UpdateProject(dbName, NEW.LBLDGRUNNO); 
    END$$ 
DELIMITER ; 
+0

那裏有一個更簡單的方法。真的是這樣嗎?哦,不,謝謝! – rh0dium

+0

您不能在觸發器中使用prepare語句,因此您必須創建存儲過程以生成動態查詢 –

+0

dbName set在哪裏?然後,哪裏得到改變? – rh0dium