我尝试使用用户定义的变量创建一个干净的触发器,所以这是我的代码:
SET @target_bdd = 'trigger_second';
SET @trigger_name = 'account_copy';
SET @table_name = 'account';
SET @primary_key = 'id';
DROP TRIGGER IF EXISTS `@trigger_name`;
DELIMITER $$
CREATE TRIGGER `@trigger_name` AFTER INSERT
ON `@table_name`
FOR EACH ROW BEGIN
INSERT INTO `@target_bdd`.`@table_name`
SELECT * FROM `@table_name`
WHERE `@primary_key` = NEW.`@primary_key`;
END $$
DELIMITER ;
但我有这个错误:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds >to your MySQL server version for the right syntax to use near '@table_name
FOR EACH ROW BEGIN INSERT INTO `@target_bdd`.`@table_name` SELECT * ' at line 2
为什么?我试过别人引用(‘“)但是有同样的错误:(
没有报价:
ERROR 1064 (42000): You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near ‘@trigger_name AFTER INSERT ON @table_name FOR EACH
ROW BEGIN INSERT INTO @target’ at line 1
我尝试使用SQL指令声明用户定义的变量,如:
SET @sql = CONCAT(
'CREATE TRIGGER ',
@trigger_name,
' AFTER INSERT ON ',
@table_name,
' FOR EACH ROW BEGIN INSERT INTO ',
@target_bdd,
'.',
@table_name,
' SELECT * FROM ',
@table_name,
' WHERE ',
@primary_key,
' = NEW.',
@primary_key,
'; END'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
但我有一个错误1295(See in MySQL Documentation)
解决方法:
您不能在普通SQL中将用户变量用于表名,列等.您也不能在预准备语句中创建触发器(就像错误告诉您的那样).好像目前没有办法做你想做的事.