引用:https://blog.csdn.net/qq_36984221/article/details/128958691
# 查找数据的表
select * from information_schema.TABLES
# 查找数据库的字段
select * from information_schema.COLUMNS
table_schema : 数据库名字
table_name : 表的名字
column_name: 列的名字
drop procedure if exists addColumn;
delimiter $$
create procedure addColumn() begin
-- 声明变量
declare s_tablename varchar(100);
declare s_columnname varchar(100);
-- 查找数据库表的游标
declare cur_table_structure cursor for select table_name from information_schema.TABLES
where TABLE_SCHEMA='sleeve';
-- 02000表示 no data,,在游标迭代的时候,,没有数据的时候
declare continue handler for sqlstate '02000' set s_tablename = null;
open cur_table_structure;
fetch cur_table_structure into s_tablename;
-- 遍历表
while (s_tablename is not null) do
set s_columnname = null;
-- 查找有is_deleted的列
select COLUMN_NAME into s_columnname from information_schema.COLUMNS where TABLE_NAME=s_tablename and COLUMN_NAME='is_deleted' limit 1;
-- 没有的设置is_deleted
if s_columnname is null then
set @myQuery = concat('alter table `',s_tablename,'` add column is_deleted tinyint default 0 ');
-- 将@myQuery中sql查询字符串编译成可执行的sql语句
prepare MSQL from @myQuery;
-- 执行动态sql
execute MSQL;
end if;
-- 获取下一个游标值
fetch cur_table_structure into s_tablename;
end while;
close cur_table_structure;
end;
$$
call addColumn();