服务器之家:专注于服务器技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - Mysql - mysql动态游标学习(mysql存储过程游标)

mysql动态游标学习(mysql存储过程游标)

2020-01-20 14:41MYSQL教程网 Mysql

mysql动态游标示例,通过准备语句、视图和静态游标实现,大家参考使用吧

代码如下:


-- 建立测试表和数据
create table webuser (username varchar(10));
insert into webuser values ('a1'),('a2'),('a3'),('b1'),('b2'),('b3');
commit;

-- 建立存储过程
drop procedure if exists dynamic_cursor;
delimiter //
CREATE PROCEDURE dynamic_cursor (IN p_name varchar(10))
BEGIN
    DECLARE done INT DEFAULT 0;
    DECLARE v_username varchar(10);
    DECLARE cur CURSOR for( SELECT username from webuser_view);
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

    DROP VIEW IF EXISTS webuser_view;

    SET @sqlstr = "CREATE VIEW webuser_view as ";
    SET @sqlstr = CONCAT(@sqlstr , "SELECT username FROM webuser WHERE username like '", p_name,"%'");

    PREPARE stmt FROM @sqlstr;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

    OPEN cur;
    f_loop:LOOP 
    FETCH cur INTO v_username;
    IF done THEN
        LEAVE f_loop;  
    END IF;
    SELECT v_username;    
    END LOOP f_loop;
    CLOSE cur;
END;
//
delimiter ;

-- 测试
call dynamic_cursor('a');

延伸 · 阅读

精彩推荐