1

I wanted to know how to insert into a table using stored procedures in DB2 using SQL. I have created a table as follows:

create table ADCLIBT.Itest
(ITNBR CHAR(15) CCSID 65535 NOT NULL DEFAULT '');

This table contains a list of items. Using this list I want to insert various other fields to another table. But, just for example sake, let's say I just want to insert these values one by one using cursors. I have written the stored procedure as follows:

create procedure ADCLIBT.itest1()
    LANGUAGE SQL
BEGIN
    DECLARE itemno char(15);
    DECLARE END_TABLE INT DEFAULT 0;
    DECLARE not_found CONDITION FOR SQLSTATE '20000';
    DECLARE c CURSOR FOR 
        select ITNBR from ADCLIBT.ITEMAT;
    DECLARE CONTINUE HANDLER FOR not_found
    SET END_TABLE = 1;

    open c;
    fetch from c into itemno;
    WHILE END_TABLE = 0 DO
        insert into ADCLIBT.ITEST
                (ITNBR)
                values
        (select a.ITNBR from ADCLIBT.ITEMAT a where ITNBR=itemno GROUP BY a.ITNBR);
    END WHILE;
    Close c;
END;

This is giving me an infinite loop. Can anyone please tell me how do I stop the infinite loop and insert these records. I want to use the cursor because I want to further use itemno to compare and get single results.

1 Answer 1

1

You are opening the cursor but not feching in the while, you must do a fetch in the while of the cursor. Here an example from the IBM documentation.

CREATE PROCEDURE sum_salaries(OUT sum INTEGER) LANGUAGE SQL
BEGIN
DECLARE SQLSTATE CHAR(5) DEFAULT '00000';
DECLARE p_sum INTEGER;
DECLARE p_sal INTEGER;
DECLARE c CURSOR FOR SELECT SALARY FROM EMPLOYEE;

 SET p_sum = 0;

 OPEN c;

 FETCH FROM c INTO p_sal;

 WHILE(SQLSTATE = '00000') DO
    SET p_sum = p_sum + p_sal;
    FETCH FROM c INTO p_sal; 
 END WHILE;

 CLOSE c;

 SET sum = p_sum;

END%
Sign up to request clarification or add additional context in comments.

5 Comments

Yes, if you don't do that you are just in the first row.
Thanks for the prompt reply.I tried doing it but it is still giving an infinite loop. 'open c; fetch from c into itemno; WHILE END_TABLE = 0 DO insert into ADCLIBT.ITEST (ITNBR) values (select a.ITNBR from ADCLIBT.ITEMAT a where ITNBR=itemno GROUP BY a.ITNBR); fetch from c into itemno; END WHILE; Close c;' There are around 10k rows
Sorry... I have not clue what is going on.
can you tell me if I should use the continue handler or an EXIT handler to get out of the table after the records are all gone through?
Got it finally, how to do this. The DECLARE not_found CONDITION FOR SQLSTATE '20000'; was giving a problem , so I just used the normal continue` handler with NOT FOUND

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.