在多个触发器中使用存储过程

时间:2013-04-16 19:33:48

标签: mysql sql stored-procedures triggers

除了notes表之外,我将这个相同的触发器应用于大约15个其他表。不确定,但似乎存储过程将消除重复的代码。这是一个存储过程的好应用程序吗?如果是这样,它怎么可能实现?

CREATE TRIGGER tg_notes_ins BEFORE INSERT ON notes FOR EACH ROW
BEGIN
    IF NEW.created_by_user IS NULL OR NEW.created_by_user = '' THEN
        SET NEW.created_by_user = @users_id;
    END IF;
    IF NEW.modified_by_user IS NULL OR NEW.modified_by_user = '' THEN
        SET NEW.modified_by_user = @users_id;
    END IF;
END$$

CREATE TRIGGER tg_notes_upd BEFORE UPDATE ON notes FOR EACH ROW
BEGIN
    IF NEW.modified_by_user = OLD.modified_by_user THEN
        SET NEW.modified_by_user = @users_id;
    END IF;
END$$

1 个答案:

答案 0 :(得分:0)

我并不是说这是怎么做的,但它似乎有用,并且会欣赏任何意见。感谢

DELIMITER $$

CREATE PROCEDURE `createRecord` ()
BEGIN
    IF NEW.created_by_user IS NULL OR NEW.created_by_user = '' THEN
        SET NEW.created_by_user = @users_id;
    END IF;
    IF NEW.modified_by_user IS NULL OR NEW.modified_by_user = '' THEN
        SET NEW.modified_by_user = @users_id;
    END IF;
END$$

CREATE PROCEDURE `modifyRecord` ()
BEGIN
    IF NEW.modified_by_user = OLD.modified_by_user THEN
        SET NEW.modified_by_user = @users_id;
    END IF;
END$$

CREATE TRIGGER tg_notes_upd BEFORE UPDATE ON notes FOR EACH ROW
BEGIN
    CALL createRecord();
END$$

CREATE TRIGGER tg_notes_ins BEFORE INSERT ON notes FOR EACH ROW
BEGIN
    CALL modifyRecord();
END$$

DELIMITER ;