有可能编写一个脚本来自动生成每个sql触发器吗?

时间:2016-02-25 02:18:01

标签: mysql sql triggers scripting

我必须为我服务器中的每个表创建触发器。例如,这三个触发器将用于我的员工:

DELIMITER $$
DROP TRIGGER IF EXISTS auditemployees_insert$$
CREATE TRIGGER auditemployees_insert AFTER INSERT ON employees

FOR EACH ROW
BEGIN
INSERT INTO employees_trigger (emp_no, birth_date, first_name, last_name, gender, hire_date) SELECT emp_no, birth_date, first_name, last_name, gender, hire_date FROM employees WHERE emp_no = NEW.emp_no;
END$$

DROP TRIGGER IF EXISTS auditemployees_delete$$
CREATE TRIGGER auditemployees_delete BEFORE DELETE ON employees

FOR EACH ROW
BEGIN
INSERT INTO employees_trigger (emp_no, birth_date, first_name, last_name, gender, hire_date) SELECT emp_no, birth_date, first_name, last_name, gender, hire_date FROM employees WHERE emp_no = OLD.emp_no;
END$$

DROP TRIGGER IF EXISTS auditemployees_update$$
CREATE TRIGGER auditemployees_update BEFORE UPDATE ON employees

FOR EACH ROW
BEGIN
INSERT INTO employees_trigger (emp_no, birth_date, first_name, last_name, gender, hire_date) SELECT emp_no, birth_date, first_name, last_name, gender, hire_date FROM employees WHERE emp_no = NEW.emp_no;
END$$


DELIMITER ;

问题是:

我可以使用哪种脚本/语言为每个表生成这些触发器?

甚至可能吗?

1 个答案:

答案 0 :(得分:1)

是可以的,你需要通过两个表声明一个游标。

 select * from information_schema.tables;
select * from information_schema.columns

然后查询information_schema.columns以获取列名称,用于将创建触发器sql组成字符串

这是我的更新,但您需要更正结果集上的一些语法: 最重要的是学习如何使用information_schema.columns表连接列名和查询表模式

返回结果集作为sql语句后,复制并运行这些脚本。

SELECT 
    CONCAT('DROP TRIGGER IF EXISTS auditemployees_insert;
            CREATE TRIGGER audit',
            table_name,
            '_insert AFTER INSERT ON ',
            table_name,
            '
            
            FOR EACH ROW
            BEGIN
            INSERT INTO ',
            table_name,
            '_trigger (',
            GROUP_CONCAT(CONCAT('`', column_name, '`')
                SEPARATOR ','),
            ') SELECT ',
            GROUP_CONCAT(CONCAT('`', column_name, '`')
                SEPARATOR ','),
            ' FROM ',
            table_name,
            ' WHERE id = NEW.id;
            END$$')
FROM
    information_schema.columns
WHERE
    table_name IN ('roles' , 'users', 'news')
GROUP BY table_name