mysql - 存储过程不在mysql中使用游标返回多行

标签 mysql stored-procedures cursor

这是我见过的示例程序Blog written by Kevin Bedell我无法从 mysql 中的以下过程中获取所有记录。当我调用此过程时,它返回单行 -

存储过程-

DELIMITER $$
USE `test`$$
DROP PROCEDURE IF EXISTS `usp_cursor_example`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `usp_cursor_example`(
   IN name_in VARCHAR(255)
)
READS SQL DATA
BEGIN
  DECLARE name_val VARCHAR(255);
  DECLARE status_update_val VARCHAR(255);
  DECLARE no_more_rows BOOLEAN;
  DECLARE loop_cntr INT DEFAULT 0;
  DECLARE num_rows INT DEFAULT 0;
  DECLARE friends_cur CURSOR FOR
     SELECT
        `name`
     , status_update
     FROM test.friend_status
     WHERE `name` = name_in;
  DECLARE CONTINUE HANDLER FOR NOT FOUND
SET no_more_rows = TRUE;
OPEN friends_cur;
 SELECT FOUND_ROWS() INTO num_rows;
  the_loop: LOOP
  FETCH  friends_cur
 INTO   name_val
,      status_update_val;
IF no_more_rows THEN
    CLOSE friends_cur;
    LEAVE the_loop;
END IF;
SET loop_cntr = loop_cntr + 1;
END LOOP the_loop;
SELECT name_val, status_update_val;
-- SELECT num_rows, loop_cntr;
END$$
DELIMITER ;

运行使用 -

call usp_cursor_example('John');

它应该返回 4 行,但它只返回 4 行中的第一行。

表结构-

drop table if exists test.friend_status; 

CREATE TABLE IF NOT EXISTS `test`.`friend_status` (
    `id`            INTEGER(10) unsigned NOT NULL auto_increment,
    `name`          VARCHAR(255) NOT NULL,
    `status_update` VARCHAR(255) NOT NULL,
    PRIMARY KEY (`id`)
);

insert into test.friend_status
    (name, status_update)
  values
      ('John',  'Woke up. Guiness for Brkfst.')
    , ('Fred',  'is thinking about joining the circus')
    , ('Erin',  "Getting ready for a job interview")
    , ('Amy',   'at work and dreaming of kittens')
    , ('John',  'Watching Scooby Doo reruns. Guiness for Lunch.')
    , ('Amy',   'dreaming of fuzzy slippers and wedding dresses')
    , ('Julie', 'is hating working two jobs')
    , ('John',  'Out of the shower finally. Guiness for Dinner.')
    , ('Erin',  "if I don't get this job, I'll be asking 'Paper or Plastic?'")
    , ('Amy',   'dreaming of Meeting Mr. Right!')
    , ('Erin',  'Nailed the job interview -- calling John to celebrate!')
    , ('Amy',   'John called -- meeting him at the pub!')
    , ('John',  'Heading out to meet friends for some Guiness!')
;

我没有在堆栈溢出中看到任何答案,但使用这些答案我无法获取所有记录。请建议我从存储过程中获取这些记录的方法是什么?

最佳答案

SELECT name_val, status_update_val;

将上面的行放在循环中以获取所有记录。

关于mysql - 存储过程不在mysql中使用游标返回多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34413348/

相关文章:

java - 如何从游标中删除唯一值

php - WordPress 帖子按类别和日期排序

mysql - 在不知道上限的情况下使用spark并行读取sql数据库

MySQL 错误 : PROCEDURE can't return a result set in the given context

MySQL 函数 REPLACE 抛出语法错误

oracle - Oracle Procedure error “declaration of cursor '“我们不完整或格式错误”?

mysql - 无法初始化提供程序。架构缺失或不正确。用于 MySql.Web 连接器

mysql - 使用 JOIN 查询检索记录

sql - 我在这个 MySQL 存储过程中做错了什么?

MySQL 版本 5.5.37 : Dropping tables older than 30 days using CURSOR