存储过程不使用mysql中的Cursor返回多行

时间:2015-12-22 10:14:29

标签: 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!')
;

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

1 个答案:

答案 0 :(得分:0)

SELECT name_val, status_update_val;

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