DELIMITER $$
/* Mysql 创建存储过程 名为:new_pro */
CREATE DEFINER=`root`@`localhost` PROCEDURE `new_pro`()
BEGIN
/* 声明变量 并设定默认值 */
Declare not_found int default 0;
Declare collectionId bigint;
Declare children_collectionId bigint;
/* 创建游标 通过查询表 channelcollection创建出游标 */
Declare idCursor cursor for select id from channelcollection where name='a' or name='c';
/* 异常处理,当发生异常的时候设定 not_found的值为1 */
Declare continue handler for not found set not_found=1;
/* 设定collectionId的值为 查询出的ID */
set collectionId = (SELECT id FROM channelcollection where name='b' limit 1);
/* 使用游标之前先打开游标 */
open idCursor;
/* 循环游标并且把循环出来的游标赋值给 children_collectionId */
idCursor_loop: LOOP fetch idCursor into children_collectionId;
if not_found=1 then
leave idCursor_loop;
else
/* 将数据循环插入另外一个表 */
insert into channelcollectionfamily values (collectionId,children_collectionId);
end if;
end LOOP idCursor_loop;
/* 使用完之后关闭游标 */
close idCursor;
END
转载于:https://my.oschina.net/Kxvz/blog/417352