我在这里要做的是创建动态触发器:
我收到此错误消息:[Err] 1054 - Unknown column 'column_name' in 'NEW'
如果我手动输入列名称然后它可以工作,但在这种情况下,这种方法会变为静态,这取决于人类的交互。
TRIGGER:
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;
答案 0 :(得分:-1)
column_name
中没有名为original_table
的列,因此您可以执行NEW.COLUMN_NAME
或OLD.COLUMN_NAME
之类的操作。你应该NEW.First_name
例如