Sunday, July 17, 2011

Iterative Control in PL/pgSQL

LOOP Statements
  • Loops repeat a statement or sequence of statements multiple times.
  • There are three loop types:
    • Basic loop
    • FOR loop
    • WHILE loop
Basic Loops
  • Syntax :
          LOOP
          statement1;
          . . .
          EXIT [WHEN condition];
          END LOOP;
  • Example :
         create or replace function f2() returns void as
         $$
         DECLARE
         ctr numeric:=0;
         BEGIN
               LOOP
                     raise notice '%',ctr;
                     ctr:=ctr+1;
                     EXIT WHEN ctr > 3;
               END LOOP;
         END;
$$ language plpgsql;

WHILE Loops
  • Syntax :
          WHILE condition LOOP
          statement1;
          statement2;
          . . .
          END LOOP;
  • Use the WHILE loop to repeat statements 
  • while a condition is TRUE.
FOR Loops
  • Use a FOR loop to shortcut the test for the numeric of iterations.
  • Do not declare the counter; it is declared implicitly.
  • 'lower_bound .. upper_bound' is required syntax.
          FOR counter IN [REVERSE]
          lower_bound..upper_bound LOOP
          statement1;
          statement2;
          . . .
          END LOOP;
  • Example :
          create or replace function f3() returns void as
          $$
          BEGIN
          FOR ctr IN 1..3 LOOP
          raise notice '%',ctr;
          END LOOP;
          END;
          $$ language plpgsql;

Loop through Query Results



FOR record_or_row IN query LOOP
statements
END LOOP [ label ];
create or replace function f4() returns void as
$$
DECLARE
rec emp%ROWTYPE;
BEGIN
FOR rec IN select * from emp LOOP
raise notice '%',rec.ename;
END LOOP;
END;
$$ language plpgsql;

Saturday, July 16, 2011

Controlling Flow of Execution in plsql

Controlling Flow of Execution


IF Statements


Syntax:

IF condition THEN
statements;
[ELSIF condition THEN
statements;]
[ELSE
statements;]
END IF;


Simple IF Statement

DECLARE
myage numeric:=31;
BEGIN
IF myage < 11
THEN
raise notice ' I am a child ';
END IF;
END;


IF THEN ELSE Statement

DECLARE
myage numeric:=31;
BEGIN
IF myage < 11
THEN
raise notice ' I am a child ';
ELSE
raise notice ' I am not a child ';
END IF;
END;


CASE Expressions: Example

DECLARE
grade varchar := UPPER('a');
appraisal varchar(20);
BEGIN
appraisal :=
CASE grade
WHEN 'A' THEN 'Excellent'
WHEN 'B' THEN 'Very Good'
WHEN 'C' THEN 'Good'
ELSE 'No such grade'
END;
END;



Followers