MySQL 存储过程中的循环操作
使用光标执行循环操作
DROP PROCEDURE IF EXISTS sp_opr;
CREATE PROCEDURE sp_opr()
BEGIN
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
/* 定义变量一 */
DECLARE _Err_Code CHAR(8) DEFAULT '';
/* 定义变量二 */
DECLARE _Cnt INT DEFAULT 0;
/* 光标 */
DECLARE _done INT DEFAULT 0;
DECLARE _Cur_Error CURSOR FOR
SELECT col1,col2 FROM table WHERE rec_dd=ADDDATE(CURDATE(),-1);
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET _done = 1;
/* 打开光标 */
OPEN _Cur_Error;
/* 循环执行 */
REPEAT
FETCH _Cur_Error INTO _Err_Code, _Cnt; --读取下一行
IF NOT _done THEN
-- 这里的代码被循环执行(这里可以使用上面读取的值)
END IF;
UNTIL _done END REPEAT; --当_done=1时退出被循
/*关闭光标*/
CLOSE _Cur_Error;
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
END;
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)