j-p
j-p

Reputation: 3828

DB2 stored proceedure and conditional logic

I'm trying to find an example of conditional logic inside a DB2 stored procedure.... literally a syntax example.

Specifically - I need to do one of two things based on the results from another query. So the procedure is logically something like this

SELECT x FROM y
IF x = 'a'
    UPDATE table1
else
    UPDATE table2

can anyone provide an example of this? thx

Upvotes: 0

Views: 891

Answers (1)

Ian Bjorhovde
Ian Bjorhovde

Reputation: 11052

It's not too complex:

CREATE PROCEDURE p1
   LANGUAGE SQL
BEGIN

   -- Set this to the appropriate data type.
   DECLARE varX CHAR(1);

   -- Get the value of column 'X' and store it in variable 'varX'.
   -- Make sure this query returns only a single row.  If you need
   -- to iterate over multiple values from the table 'Y' then you
   -- will need to use a cursor and use the FETCH ... INTO statement 
   -- to get each row's value into 'varX'

   SELECT x INTO varX FROM y;

   -- Do your update as necessary...
   IF varX = 'a' THEN
      update table1 ... ;
   ELSE
      update table2 ... ;
   END IF;

END
@

Upvotes: 1

Related Questions