我正在尝试使用以下代码创建一个 MySQL Before Insert 触发器,如果我能找到一种方法来执行由触发器生成的准备好的语句,它将执行我希望它执行的操作。
是否有任何替代方法可以从触发器中执行准备好的语句?谢谢
BEGIN
SET @CrntRcrd = (SELECT AUTO_INCREMENT FROM information_schema.TABLES
WHERE TABLE_SCHEMA=DATABASE()
AND TABLE_NAME='core_Test');
SET @PrevRcrd = @CrntRcrd-1;
IF (NEW.ID IS NULL) THEN
SET NEW.ID = @CrntRcrd;
END IF;
SET @PrevHash = (SELECT Hash FROM core_Test WHERE Record=@PrevRcrd);
SET @ClmNms = (SELECT CONCAT('NEW.',GROUP_CONCAT(column_name
ORDER BY ORDINAL_POSITION SEPARATOR ',NEW.'),'')
FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = 'core_Test');
SET @Query = CONCAT("SET @Query2 = CONCAT_WS(',','",@PrevHash,"','", @CrntRcrd, "',", @ClmNms, ");");
PREPARE stmt1 FROM @Query;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
SET NEW.Hash = @Query2;
END
更新/澄清:数据将存储在下表中。
+------------+-----+------+----------------+
| Record (AI)| ID | Data | HASH |
+------------+-----+------+----------------+
| 1 | 1 | ASDF | =DHFBGKJSDFHBG | (Hash Col 1)
| 2 | 2 | NULL | =UEGFRYJKSDFHB | (Hash Col 1 + Col 2)
| 3 | 1 | VBNM | =VKJSZDFVHBFJH | (Hash Col 2 + Col 3)
| 4 | 4 | TYUI | =KDJFGNJBHMNVB | (Hash Col 3 + Col 4)
| 5 | 5 | ZXCV | =SDKVBCVJHBJHB | (Hash Col 4 + Col 5)
+------------+-----+------+----------------+
在每个插入命令上,该表将通过将前一行的哈希值应用到整个新行的 CONCAT() 中,然后重新对整个字符串进行哈希处理,从而为该行生成一个哈希值。这将创建哈希值的运行记录,用于审计目的/在应用程序的另一部分中使用。
我的限制是这必须在 INSERT 之前完成,因为之后无法更新行。
更新:我目前正在使用以下代码,直到找到一种将列名动态传递给 CONCAT 的方法:
BEGIN
SET @Record = (
SELECT AUTO_INCREMENT FROM information_schema.TABLES
WHERE TABLE_SCHEMA=DATABASE()
AND TABLE_NAME='core_Test' #<--- UPDATE TABLE_NAME HERE
);
SET @PrevRecrd = @Record-1;
IF (new.ID IS NULL) THEN
SET new.ID = @Record;
END IF;
SET @PrevHash = (
SELECT Hash FROM core_Test #<--- UPDATE TABLE_NAME HERE
WHERE Record=@PrevRecrd
);
SET new.Hash = SHA1(CONCAT_WS(',',@PrevHash, @Record,
/* --- UPDATE TABLE COLUMN NAMES HERE (EXCLUDE "new.Record" AND "new.Hash") --- */
new.ID, new.Name, new.Data
));
END