背景:在一个项目中,您需要将相同的字段添加到数百个表中,这很难手动添加,因此您计划使用存储过程来实现。
[En]
Background: in a project, you need to add the same fields to hundreds of tables, which is difficult to add manually, so you plan to use stored procedures to implement it.
编写的存储过程:
delimiter //
-- 创建存储过程之前需判断该存储过程是否已存在,若存在则删除
DROP PROCEDURE IF EXISTS updateTables;
-- 创建存储过程
CREATE PROCEDURE updateTables()
BEGIN
-- 定义变量
DECLARE s int DEFAULT 0;
DECLARE tableName varchar(100);
DECLARE var_sql varchar(800);
DECLARE cnt INT DEFAULT 0;
-- 定义游标,并将sql结果集赋值到游标中
DECLARE report CURSOR FOR select table_name from information_schema.tables where table_schema='pbocbdms' and table_name like 'ods_%';
-- 声明当游标遍历完后将标志变量置成某个值
DECLARE CONTINUE HANDLER FOR NOT FOUND SET s=1;
-- 打开游标
open report;
-- 将游标中的值赋值给变量,注意:变量名不要和返回的列名同名,变量顺序要和sql结果列的顺序一致
fetch report into tableName;
-- 当s不等于1,也就是未遍历完时,会一直循环
while s<>1 do
-- 执行业务逻辑
SELECT count(*) into cnt FROM information_schema.columns WHERE table_schema='pbocbdms' AND table_name = tableName AND column_name = 'xm_code';
-- 列不存在则可以添加
IF cnt = 0 THEN
set var_sql = concat('alter table ',tableName,' add column xm_code varchar(50) COMMENT \'项目别名编码\';');
set @sql = var_sql;
PREPARE s1 from @sql;
EXECUTE s1;
deallocate prepare s1;
END IF;
-- 继续抓取游标数据到变量
fetch report into tableName;
end while;
-- 关闭游标
close report;
END //
delimiter ;
调用存储过程
call updateTables();
Original: https://www.cnblogs.com/hdwang/p/16097550.html
Author: 追极
Title: mysql使用存储过程批量给表加字段
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/505498/
转载文章受原作者版权保护。转载请注明原作者出处!