Monday, October 5, 2015

Learn Plsql - Loops


Basic loop 

Basic loop structure encloses sequence of statements in between the LOOP and END LOOP statements. With each iteration, the sequence of statements is executed and then control resumes at the top of the loop.

Syntax:
The syntax of a basic loop in PL/SQL programming language is:

LOOP
  Sequence of statements;
END LOOP;


Sample code:

DECLARE
  i NUMBER :=1;
  BEGIN
  LOOP
    dbms_output.put_line('i value is'||i);
    i   := i+1;
    IF i > 10 THEN
      EXIT;
    END IF;
  END LOOP;
  --end loop;
  dbms_output.put_line(' this is end of loop');
END;


Sample output :

i value is1
i value is2
i value is3
i value is4
i value is5
i value is6
i value is7
i value is8
i value is9
i value is10
 this is end of loop




WHILE LOOP


A WHILE LOOP statement in PL/SQL programming language repeatedly executes a target statement as long as a given condition is true.

Syntax:


WHILE condition LOOP
   sequence_of_statements
END LOOP;

Sample code


DECLARE
  i NUMBER :=1;
BEGIN
  while i < 10 LOOP
    dbms_output.put_line('i value is'||i);
    i   := i+1;
  END LOOP;
  --end loop;
  dbms_output.put_line(' this is end of loop');
END;


Output :

i value is1
i value is2
i value is3
i value is4
i value is5
i value is6
i value is7
i value is8
i value is9
i value is10
 this is end of loop



 FOR LOOP

A FOR LOOP is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

Syntax:
FOR counter IN initial_value .. final_value LOOP
   sequence_of_statements;
END LOOP;



DECLARE
   i number(2);
BEGIN
   FOR i in 10 .. 15 LOOP
       dbms_output.put_line('value of i: ' || i);
  END LOOP;
END;
/

No comments:

Post a Comment