DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `update_factoryName`()
BEGIN
-- 定义循环条件
DECLARE flag INT DEFAULT 0;
-- 保存表名
DECLARE tname VARCHAR(50);
-- 查询数据库test中含有userId列的表,如果区分大小写使用binary COLUMN_NAME = 'userId'
DECLARE result CURSOR FOR SELECT distinct table_name FROM information_schema.columns
WHERE column_name='factoryName' and table_name not like '%_bk' and table_name like 't_%' and table_name not like '%_zjy'and table_name not like '%_0929' and table_name not like '%_bkbk'
and table_name not like '%_bak' and table_name not in ('t_baseinfo_factoryinfo' ) and table_schema = 'qms';
-- 退出循环
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET flag = 1;
-- 打开游标
OPEN result;
WHILE flag <> 1 DO
-- 游标指向下一个位置,可以有多个数据,比如FETCH result INTO tname,ttype,...;
FETCH result INTO tname;
set @bakTableName = concat(tname, '_bkbk');
-- 备份表数据
set @dropTable = concat(' drop table if exists ', @bakTableName , ';');
PREPARE stmt FROM @dropTable;
EXECUTE stmt;
SET @stmt = CONCAT( ' create table ',@bakTableName, ' select * from ', tname, ' ;');
PREPARE stmt FROM @stmt;
EXECUTE stmt;
if tname = 't_claim_saleclaimdetail'
then
SET @execSql = CONCAT('UPDATE ', tname, ' a , t_baseinfo_factoryInfo b set a.factoryName = b.factoryName where b.deleted = 0 and a.factoryNo = b.sapFactoryCode;');
elseif tname in ('t_claim_saleclaim', 't_claim_x5data')
then
SET @execSql = CONCAT('UPDATE ', tname, ' a , t_baseinfo_factoryInfo b set a.factoryName = b.factoryName where b.deleted = 0 and a.plantNum = b.sapFactoryCode;');
elseif tname in ('t_esb_biscrapdetail', 't_esb_biscrapotherdetail', 't_esb_bisppmprojectdetail')
then
SET @execSql = CONCAT('UPDATE ', tname, ' a , t_baseinfo_factoryInfo b set a.factoryName = b.factoryName where b.deleted = 0 and a.werks = b.sapFactoryCode;');
else
SET @execSql = CONCAT('UPDATE ', tname, ' a , t_baseinfo_factoryInfo b set a.factoryName = b.factoryName where b.deleted = 0 and a.factoryCode = b.sapFactoryCode;');
end if;
PREPARE stmt FROM @execSql;
EXECUTE stmt;
END WHILE;
END$$
DELIMITER ;