如果列的名称存储在触发器内的变量中,如何获取列的值?

时间:2018-02-14 14:12:46

标签: mysql sql database-trigger

更新数据库表中的数据时,我需要写一个单独的表:表名,更改日期,旧列值,新列值。

我写了触发器

CREATE TRIGGER `user_update_trigger`
AFTER UPDATE ON `users`
FOR EACH ROW
BEGIN

DECLARE done int default false;
DECLARE col_name CHAR(255);

DECLARE counter INTEGER(11);

DECLARE column_cursor cursor for SELECT `column_name`
                        FROM `INFORMATION_SCHEMA`.`COLUMNS` 
                        WHERE `TABLE_SCHEMA`='test' 
                        AND `TABLE_NAME`='users';

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

open column_cursor;

myloop: loop

    fetch column_cursor into col_name;

    if done then
        leave myloop;
    end if;

    /*SET @old_val = OLD.{{col_name}}; <------ HERE */
    /*SET @new_val = NEW.{{col_name}};<------ HERE */

    if @old_val <> @new_val then
        /*INSERT INTO `logs` ....*/
    end if;


end loop;

close column_cursor;

END;

我需要从OLDNEW获得价值。

但是列名在变量col_name中。

我试过了:

SET @old_q = CONCAT('OLD.', col_name);
SET @new_q = CONCAT('NEW.', col_name);

PREPARE old_prepare_query FROM @old_q;
PREPARE new_prepare_query FROM @new_q;

EXECUTE old_prepare_query USING @old_val;
EXECUTE new_prepare_query USING @new_val;

但我收到了一个错误:

Error Code: 1336. Dynamic SQL is not allowed in stored function or trigger

0 个答案:

没有答案