简体   繁体   中英

DB2 Stored Procedure IF statement

I am currently experimenting with stored procedures and I am try to implement a simple IF/ELSE statement. I am using DB2 and I am trying to select all records if the procedure parameter is null and if the parameter is not null, query the database.

My stored procedure code is as follows:

    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@

(I am using the @ symbol for the command separator). The error message I receive when trying to execute the procedure is as follows... 错误信息

Any help is appreciated. Thanks.

You can do that by preparing the statement to execute. You do not need two cursors in this case:

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@

Best option I found was creating one cursor for each condition and opening the one you need.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM