Mysql 动态创建当前库所有表索引

mysql数据库版本:mysql-5.7.21-winx64
-- 动态生成索引
DROP PROCEDURE IF EXISTS proc_createIndex;
CREATE PROCEDURE proc_createIndex()
BEGIN
	set @rownum=0;
	SELECT DATABASE() INTO @CurrentDatabase;
	drop table if EXISTS a_temp;
	create table a_temp as
	SELECT @rownum := @rownum +1 as seq,
	concat('create index IDX_',replace(TABLE_NAME,'_info',''),'_',column_name,' on ',TABLE_NAME,'(',column_name,');') as sqlStr
	from information_schema.columns syscolumn
	where TABLE_SCHEMA = @CurrentDatabase
	and TABLE_NAME not like 'v_%'   -- 排除视图表
	and TABLE_NAME not like 'act_%' -- 排除以act_开头的表
	and
	(COLUMN_NAME like '%_id'
		or COLUMN_NAME like '%genecode'
		or COLUMN_NAME = 'pid'
	)
	and concat('IDX_',replace(syscolumn.TABLE_NAME,'_info',''),'_',syscolumn.column_name) not in(
	SELECT i.index_name
	FROM information_schema.statistics i
	WHERE i.table_schema=@CurrentDatabase AND i.table_name = syscolumn.TABLE_NAME )
	;

set @i=1;
select count(*) into @c from a_temp;
	while @i<=@c DO -- 循环开始
			select sqlStr into @sqlValue from a_temp where seq=@i;
		  prepare process from @sqlValue;
		  execute process;
			set @i=@i+1;
	end while; -- 循环结束
END;

call proc_createIndex();


猜你喜欢

转载自blog.csdn.net/lwbjyl/article/details/80488000
今日推荐