码迷,mamicode.com
首页 > 数据库 > 详细

MySQL 游标(cursor)简单应用

时间:2014-09-16 10:59:00      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:os   使用   ar   for   sp   on   c   new   ef   

    MySQL存储过程不可以定义动态的游标(cursor),但是可以使用变量。open -> fetch...into -> close。

    1、声明一个游标:

-- define userId
DECLARE userId nvarchar(50) default 0;
-- define CURSOR
DECLARE mycur CURSOR FOR select id from user; 
-- declare cur stop flag (sql error -> stopCur=1)
DECLARE CONTINUE HANDLER FOR SQLSTATE ‘02000‘ SET stopCur=1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET stopCur=1;

    2、open,执行 fetch 循环

-- open CURSOR
OPEN cur;
-- Execute only once
FETCH cur INTO userId;
WHILE stopCur<>1 DO
    BLOCKA:BEGIN
       set insertsql=‘‘;
       set insertsql=concat(‘insert into newUser(id,name,age) select id,name,age from user where id="‘+userId+‘"‘); 
       set @sqlinsert=insertSql;
       prepare stmtinsert from @sqlinsert;
       execute stmtinsert;
    END BLOCKA;
    -- Execute i-1 times  
    fetch cur into userId;
END WHILE 
CLOSE cur;

MySQL 游标(cursor)简单应用

标签:os   使用   ar   for   sp   on   c   new   ef   

原文地址:http://my.oschina.net/chinamummy29/blog/313986

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!