我不太熟悉MySQL存储过程,但我正在尝试第一次编写一个。在我的过程中,我有2个参数,其中一个或两个参数都是空的。我需要创建一个游标来循环,但是我的游标需要基于in参数。如果1为null,而另一个为null,则游标查询不同。
例如:
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有人能给我举个简单的例子来说明如何做到这一点吗?
发布于 2015-12-31 23:39:02
问题
DECLARE cursor_name CURSOR FOR select_statementSELECT 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集的处理。
参考
https://stackoverflow.com/questions/34548583
复制相似问题