Mysql calling procedure failed when dynamically alter table in it

后端 未结 2 1868
萌比男神i
萌比男神i 2021-01-23 08:05

I want to alter my tables dynamically based on whether the table has specific column.

My database name is summer_cms, and there are over 50 tables in it.

2条回答
  •  遇见更好的自我
    2021-01-23 08:35

    There a a few alterations you can make to your procedure to make it more streamlined as well as getting round a few problems.

    First using a cursor to select the table names rather than using the two selects your using. Secondly to use a prepared statement to allow you to dynamically set the table name...

    DELIMITER $$
    CREATE DEFINER=`root`@`localhost` PROCEDURE `ALTER_SUMMER_TABLE`()
    BEGIN
        DECLARE done INT DEFAULT 0;
        DECLARE tableName VARCHAR(64);
        declare cur cursor for SELECT TABLE_NAME
                                 FROM information_schema.COLUMNS
                                WHERE TABLE_SCHEMA = 'summer_cms'
                                AND COLUMN_NAME = 'add_time';
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
    
        open cur;
    
        start_loop: loop
            fetch cur into tableName;
            if (done = 1 )THEN
                 LEAVE start_loop;
            END IF;
            SET @sql = CONCAT('ALTER TABLE ', tableName,' ADD COLUMN `add_user_id` INT NOT NULL DEFAULT 0 ');
            PREPARE stmt FROM @sql;
            EXECUTE stmt;
    
        end loop;
    
        close cur;
    END$$
    DELIMITER ;
    

    You could do a few tweaks - only fetch table names where the column doesn't already exist for example.

提交回复
热议问题