1
我想在這裏做的是創建動態觸發:觸發與光標審計
- 從名爲* original_table *
- 迭代通過返回的列名錶獲取列名。
- 如果在與列名關聯的舊值和新值之間有更改,請更新日誌表。
我收到此錯誤信息:[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;
告訴我們'desc original_table'的結果 – ravnur
剛剛加上 – BentCoder