开发者

Use an user variable in a "INSERT ON" clause

开发者 https://www.devze.com 2023-03-23 11:22 出处:网络
I try to make a clean trigger with user-defined variables, so this is my code : SET @target_bdd = \'trigger_second\';

I try to make a clean trigger with user-defined variables, so this is my code :


SET @target_bdd = 'trigger_second';
SET @trigger_name = 'account_copy';
SET @table_name = 'account';
SET @开发者_JS百科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 ;

But I have this error :

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

Why ? I tried with others quotes ('") but there's same error :(

With no quote :

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

I try to declare an user-defined variable with SQL instructions like :

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;

But I have an error 1295 (See in MySQL Documentation)


You can't use user variables for table names, columns etc in plain SQL. You can't also create a trigger in prepared statement (just like the error told you). Seems like there is currently no way to do what you want.


I must say that I've never used user defined variables before, but in testing it I found out you shouldn't quote them!
When you quote the `@vars` mysql will look for the literal '@vars' field, in stead of the value that is stored in it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号