我正在更新时为表中的记录更改编写触发器 我的触发器是
CREATE TRIGGER vehicle_mst_log
AFTER UPDATE ON vehicle_mst
FOR EACH ROW BEGIN
IF (OLD.COLUMN1 != NEW.COLUMN1) THEN
INSERT INTO ABN_OLDLOGTABLE (
TABLENAME,
COLUMNNAME,
OLDVALUE,
NEWVALUEW,
TIME,
USER)
VALUES (
"TABLE",
"COLUMN1",
COLUMN1OLDVALUE,
COLUMN1NEWVALUE,
NOW(),
USER);
END IF;
IF (OLD.COLUMN2 != NEW.COLUMN2) THEN
INSERT INTO ABN_OLDLOGTABLE (
TABLENAME,
COLUMNNAME,
OLDVALUE,
NEWVALUEW,
TIME,
USER)
VALUES (
"TABLE",
"COLUMN2",
COLUMN2OLDVALUE,
COLUMN2NEWVALUE,
NOW(),
USER);
END IF;
END;
但我在表中有大约40列任何其他方便的方法来在循环中写入列名并检查值的变化
答案 0 :(得分:4)
您可能需要编写一个小实用程序,它将从MySQL读取给定表的模式并创建检查所有列的触发器。一旦更改了表结构,您需要重新运行此实用程序。如果你需要帮助写这样的实用工具,请告诉我。
以下是生成触发器的脚本:
#!/bin/sh
db="$1";
shift
echo "DELIMITER ;;"
for table in "$@"
do
sql="show columns from $table"
columns=`mysql -B -N -e "$sql" "$db" | cut -f 1`
echo "CREATE TRIGGER ${table}_log"
echo "AFTER UPDATE ON $table"
echo "FOR EACH ROW BEGIN"
for column in $columns
do
echo " IF (OLD.$column != NEW.$column) THEN"
echo " INSERT INTO ABN_OLDLOGTABLE (TABLENAME, COLUMNNAME, OLDVALUE, NEWVALUEW, TIME, USER)"
echo " VALUES (\"$table\", \"$column\", OLD.$column, NEW.$column, NOW(), USER());"
echo " END IF;"
done
echo "END;;"
done
将其另存为trigger.sh
,在其上设置可执行位(chmod a+x trigger.sh
),然后按以下方式运行:
trigger.sh dbname table1 table2 ...
它将在STDIN上打印触发器代码。