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

标签 mysql stored-procedures

我不是很熟悉 MySQL 存储过程,但我是第一次尝试编写一个。在我的过程中,我有 2 个参数,其中一个或两个可以为空。我需要创建一个游标来循环,但我的游标需要基于 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

谁能给我一个简单的例子来说明如何实现这一点?

最佳答案

问题

  • syntax error, the declare cursor statement requires to be associated with exactly one select query :

    DECLARE cursor_name CURSOR FOR select_statement

  • also Table is a reserved keyword and needs to be escaped ( or use a different name ) in :

    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 集的处理


引用

关于基于参数的MySQL存储过程游标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34548583/

相关文章:

php - 使用sql按家庭搜索表

postgresql - 如何确保存储函数始终返回 TRUE 或 FALSE?

stored-procedures - SQL Server 2012 存储过程被自动删除

mysql - SQLite空指针异常

c# - 如何使用 MySql 和 Umbraco 4.7.1 为波斯尼亚语(或克罗地亚语或斯洛文尼亚语)字符集设置编码

Mysql 选择列中仅具有指定值的行

php - 将 Webform 推送到 vTiger

php - 进入存储过程,需要帮助转换查询

php - 使用 php(mysqli) 的连续 mysql 过程调用不会产生结果

sql - 插入表并跳过重复项