我在这里要做的是创建动态触发器:
- 从名为 *original_table* 的表中获取列名
- 遍历返回的列名。
- 如果与列名关联的旧值和新值之间发生变化,请更新日志表。
我收到此错误消息:[Err] 1054 - Unknown column 'column_name' in 'NEW'
如果我手动输入列名,那么它会起作用,但在这种情况下,这种方法会变成静态的,这取决于人工交互。
扳机:
DELIMITER $$
DROP TRIGGER IF EXISTS log_original_table $$
CREATE TRIGGER log_original_table AFTER UPDATE ON original_table
FOR EACH ROW
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE column_name VARCHAR(100);
DECLARE column_cursor CURSOR FOR SELECT column_name FROM information_schema.columns WHERE table_name = 'original_table';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN column_cursor;
read_loop: LOOP
FETCH column_cursor INTO column_name;
IF done THEN
LEAVE read_loop;
END IF;
IF (NEW.column_name <> OLD.column_name) THEN
INSERT INTO original_table_log
(parent_id, parent_field_name, parent_old_value, parent_new_value, parent_modified_on)
VALUES
(NEW.id, column_name, OLD.column_name, NEW.column_name, NOW());
END IF;
END LOOP;
CLOSE column_cursor;
END$$
DELIMITER ;
ORIGINAL_TABLE:
DROP TABLE IF EXISTS `original_table`;
CREATE TABLE `original_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(100) DEFAULT NULL,
`surname` varchar(100) DEFAULT NULL,
`username` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of original_table
-- ----------------------------
INSERT INTO `original_table` VALUES ('1', 'michael', 'jakson', 'you');
INSERT INTO `original_table` VALUES ('2', 'john', 'travolta', 'me');
INSERT INTO `original_table` VALUES ('3', 'lionel', 'messi', 'her');
INSERT INTO `original_table` VALUES ('4', 'brian', 'adams', 'they');
ORIGINAL_TABLE_LOG:
DROP TABLE IF EXISTS `original_table_log`;
CREATE TABLE `original_table_log` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`parent_id` int(11) DEFAULT NULL,
`parent_field_name` varchar(100) DEFAULT NULL,
`parent_old_value` varchar(100) DEFAULT NULL,
`parent_new_value` varchar(100) DEFAULT NULL,
`parent_modified_on` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;