Running a PL/SQL Program

Running a PL/SQL Program

XIX

So, here we go (drumroll, please). Let’s type a short PL/SQL program into SQL*Plus:

Although it has successfully completed, this particular program was supposed to invoke PL/SQL’s built-in program that echoes back some text. SQL*Plus’s somewhat annoying behavior is to suppress such output by default. To get it to display properly, you must use a SQL*Plus command to turn on SERVEROUTPUT:

I generally put the SERVEROUTPUT command in my startup file , causing it to be enabled until one of the following occurs:
• You disconnect, log off, or otherwise end your session.
• You explicitly set SERVEROUTPUT to OFF.
• The Oracle database discards session state either at your request or because of a compilation error.
• In Oracle versions through Oracle9i Database Release 2, you issue a new CON‐ NECT statement; in subsequent versions, SQL*Plus automatically reruns your startup file after each CONNECT.
When you enter SQL or PL/SQL statements into the console or pseudo-GUI SQL*Plus, the program assigns a number to each line after the first. There are two benefits to the line numbers: first, they help you designate which line to edit with the built-in line editor (which you might actually use one day); and second, if the database detects an error in your code, it will usually report the error accompanied by a line number. You’ll have plenty of opportunities to see that behavior in action.
To tell SQL*Plus that you’re done entering a PL/SQL statement, you must usually include a trailing slash (see line 4 in the previous example). Although mostly harmless, the slash has several important characteristics:
• The meaning of the slash is “execute the most recently entered statement,” regardless of whether the statement is SQL or PL/SQL.
• The slash is a command unique to SQL*Plus; it is not part of the PL/SQL language, nor is it part of SQL.
• It must appear on a line by itself; no other commands can be included on the line. • In most versions of SQL*Plus prior to Oracle9iDatabase, if you accidentally precede the slash with any spaces, it doesn’t work! Beginning with Oracle9i Database, SQL*Plus conveniently overlooks leading whitespace. Trailing space doesn’t matter in any version. 
As a convenience feature, SQL*Plus offers PL/SQL users an EXECUTE command, which saves typing the BEGIN, END, and trailing slash. So, the following is equivalent to the short program I ran earlier:

SQL> EXECUTE DBMS_OUTPUT.PUT_LINE('Hey look, Ma!')

A trailing semicolon is optional, but I prefer to omit it. As with most SQL*Plus com‐ mands, EXECUTE can be abbreviated and is case insensitive, so most interactive use gets reduced to:

SQL> EXEC dbms_output.put_line('Hey look, Ma!') 

Report Page