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.
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.