Question

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 @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)

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top