1、源表信息:
CREATE TABLE `aa` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`b1` int(11) DEFAULT NULL,
`abc` int(200) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `b` (`b1`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
2、目标表
CREATE TABLE `test` (
`auto_id` int(11) NOT NULL AUTO_INCREMENT,
`a1` int(10) NOT NULL,
`a2` int(11) DEFAULT NULL,
`a3` int(11) DEFAULT NULL,
PRIMARY KEY (`auto_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COMMENT='测试表'
3、存储过实现:注意格式
DELIMITER $$
DROP PROCEDURE IF EXISTS `record_timestamp_deal`$$
#创建存储过程
CREATE PROCEDURE record_timestamp_deal()
BEGIN
#定义获取值存储的变量
DECLARE a4 INT;
DECLARE a5 INT;
DECLARE a6 INT;
DECLARE is_done INT DEFAULT 0;
DECLARE cur CURSOR FOR SELECT id,b1,abc FROM aa;
#异常处理
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET is_done =1;
OPEN cur;
#取出游标值至定义的变量中
FETCH NEXT FROM cur INTO a4,a5,a6;
REPEAT
IF NOT is_done THEN
INSERT INTO test(a1,a2,a3)VALUES(a4,a5,a6);
END IF ;
#重新抓取数据进入循环
FETCH NEXT FROM cur INTO a4,a5,a6;
#结束循环
UNTIL is_done END REPEAT ;
#关闭游标
CLOSE cur ;
END $$
##调用存储过程
call record_timestamp_deal