Jun 21, 2010

CONTINUE Statement in PL/SQL (Oracle 11g):

We -as developers- know that most programming languages have CONTINUE statement to skip to next iteration of the loop, but unfortunately we didn't have in Oracle, so we used to do workaround code to imitate CONTINUE functionality. Say we have the following loop code:
SET serveroutput ON
DECLARE
BEGIN
  FOR i IN 1 .. 10
  LOOP
    DBMS_OUTPUT.put_line ('The current number is ' || i);
  END LOOP;
END;

And if we don't want to print for 4,6 and 8 numbers we would do some of the following workarounds:
Use label:

SET serveroutput ON
DECLARE
BEGIN
  FOR i IN 1 .. 10
  LOOP
    IF (I IN (4,6,8)) THEN
      GOTO FOO ;
    END IF;
    DBMS_OUTPUT.PUT_LINE ('The current number is ' || I);
    <<FOO>> NULL;
  END LOOP;
END;

Or use IF ELSE:
SET serveroutput ON
DECLARE
BEGIN
  FOR i IN 1 .. 10
  LOOP
    IF (I NOT IN (4,6,8)) THEN
      DBMS_OUTPUT.PUT_LINE ('The current number is ' || I);
    ELSE
      NULL;
    END IF;
  END LOOP;
END;

etc...

The good news is we don't have to do previous code. In Oracle 11g a new feature is introduced to enable user to enable the developer to explicitly use CONTINUE statement:
SET serveroutput ON
DECLARE
BEGIN
  FOR i IN 1 .. 10
  LOOP
    CONTINUE WHEN i IN (4,6,8);
    DBMS_OUTPUT.put_line ('The current number is ' || i);
  END LOOP;
END;

Or write:
SET serveroutput ON
DECLARE
BEGIN
  FOR i IN 1 .. 10
  LOOP
    IF I IN (4,6,8) THEN
      CONTINUE;
    END IF;
    DBMS_OUTPUT.put_line ('The current number is ' || i);
  END LOOP;
END;


And viola....

Saad Nayef,

Jun 17, 2010

Escape special character (Still some people don't know 10g mechanism!):





To escape single quote in a string we used to add another single quote before -or after :)- the original single quote to consider those two single quote as one single quote within the string and not a string terminator, as the following:


SELECT 'I don''t like my brother''s car'
  FROM DUAL


But do we have to do that for every single quote? Well we had to do it, but not anymore. In oracle 10g a new feature is introduced to make it easier to Oracle developers. The previous query would be:


SELECT q'!I don't like my brother's car!'
  FROM DUAL


You may notice the exclamation mark "!" which is not the only character you can use, you can use "[" and "]" as start and end respectively, or any character that is found in the original string with a succeeding single quote and it's better to choose a special character like "[ and ]", "{ and }", "!" ....
All of these queries are right:


SELECT q'[I don't like my brother's car]'
  FROM DUAL
 
SELECT q'{I don't like my brother's car}'
  FROM DUAL

Even:


SELECT q'ZI don't like my brother's carZ'
  FROM DUAL




Saad Nayef,