Mysql calling procedure failed when dynamically alter table in it

后端 未结 2 1831
萌比男神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:48

    Here's an example of dynamic sql

    drop procedure if exists alter_table;
    delimiter //
    
    CREATE DEFINER=`root`@`localhost`  procedure alter_table()
    
    begin
    declare tablename varchar(20);
    set tablename = 'u';
    
    set @sqlstmt =  concat('ALTER TABLE ', tableName, ' ADD COLUMN ', char(96), 'add_user_id', char(96), ' INT NOT NULL DEFAULT 0 COMMENT', char(39), 'add user id', char(39),';');
    prepare stmt from @sqlstmt;
    execute stmt;
    deallocate prepare stmt;
    
    end //
    
    delimiter ;
    

    Note I have used ascii backticks and single quotes.

提交回复
热议问题