1. 程式人生 > 其它 >儲存過程--新增索引、刪除索引

儲存過程--新增索引、刪除索引

/*存在則刪除儲存過程*/
drop procedure if EXISTS add_index_while_procure;
/*檢視儲存過程*/
show procedure status;
show create procedure add_index_while_procure;

 1 delimiter $$
 2 /*建立帶參儲存過程 dbName庫名稱;tablePrefixName表名稱字首;minTableNumber表最小序號;maxTableNumber表最大序號;indexName索引名稱;indexValue索引列*/
 3 create PROCEDURE add_index_while_procure(IN dbPrefixName VARCHAR(50),IN tablePrefixName VARCHAR(50),IN minTableNumber INT,IN maxTableNumber INT,IN indexName varchar(50),IN indexValue varchar(200))
4 BEGIN 5 declare table_name_number int; 6 7 set table_name_number=minTableNumber; 8 while(table_name_number<=maxTableNumber) DO 9 /*新增索引語句*/ 10 set @STMT :=CONCAT("alter table ",dbPrefixName,".",tablePrefixName,table_name_number," ADD index " ,indexName," ",indexValue,";"); 11 /*輸出執行語句*/ 12
select @STMT; 13 prepare STMT FROM @STMT; 14 EXECUTE STMT; 15 16 set table_name_number=table_name_number+1; 17 end while; 18 END 19 $$ 20 delimiter;
新建儲存過程:給庫.表的欄位新增索引

/*呼叫儲存過程 所有子表及主表
ALTER TABLE manager.tableName ADD INDEX idx_station_time (STATION_CODE, TIME) USING BTREE ;
*/
call add_index_while_procure("manager","tableName_",1906,1912,"idx_code_time","(CODE, TIME)");

---------------------------

 1 delimiter $$
 2 /*建立帶參儲存過程 dbName庫名稱;tablePrefixName表名稱字首;minTableNumber表最小序號;maxTableNumber表最大序號;indexName索引名稱;indexValue索引列*/
 3 create PROCEDURE drop_index_while_procure(IN dbPrefixName VARCHAR(50),IN tablePrefixName VARCHAR(50),IN minTableNumber INT,IN maxTableNumber INT,IN indexName varchar(50))
 4 BEGIN
 5 declare table_name_number int;
 6 
 7 set table_name_number=minTableNumber;
 8 while(table_name_number<=maxTableNumber) DO 
 9 /*新增索引語句*/ 
10 set @STMT :=CONCAT("alter table ",dbPrefixName,".",tablePrefixName,table_name_number," DROP index " ,indexName,";");
11 /*輸出執行語句*/ 
12 select @STMT;
13 prepare STMT FROM @STMT;
14 EXECUTE STMT; 
15 
16 set table_name_number=table_name_number+1;
17 end while;
18 END 
19 $$
20 delimiter;
刪除儲存過程:給庫.表的欄位新增索引

/*呼叫儲存過程 所有子表及主表
ALTER TABLE manager.tableName DROP INDEX idx_station_time;
*/
call drop_index_while_procure("manager","tableName_",1906,1912,"idx_station_time");

參考:

https://blog.csdn.net/qq_23132561/article/details/100888454