Mysql 存储过程 批量更新表中存在某个字段的数据,先备份,再更新

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 ;

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值