更新数据库表中的数据时,我需要写一个单独的表:表名,更改日期,旧列值,新列值。
我写了触发器:
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;
我需要从OLD
和NEW
获得价值。
但是列名在变量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