LiamWilson94
LiamWilson94

Reputation: 458

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... Error message

Any help is appreciated. Thanks.

Upvotes: 2

Views: 19021

Answers (2)

Ivan
Ivan

Reputation: 31

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;

Upvotes: 1

AngocA
AngocA

Reputation: 7693

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@

Upvotes: 3

Related Questions