racerxnox
racerxnox

Reputation: 21

How to insert into a table using stored procedures in DB2 using SQL?

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.

Upvotes: 1

Views: 12917

Answers (1)

sebmaldo
sebmaldo

Reputation: 59

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%

Upvotes: 1

Related Questions