淘先锋技术网

首页 1 2 3 4 5 6 7

1.在工作会遇到这种情况,mysql数据库,系统涉及到备份多表数据,为了方便,用存储过程来实现此功能,同时也复习一下存储过程的写法,同时记录下方便以后扩展修改

2.存储过程代码如下

-- 创建存储过程

CREATE PROCEDURE test_01()

BEGIN

-- 定义变量

DECLARE s int DEFAULT 0;

DECLARE monitorTable varchar(255);

DECLARE countTable varchar(256);

DECLARE countTableNew varchar(256);

-- 定义游标,并将sql结果集赋值到游标中

DECLARE report CURSOR FOR select DISTINCT monitor_table,count_table from t_monitorinfo ;

-- 声明当游标遍历完后将标志变量置成某个值

DECLARE CONTINUE HANDLER FOR NOT FOUND SET s=1;

-- 打开游标

open report;

-- 将游标中的值赋值给变量,注意:变量名不要和返回的列名同名,变量顺序要和sql结果列的顺序一致

fetch report into monitorTable,countTable;

-- 当s不等于1,也就是未遍历完时,会一直循环

while s<>1 do

-- 执行业务逻辑

set countTableNew = concat(countTable,'_bak');

-- 表名是参数的语法

SET @STMT =CONCAT("CREATE TABLE ",countTableNew," LIKE ",countTable,";");

PREPARE STMT FROM @STMT;

EXECUTE STMT;

SET @STMT2 =CONCAT("INSERT INTO ",countTableNew," SELECT * FROM ",countTable,";");

PREPARE STMT2 FROM @STMT2;

EXECUTE STMT2;

-- 表名非参数的语法

-- update patrolreporthistory set reportUrl = CONCAT('patrolReport.html?monitorId=',substring(report_url,15,1),'&reportId=',report_id) where reportId=report_id;

-- 将游标中的值再赋值给变量,供下次循环使用

fetch report into monitorTable,countTable;

-- 当s等于1时表明遍历以完成,退出循环

end while;

-- 关闭游标

close report;

END;