Search code examples
mysqlstored-proceduressetsql-insertconcatenation

MySQL stored prosedure, INSERT INTO $table


I am trying to create a stored procedure to first create a table, if it doesn't already exist. This part function as intended:

    BEGIN
    SET @sql = CONCAT('CREATE TABLE IF NOT EXISTS ',`@variable_table`,' LIKE table_template;');
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

After creating the table, or if the table already exist, i want the stored proseadure to dump a set of data in it.

    SET @sql = CONCAT('INSERT INTO ',`@variable_table`,' (
    `col1`,`col2`,`col3`,`col4`,`col5`)
    VALUES (
    `@D1`,`@D2`,`@D3`,`@D4`,`@D5`);');

    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    END

If i exchange the ',@variable_table,' with existing_table_name the code works as intended. Is it possible to run the code With a variable here and in that case, how do I do it?


Solution

  • After playing around with trial and error for the past few hours I found the errors and the code is now working:

    BEGIN
    SET @sql = CONCAT('CREATE TABLE IF NOT EXISTS ',`@variable_table`,' LIKE table_template;');
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    
    SET @sql = CONCAT('INSERT INTO ',`@variable_table`,' (`col1`,`col2`,`col3`,`col4`,`col5`)
    VALUES ("',`@D1`,'","',`@D2`,'","',`@D3`,'","',`@D4`,'","',`@D5`,'");');
    
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    END
    

    It seems to me that my syntax error was in the '',``,"" area of the code. As you can see, the only change I've made is to put the @D1 variables outside the 'Text' and added " inside the text on both sides of the variables.