首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于参数的MySQL存储过程游标

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

Stack Overflow用户
提问于 2015-12-31 15:42:52
回答 1查看 6.8K关注 0票数 1

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

例如:

代码语言:javascript
复制
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

有人能给我举个简单的例子来说明如何做到这一点吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-12-31 23:39:02

问题

  • 语法错误时,声明游标语句需要精确地与一个选择查询相关联: DECLARE cursor_name CURSOR FOR select_statement
  • 表也是一个保留关键字,需要转义(或使用不同的名称): SELECT columns FROM Table

要修复,可以为每个场景创建两个游标,或者在一个选择查询中嵌入两个查询路径。

设置

代码语言:javascript
复制
create table `Table`
(
  id integer primary key auto_increment not null,
  userid integer not null,
  modified_on datetime not null
);

固定

代码语言:javascript
复制
-- 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集的处理。

参考

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34548583

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档