MySql存储过程批量删除多个数据库中同名表中的指定字段

1、 创建存储过程batchDeleteField:删除所有名称为"MyDB_"开头的数据库中的指定字段

-- ----------------------------
-- Procedure structure for batchDeleteField
-- ----------------------------
DROP PROCEDURE IF EXISTS `batchDeleteField`;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `batchDeleteField`(IN `tableName` varchar(100),IN `fieldName` varchar(100))
BEGIN
    #数据库名称
  DECLARE schemaName VARCHAR(100); 

  #声明结束标识
    DECLARE end_flag int DEFAULT 0;
    #声明游标 curosr ,查找所有“MyDB_”开头的数据库
    DECLARE curosr CURSOR FOR select  TABLE_SCHEMA   from information_schema.`TABLES`  WHERE TABLE_SCHEMA like 'MyDB_%' and table_name = tableName;
  #设置终止标志
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET end_flag=1;

    #打开游标
    OPEN curosr;
    
    #遍历游标
    loop_label:  LOOP
        
        FETCH curosr INTO schemaName;#获取当前游标指针记录,取出值赋给自定义的变量
        
        IF end_flag > 0 THEN 
            LEAVE  loop_label;
        END IF;
    
        SET @sqlStr=CONCAT('alter table ',schemaName,'.',tableName,' drop column `',fieldName,'` ');
    PREPARE stmt from @sqlStr;
    EXECUTE stmt;

    END LOOP;
    
  #关闭游标
    close curosr;
END
;;
DELIMITER ;

2、调用存储过程:

batchDeleteField('Users','score') //删除Users表中的score字段

 

posted @ 2019-12-20 14:36  ziwuxian  阅读(1048)  评论(0编辑  收藏  举报