我目前正在试验存储过程,我尝试实现一个简单的IF / ELSE语句。我正在使用DB2,如果procedure参数为null,并且如果参数不为null,则我尝试选择所有记录,查询数据库。
我的存储过程代码如下:
DROP PROCEDURE LWILSON.IFQUERY@
CREATE PROCEDURE LWILSON.IFQUERY
(
IN p_type VARCHAR(15)
)
DYNAMIC RESULT SETS 1
LANGUAGE SQL
BEGIN
DECLARE c_result CURSOR WITH RETURN FOR
IF p_type IS NULL
THEN
SELECT * FROM LWILSON."ANIMALS";
OPEN c_result;
ELSE
SELECT ID,TYPE,NAME,WEIGHT, AGE FROM LWILSON."ANIMALS" AS ANIMALRESULTS WHERE ANIMALRESULTS.type = p_type;
OPEN c_result;
END IF;
END@
(我使用@符号作为命令分隔符)。 我在尝试执行该过程时收到的错误消息如下...
感谢任何帮助。感谢。
答案 0 :(得分:1)
您可以通过准备要执行的语句来实现。在这种情况下,您不需要两个游标:
CREATE OR REPLACE PROCEDURE LWILSON.IFQUERY (
IN p_type VARCHAR(15)
)
DYNAMIC RESULT SETS 1
LANGUAGE SQL
BEGIN
DECLARE STMT VARCHAR(120);
DECLARE c_result CURSOR
WITH RETURN FOR RES_SET;
IF (p_type IS NULL) THEN
SET STMT = "SELECT * FROM LWILSON.ANIMALS";
ELSE
SET STMT = "SELECT ID, TYPE, NAME, WEIGHT, AGE "
|| "FROM LWILSON.ANIMALS AS ANIMALRESULTS "
|| "WHERE ANIMALRESULTS.type = " || p_type;
END IF;
PREPARE RES_SET FROM STMT
OPEN c_result;
END@
答案 1 :(得分:0)
我找到的最佳选择是为每个条件创建一个光标并打开你需要的光标。
DECLARE cursor1 CURSOR
WITH RETURN FOR SELECT * FROM LWILSON.ANIMALS;
DECLARE cursor2 CURSOR
WITH RETURN FOR SELECT * FROM LWILSON.ANIMALS AS ANIMALRESULTS
WHERE ANIMALRESULTS.type = p_type;
IF (p_type IS NULL) THEN
OPEN cursor1;
ELSE
OPEN cursor2;
END IF;