2

我有一个完美的工作触发器。随着我添加更多测试,我发现我想更改此触发器以根据当前数据库动态选择数据库。在生产中,此触发器驻留在数据库中rdata并与default. 但是在测试中,触发器驻留在test_rdata并与test_default. 如何修改以下触发器以动态选择正确的数据库

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 ;

非常感谢!

4

1 回答 1

0

您可以使用STORED PROCEDURE创建动态SELECT语句,并从您的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 ;
于 2013-01-01T05:26:45.597 回答