MySQL存储过程基于参数的游标

时间:2015-12-31 15:42:52

标签: mysql stored-procedures

我对MySQL存储过程不是很熟悉,但我是第一次尝试写一个。在我的程序中,我有2个参数,其中一个或两个可以为null。我需要创建一个游标来循环,但我的光标需要基于in参数。如果1为空而另一个不为,则我的光标查询不同。

例如:

CREATE PROCEDURE test (IN date timestamp, IN id int(11))
BEGIN
     DECLARE cur CURSOR FOR 
     IF timestamp IS NOT NULL THEN
          IF id IS NULL THEN
               SELECT columns FROM Table WHERE modified_on <= timestamp
          ELSE
               SELECT columns FROM Table WHERE userid = id AND modified_on <= timestamp
     ELSE
          /* Logic here to pull query without the timestamp and where userid matches if the id passed in is not null */
     END IF
END

有人能告诉我一个如何实现这个目标的简单例子吗?

1 个答案:

答案 0 :(得分:1)

<强>问题

  
      
  • 语法错误,declare cursor statement只需要与一个选择查询相关联:

         

    DECLARE cursor_name CURSOR FOR select_statement

  •   
  • 表格也是reserved keyword,需要在以下位置进行转义(或使用其他名称):

         

    SELECT columns FROM Table

  •   

要修复,要么为每个方案创建一个游标,要么在一个选择查询中嵌入两个查询路径

<强>设置

create table `Table`
(
  id integer primary key auto_increment not null,
  userid integer not null,
  modified_on datetime not null
);

<强>修复

-- option one : combine queries into one
drop procedure if exists test;
delimiter $$
CREATE PROCEDURE test (IN date timestamp, IN id int(11))
BEGIN
     DECLARE cur CURSOR FOR SELECT columns FROM `Table` WHERE ( id is null or userid = id ) and modified_on <= timestamp;
     -- open and read from cursor..
END$$
delimiter ;

-- option two define two cursors and use conditional logic below to decide which to read from
drop procedure if exists test;
delimiter $$
CREATE PROCEDURE test (IN date timestamp, IN id int(11))
BEGIN
     DECLARE cur1 CURSOR FOR SELECT columns FROM `Table` WHERE modified_on <= timestamp;
     DECLARE cur2 CURSOR FOR SELECT columns FROM `Table` WHERE userid = id AND modified_on <= timestamp;  
     -- evaluate if/else logic here to decide which cursor to open and use..
END$$
delimiter ;

注意:不确定每个游标提取的计划是什么。根据您的使用情况,您可以在没有光标的情况下执行此操作。如果是这种情况,请不要使用游标并使处理更接近基于自然sql集的处理

<强>参考

相关问题