Loop statement

The basic LOOP statement has the following structure:

[ <<label>> ]
LOOP
statements
END LOOP [ label ];

To understand the LOOP statement, let's rewrite the factorial function, as follows:

DROP FUNCTION IF EXISTS factorial (int);
CREATE OR REPLACE FUNCTION factorial (fact int) RETURNS BIGINT AS $$
DECLARE
result bigint = 1;
BEGIN
IF fact = 1 THEN RETURN 1;
ELSIF fact IS NULL or fact < 1 THEN RAISE EXCEPTION 'Provide a positive integer';
ELSE
LOOP
result = result*fact;
fact = fact-1;
EXIT WHEN fact = 1;
END Loop;
END IF;
RETURN result;
END; $$ LANGUAGE plpgsql;

In the preceding code, the conditional EXIT statement is used to prevent infinite looping by exiting the LOOP statement. When an EXIT statement is encountered, the execution control goes to the first statement after the LOOP. To control the execution of the statements inside the LOOP statement, PL/pgSQL also provides the CONTINUE statement, which works somewhat like the EXIT statement. Thus, instead of forcing termination, the CONTINUE statement forces the next iteration of the loop to take place, skipping any code in between.

The usage of the CONTINUE and EXIT statements, especially in the middle of a code block, is not encouraged because it breaks the execution order, which makes the code harder to read and understand.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset