MySQL – Loop Through Comma Separated Values in Stored Procedures

MySQLstored-procedures

I have a Master DB.
I want to make duplicate DB of the Master DB but not all tables just specified.

I have those table names in comma separated string.
tbl1, tbl2, tbl7, tbl10 etc.

I'm trying to make a stored procedure passing it new DB name That creates the DB and replicate the given table to it. So far i have 2 thing, but i don't know how to loop through it. I'm new to DB so please guide how to achieve this.

(Note) I haven't found if an array can be used to loop through, the table names could also be stored in array variable, because the table names are hard coded.

The following is the sudo code i desire.

CREATE DATABASE %param_db%;

@tables = 'tbl1, tbl2, tbl7, tbl10';
loop through @tables as table_name
    CREATE TABLE %param_db.table_name% LIKE Master.%table_name%;
End loop

Best Answer

Here are the steps to layout in the Stored Procedure

  • Create the Target database
  • Determine how many elements are in the list of tables
  • Loop through each element of the list of tables using the ELT() function
  • Take each element and form SQL Statement to create the new table in Target DB

Here is that Stored Procedure

DELIMITER $$

DROP PROCEDURE IF EXISTS `test`.`TableCookieCutter` $$
CREATE PROCEDURE `test`.`TableCookieCutter`
(
    SourceDB VARCHAR(64),
    TargetDB VARCHAR(64),
    TableList VARCHAR(1024)
)
BEGIN

    # Create the Target DB
    SET @sql = CONCAT('CREATE DATABASE IF NOT EXISTS ',TargetDB);
    PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s;

    # Strip Table List of Blanks
    # Enclose each table in quotes
    SET @table_list = CONCAT('''',REPLACE(REPLACE(TableList ,' ',''),',',QUOTE(',')),'''');

    # Count the number of tables in the list
    SET @table_stub = REPLACE(@table_list,',','');
    SET @array_count = LENGTH(@table_list) - LENGTH(@table_stub) + 1;

    # Loop through list of tables, creating each table
    SET @x = 0;
    WHILE @x < @array_count DO
        SET @x = @x + 1;
        SET @sql = CONCAT('SELECT ELT(',@x,',',@table_list,') INTO @tb');
        PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s;
        SET @sql = CONCAT('CREATE TABLE ',TargetDB,'.',@tb,' LIKE ',SourceDB,'.',@tb);
        PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s;
    END WHILE;

END $$

DELIMITER ;