DB2 (Procedure) stored procedure traversal loop

 

Because sometimes some complex business logic will be processed through the loop statement of the stored procedure; the following lists the loop statements of the two DB2 stored procedures, which is convenient for future viewing and use!

I recommend the use of the first method, the biggest advantage is that it is more intuitive; when many fields need to be manipulated, there is no need to define too many field variables as an intermediate storage medium.

1. FOR method (FOR .. AS [cursor name] CURSOR FOR [SELECT...])

BEGIN -- statement block, must be added, otherwise an error will occur.
	FOR V AS MYCURSOR CURSOR FOR SELECT ID,NAME,AGE FROM PEOPLE
	DO
		BEGIN
			--Business logic processing is performed here. When each row is looped, the value of each column will be stored in the V variable
			--Example: insert data into another table
			INSERT INTO PERSON(NAME,AGE) VALUES(V.NAME,V.AGE);
		END;
	END FOR;
END;

2. WHILE method (DECLARE [cursor name] CURSOR FOR [SELECT.....])

BEGIN -- statement block, must be added, otherwise an error will occur.
	DECLARE NOTFOUND INT DEFAULT 0;
	DECLARE V_NAME VARCHAR(20);
	DECLARE V_AGE VARCHAR(20);
	
	DECLARE MYCURSOR CURSOR FOR SELECT NAME,AGE FROM PEOPLE;
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET NOTFOUND = 1;
	WHILE NOTFOUND = 0 DO FETCH MYCURSOR INTO V_NAME,V_AGE -- the order here should be consistent with the query result field order
		--There will be one more loop here, so you need to add a judgment
		IF(NOTFOUND = 0)
		THEN
			INSERT INTO PERSON(NAME,AGE) VALUES(V_NAME,V_AGE);
		END IF;
	END WHILE;
END;

 

refer to:

http://www.cnblogs.com/javalism/p/3511742.html

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326936192&siteId=291194637