Link to home
Start Free TrialLog in
Avatar of Raja Jegan R
Raja Jegan RFlag for India

asked on

Cursor Not Closing Properly in DB2

Hi,
   My Procedure (given below) which is used to Insert/Update/ Delete records from one database to another using Federated Server. The cursor used in it is not exiting out properly. It runs till the last record correctly and for the Last record in the cursor it executes infinite times and I have to stop the execution of procedure manually.

Can anyone tell me what is wrong in the code below. Can you try it once and suggest me what is wrong.
Since I have created it, I am not able to identify the reason and thought a third eye will help me in that.
Thanks in advance.

Regards,
rrjegan17
DROP PROCEDURE test.proc@
 
CREATE PROCEDURE test.proc (
   IN P_jobexecid INTEGER
)
LANGUAGE SQL
BEGIN
    DECLARE EOF INT DEFAULT 0;
    DECLARE P_col1 INTEGER;
    DECLARE P_col2 VARCHAR(40);
    DECLARE P_col3 VARCHAR(60);
    DECLARE P_col4 VARCHAR(20000);
    DECLARE SQLCODE INTEGER DEFAULT 0;
 
    DECLARE query_cur CURSOR FOR
    SELECT col1,col2,col3,col4
    FROM mytable;
 
    DECLARE CONTINUE HANDLER FOR NOT FOUND
    SET EOF = 1;
 
        OPEN query_cur;
        FETCH query_cur INTO P_col1, P_col2, P_col3, P_col4;
        WHILE (SQLCODE <> 100)
        DO
              EXECUTE IMMEDIATE P_col4;
 
              IF SQLCODE < 0
              THEN
                   ROLLBACK WORK;
-- Have to rollback if any of the Execute Immediate command Fails and exit the cursor immediately.
              END IF;
 
              FETCH query_cur INTO P_col1, P_col2, P_col3, P_col4;
        END WHILE;
        CLOSE query_cur;
 
    COMMIT WORK;
 
END@

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of momi_sabag
momi_sabag
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Raja Jegan R

ASKER

Have added that Continue Handler during testing of the query and forgot to remove it.
Thanks for pointing it out.
Will test it and revert back.
As I mentioned earlier, I included that one for testing and forgot to remove it.
And definitely your third eye on it helped me out.
Thanks momi_sabag