mysql数据库创建存储过程

阅读更多
多游标及游标嵌套使用


DELIMITER $$
CREATE PROCEDURE test_cursor()
BEGIN
/*定义变量*/
DECLARE userId Long;
DECLARE userName VARCHAR(255);
DECLARE userAge INT;
-- 定义循环标识,默认值为 FALSE
DECLARE done INT DEFAULT FALSE;
-- 定义游标
DECLARE My_Cursor CURSOR FOR (SELECT id,`name`,age FROM user);
DECLARE My_Cursor2 CURSOR FOR (SELECT id,`name`,age FROM user WHERE id in(3,4));
DECLARE My_Cursor3 CURSOR FOR (SELECT id,`name`,age FROM user WHERE id=userId);
-- 将结束标志绑定到游标,若没有数据返回,程序继续,并将变量done设为TRUE
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
-- 打开游标
OPEN My_Cursor;
myLoop : LOOP
-- 循环游标中的数据,并赋值到变量中
FETCH My_Cursor INTO userId,userName,userAge;
IF done THEN
LEAVE myLoop;
ELSE
IF userName='lisi' THEN
UPDATE user SET `name`='lisi1' WHERE id=userId;
END IF;
END IF;
COMMIT;
END LOOP myLoop;
CLOSE My_Cursor;

-- 开始第二个游标时先将 done 置为 FALSE
SET done = FALSE;

-- 打开游标
OPEN My_Cursor2;
myLoop2 : LOOP
-- 循环游标中的数据,并赋值到变量中
FETCH My_Cursor2 INTO userId,userName,userAge;
IF done THEN
LEAVE myLoop2;
ELSE
OPEN My_Cursor3;
myLoop3 : LOOP
FETCH My_Cursor3 INTO userId,userName,userAge;
IF done THEN
LEAVE myLoop3;
ELSE
UPDATE user SET `name`=CONCAT(userName,'1','2') WHERE id=userId;
END IF;
COMMIT;
END LOOP myLoop3;
CLOSE My_Cursor3;
-- 嵌套使用是内部游标结束后给done置 FALSE
SET done=FALSE;
END IF;
END LOOP myLoop2;
CLOSE My_Cursor2;
END
$$



参考URL:
https://blog.csdn.net/obc_132/article/details/79397128

https://blog.csdn.net/xiaosheng_papa/article/details/80635727

https://www.cnblogs.com/LJ-fish/archive/2010/10/14/1851592.html

你可能感兴趣的:(mysql数据库创建存储过程)