v The For loop iterates a range of numeric values.
v For loop is a programming language conditional iterative statement which is used to check for certain conditions and then repeatedly execute a block of code as long as those conditions are met.
BREAK:
v Specifies that a loop should stop being processed.
CONTINUE:
v Specifies that a loop should stop processing the current iteration, and should immediately start processing the next.
FOR LOOP EXAMPLE 1:
To create a Procedure with For loop:
Create procedure "KABIL_PRACTICE"."FORLOOP_1"
as begin
declare i integer;
create column table "KABIL_PRACTICE"."FOR_LOOP_1" ("ID" integer);
for i in 1..10 do
insert into "KABIL_PRACTICE"."FOR_LOOP_1" values(:i);
end for;
end;
To call the Procedure:
call "KABIL_PRACTICE"."FORLOOP_1";
select * from "KABIL_PRACTICE"."FOR_LOOP_1"
Result:
FOR LOOP EXAMPLE 2:
To create the table for inserting a records:
CREATE COLUMN TABLE "KABIL_PRACTICE"."FOR_LOOP_2"(LOOP_1 INT);
To create a Procedure with For loop:
create procedure "KABIL_PRACTICE"."FOR_LOOP_TEST"
AS
BEGIN
DECLARE N_START INTEGER :=3;
DECLARE
N_STOP INTEGER :=6;
DECLARE I INT;
FOR I IN N_START .. N_STOP DO
N_STOP :=100;
INSERT INTO "KABIL_PRACTICE"."FOR_LOOP_2" VALUES (I);
END FOR;
END;
To call the Procedure:
CALL "KABIL_PRACTICE"."FOR_LOOP_TEST";
select * from "KABIL_PRACTICE"."FOR_LOOP_2"
Result:
Note:
Here the value starts from “3” and ends at “100”.
FOR LOOP EXAMPLE 3:
To create the table for inserting a records:
CREATE COLUMN TABLE "KABIL_PRACTICE"."FOR_LOOP_3"(LOOP_1 INT);
To create a Procedure with For loop:
create procedure "KABIL_PRACTICE"."FOR_LOOP_TEST1"(IN N_START INT,IN N_STOP INT)
AS
BEGIN
DECLARE I INT;
FOR I IN :N_START .. :N_STOP DO
INSERT INTO "KABIL_PRACTICE"."FOR_LOOP_3" VALUES (I);
END FOR;
END;
To call the Procedure:
CALL "KABIL_PRACTICE"."FOR_LOOP_TEST1" (3,6);
select * from "KABIL_PRACTICE"."FOR_LOOP_3"
Result:
FOR LOOP EXAMPLE 4:
To create a Procedure with For loop:
create procedure "KABIL_PRACTICE"."FOR_LOOP_TEST2"(IN N_START INT,IN N_STOP INT)
AS
BEGIN
DECLARE I INT;
FOR I IN REVERSE :N_START .. :N_STOP DO
INSERT INTO "KABIL_PRACTICE"."FOR_LOOP_4" VALUES (I);
END FOR;
END;
To call the Procedure:
CALL "KABIL_PRACTICE"."FOR_LOOP_TEST2" (3,6);
select * from "KABIL_PRACTICE"."FOR_LOOP_4"
Result:
Note:
Reverse keyword - it inserts the values in a reverse order.
FOR LOOP EXAMPLE 5:
CREATE COLUMN TABLE "KABIL_PRACTICE"."FACTORIAL_LOOP"
(
RESULT INT
);
To create a Procedure with For loop to find the factorial :
CREATE PROCEDURE "KABIL_PRACTICE"."FACTORIAL_USING_LOOP"(IN FACT INT)
AS BEGIN
DECLARE HOLD INT :=1;
DECLARE I INT;
FOR I IN REVERSE 1 .. FACT DO
HOLD :=HOLD*I;
END FOR;
INSERT INTO "KABIL_PRACTICE"."FACTORIAL_LOOP" VALUES(HOLD);
END;
To call the Procedure:
CALL "KABIL_PRACTICE"."FACTORIAL_USING_LOOP" (8);
SELECT * FROM "KABIL_PRACTICE"."FACTORIAL_LOOP";
Result:
Nice
ReplyDelete