MySQL游标多次获取唯一的第一条记录

时间:2014-02-21 21:19:05

标签: mysql stored-procedures cursor

我的存储过程是这样的:

CREATE PROCEDURE `kiosk_pro`.`setTimeAdjustForNext`(tokenno int,cdate date)
    /*LANGUAGE SQL
    | [NOT] DETERMINISTIC
    | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
    | SQL SECURITY { DEFINER | INVOKER }
    | COMMENT 'string'*/
    BEGIN

        declare lo_SNO int;

        declare lo_TokenNo int;


        DECLARE done INT DEFAULT FALSE ;

       Declare mycur Cursor for( select  SNO  from kiosk_token_generation  where TokenDate=cdate and  TokenNo >= tokenno order by TokenNo );
              DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = TRUE;
       open mycur;

        time_loop :LOOP 

              FETCH mycur into lo_SNO;

             if done then 
                 close mycur;  
                  leave time_loop;
             end if;

            select lo_SNO ;

           end loop time_loop;


    END$$

实际上我的表在SNO列中有3条记录1,2,3和1,2,3英寸 TokenNo列,我通过传递date ='2014-02-22'tokenno=1来调用上面的存储过程,但是它返回了3次值。

我在哪里弄错了?

1 个答案:

答案 0 :(得分:0)

您的SP工作正常

也许你在另一个数据库中有另一个SP

create table kiosk_token_generation (SNO  int, TokenNo int, TokenDate datetime);
INSERT INTO kiosk_token_generation (SNO, TokenNo, TokenDate) VALUES (1,1,'2014-02-22');
INSERT INTO kiosk_token_generation (SNO, TokenNo, TokenDate) VALUES (2,2,'2014-02-22');
INSERT INTO kiosk_token_generation (SNO, TokenNo, TokenDate) VALUES (3,3,'2014-02-22');



DELIMITER $$
CREATE PROCEDURE setTimeAdjustForNext(tokenno int,cdate date)
    BEGIN
       declare lo_SNO int;
       declare lo_TokenNo int;
       DECLARE done INT DEFAULT FALSE;
       Declare mycur Cursor for( select  SNO  from kiosk_token_generation  where TokenDate=cdate and  TokenNo >= tokenno order by TokenNo );
       DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = TRUE;
       open mycur;
       time_loop :LOOP
              FETCH mycur into lo_SNO;
             if done then
                 close mycur;
                 leave time_loop;
             end if;
            select lo_SNO ;
           end loop time_loop;
    END$$
DELIMITER ;






select  SNO  from kiosk_token_generation  where TokenDate='2014-02-22' and  TokenNo >= 1 order by TokenNo

CALL setTimeAdjustForNext (1, '2014-02-22');