6. Generating Output from PL/SQL ProgramsThe built-in packages offer a number of ways to generate output from within your PL/SQL program. While updating a database table is, of course, a form of "output" from PL/SQL, this chapter shows you how to use two packages that explicitly generate output. UTL_FILE reads and writes information in server-side files, and DBMS_OUTPUT displays information to your screen. 6.1 DBMS_OUTPUT: Displaying OutputDBMS_OUTPUT provides a mechanism for displaying information from your PL/SQL program on your screen (your session's output device, to be more specific). As such, it serves as just about the only immediately accessible (meaning "free with PL/SQL") means of debugging your PL/SQL stored code.[ 1 ] It is certainly your "lowest common denominator" debugger, similar to the used-and-abused MESSAGE built-in of Oracle Forms. DBMS_OUTPUT is also the package you are most likely to use to generate reports from PL/SQL scripts run in SQL*Plus.
Of all the built-in packages, the DBMS_OUTPUT package (and its PUT_LINE procedure, in particular) is likely to be the one you will find yourself using most frequently. You may therefore find it strange that I never call DBMS_OUTPUT.PUT_LINE. I find the design and functionality of DBMS_OUTPUT to be substandard and very frustrating. In fact, I recommend that you never use this package -- at least, not directly. You should instead encapsulate calls to DBMS_OUTPUT (and the PUT_LINE procedure, in particular) inside a package of your own construction. This technique is discussed in the Section 6.1.6, "DBMS_OUTPUT Examples" " section later in this chapter. 6.1.1 Getting Started with DBMS_OUTPUTThe DBMS_OUTPUT package is created when the Oracle database is installed. The dbmsoutp.sql script (found in the built-in packages source code directory, as described in Chapter 1, Introduction ) contains the source code for this package's specification. This script is called by the catproc.sql script, which is normally run immediately after database creation. The script creates the public synonym DBMS_OUTPUT for the package. Instance-wise access to this package is provided on installation, so no additional steps should be necessary in order to use DBMS_OUTPUT. As far as package usage is concerned, you will almost always be using only the DBMS_OUTPUT.PUT_LINE procedure and only in SQL*Plus. The section Section 6.1.2, "Enabling and Disabling Output" " later in this chapter shows how you set up DBMS_OUTPUT for use in SQL*Plus. 6.1.1.1 DBMS_OUTPUT programsTable 6-1 shows the DBMS_OUTPUT program names and descriptions.
6.1.1.2 DBMS_OUTPUT conceptsEach user has a DBMS_OUTPUT buffer of up to 1,000,000 bytes in size. Write information to this buffer by calling the DBMS_OUTPUT.PUT and DBMS_OUTPUT.PUT_LINE programs. If you are using DBMS_OUTPUT from within SQL*Plus, this information will be displayed automatically when your program terminates. You can (optionally) explicitly retrieve information from the buffer with calls to DBMS_OUTPUT.GET and DBMS_OUTPUT.GET_LINE. The DBMS_OUTPUT buffer can be set to a size between 2,000 and 1,000,000 bytes with the DBMS_OUTPUT.ENABLE procedure. If you do not enable the package, no information will be displayed or be retrievable from the buffer. The buffer stores three different types of data -- VARCHAR2, NUMBER, and DATE -- in their internal representations. These types match the overloading available with the PUT and PUT_LINE procedures. Note that DBMS_OUTPUT does not support Boolean data in either its buffer or its overloading of the PUT procedures. The following anonymous PL/SQL block uses DBMS_OUTPUT to display the name and salary of each employee in department 10: DECLARE CURSOR emp_cur IS SELECT ename, sal FROM emp WHERE deptno = 10 ORDER BY sal DESC; BEGIN FOR emp_rec IN emp_cur LOOP DBMS_OUTPUT.PUT_LINE ('Employee ' || emp_rec.ename || ' earns ' || TO_CHAR (emp_rec.sal) || ' dollars.'); END LOOP; END; / This program generates the following output when executed in SQL*Plus: Employee KING earns 5000 dollars. Employee SCOTT earns 3000 dollars. Employee JONES earns 2975 dollars. Employee ADAMS earns 1100 dollars. Employee JAMES earns 950 dollars. 6.1.1.3 DBMS_OUTPUT exceptionsDBMS_OUTPUT does not contain any declared exceptions. Instead, Oracle designed the package to rely on two error numbers in the -20 NNN range (usually reserved for Oracle customers). You may, therefore, encounter one of these two exceptions when using the DBMS_OUTPUT package (no names are associated with these exceptions). The -20000 error number indicates that these package-specific exceptions were raised by a call to RAISE_APPLICATION_ERROR, which is in the DBMS_STANDARD package.
You may also receive the ORA-06502 error: 6.1.1.4 DBMS_OUTPUT nonprogram elementsThe DBMS_OUTPUT package defines a PL/SQL table TYPE as follows: TYPE chararr IS TABLE OF VARCHAR2(255) INDEX BY BINARY_INTEGER; The DBMS_OUTPUT.GET_LINES procedure returns its lines in a PL/SQL table of this type. 6.1.1.5 Drawbacks of DBMS_OUTPUTBefore learning all about this package, and rushing to use it, you should be aware of several drawbacks with the implementation of this functionality:
There are workarounds for almost every one of these drawbacks. The solution invariably requires the construction of a package that encapsulates and hides DBMS_OUTPUT. This technique is explained in the Section 6.1.6 " section. 6.1.2 Enabling and Disabling OutputThe ENABLE and DISABLE procedures enable and disable output from the DBMS_OUTPUT.PUT_LINE (and PUT and PUTF) procedure. 6.1.2.1 The DBMS_OUTPUT.ENABLE procedureThe ENABLE procedure enables calls to the other DBMS_OUTPUT modules. If you do not first call ENABLE, then any other calls to the package modules are ignored. The specification for the procedure is, PROCEDURE DBMS_OUTPUT.ENABLE (buffer_size IN INTEGER DEFAULT 20000); where buffer_size is the size of the buffer that will contain the information stored by calls to PUT and PUT_LINE. The buffer size can be as large as 1,000,000 bytes. You can pass larger values to this procedure without raising an error, but doing so will have no effect besides setting the buffer size to its maximum. You can call ENABLE more than once in a session. The buffer size will be set to the largest size passed in any call to ENABLE. In other words, the buffer size is not necessarily set to the size specified in the last call. If you want to make sure that the DBMS_OUTPUT package is enabled in a program you are testing, add a statement like this one to the start of the program: DECLARE ... declarations ... BEGIN DBMS_OUTPUT.ENABLE (1000000); ... END; 6.1.2.2 The DBMS_OUTPUT.DISABLE procedureThe DISABLE procedure disables all calls to the DBMS_OUTPUT package (except for ENABLE). It also purges the buffer of any remaining lines of information. Here's the specification for the procedure: PROCEDURE DBMS_OUTPUT.DISABLE; SQL*Plus and SQL*DBA offer a native command, SET SERVEROUTPUT, with which you can disable the package without having to execute the DISABLE procedure directly. You can use the command as follows: SQL> SET SERVEROUTPUT OFF This command is equivalent to the following PL/SQL statement: DBMS_OUTPUT.DISABLE; After you execute this command, any calls to PUT_LINE and other modules will be ignored, and you will not see any output. 6.1.2.3 Enabling output in SQL*PlusMost developers use DBMS_OUTPUT almost exclusively in the SQL*Plus environment. To enable output from calls to PUT_LINE in SQL*Plus, you will use the SET SERVEROUTPUT command, SET SERVEROUTPUT ON SIZE 1000000 or: SET SERVEROUTPUT ON Each of these calls the DBMS_OUTPUT.ENABLE procedure. I have found it useful to add SET SERVEROUTPUT ON SIZE 1000000 to my login.sql file, so that the package is automatically enabled whenever I go into SQL*Plus. (I guess that tells you how often I have to debug my code!) You should also check the Oracle documentation for SQL*Plus to find out about the latest set of options for the SET SERVEROUTPUT command. As of Oracle8, the documentation shows the following syntax for this SET command: SET SERVEROUT[PUT] {OFF|ON} [SIZE n] [FOR[MAT] {WRA[PPED]| WOR[D_WRAPPED]|TRU[NCATED]}] In other words, you have these options when you enable DBMS_OUTPUT in SQL*Plus:
6.1.3 Writing to the DBMS_OUTPUT BufferYou can write information to the buffer with calls to the PUT, NEW_LINE, and PUT_LINE procedures. 6.1.3.1 The DBMS_OUTPUT.PUT procedureThe PUT procedure puts information into the buffer, but does not append a newline marker into the buffer. Use PUT if you want to place information in the buffer (usually with more than one call to PUT), but not also automatically issue a newline marker. The specification for PUT is overloaded, so that you can pass data in its native format to the package without having to perform conversions, PROCEDURE DBMS_OUTPUT.PUT (A VARCHAR2); PROCEDURE DBMS_OUTPUT.PUT (A NUMBER); PROCEDURE DBMS_OUTPUT.PUT (A DATE); where A is the data being passed. 6.1.3.1.1 ExampleIn the following example, three simultaneous calls to PUT place the employee name, department ID number, and hire date into a single line in the DBMS_OUTPUT buffer: DBMS_OUTPUT.PUT (:employee.lname || ', ' || :employee.fname); DBMS_OUTPUT.PUT (:employee.department_id); DBMS_OUTPUT.PUT (:employee.hiredate); If you follow these PUT calls with a NEW_LINE call, that information can then be retrieved with a single call to GET_LINE. 6.1.3.2 The DBMS_OUTPUT.PUT_LINE procedureThe PUT_LINE procedure puts information into the buffer and then appends a newline marker into the buffer. The specification for PUT_LINE is overloaded, so that you can pass data in its native format to the package without having to perform conversions: PROCEDURE DBMS_OUTPUT.PUT_LINE (A VARCHAR2); PROCEDURE DBMS_OUTPUT.PUT_LINE (A NUMBER); PROCEDURE DBMS_OUTPUT.PUT_LINE (A DATE); The PUT_LINE procedure is the one most commonly used in SQL*Plus to debug PL/SQL programs. When you use PUT_LINE in these situations, you do not need to call GET_LINE to extract the information from the buffer. Instead, SQL*Plus will automatically dump out the DBMS_OUTPUT buffer when your PL/SQL block finishes executing. (You will not see any output until the program ends.) Of course, you can also call DBMS_OUTPUT programs directly from the SQL*Plus command prompt, and not from inside a PL/SQL block, as shown in the following example. 6.1.3.2.1 ExampleSuppose that you execute the following three statements in SQL*Plus: SQL> exec DBMS_OUTPUT.PUT ('I am'); SQL> exec DBMS_OUTPUT.PUT (' writing '); SQL> exec DBMS_OUTPUT.PUT ('a '); You will not see anything, because PUT will place the information in the buffer, but will not append the newline marker. When you issue this next PUT_LINE command, SQL> exec DBMS_OUTPUT.PUT_LINE ('book!'); you will then see the following output: I am writing a book! All of the information added to the buffer with the calls to PUT waited patiently to be flushed out with the call to PUT_LINE. This is the behavior you will see when you execute individual calls at the SQL*Plus command prompt to the put programs. If you place these same commands in a PL/SQL block, BEGIN DBMS_OUTPUT.PUT ('I am'); DBMS_OUTPUT.PUT (' writing '); DBMS_OUTPUT.PUT ('a '); DBMS_OUTPUT.PUT_LINE ('book'); END; / the output from this script will be exactly the same as that generated by this single call: SQL> exec DBMS_OUTPUT.PUT_LINE ('I am writing a book!'); 6.1.3.3 The DBMS_OUTPUT.NEW_LINE procedureThe NEW_LINE procedure inserts an end-of-line marker in the buffer. Use NEW_LINE after one or more calls to PUT in order to terminate those entries in the buffer with a newline marker. Here's the specification for NEW_LINE: PROCEDURE DBMS_OUTPUT.NEW_LINE; 6.1.4 Retrieving Data from the DBMS_OUTPUT BufferYou can use the GET_LINE and GET_LINES procedures to extract information from the DBMS_OUTPUT buffer. If you are using DBMS_OUTPUT from within SQL*Plus, however, you will never need to call either of these procedures. Instead, SQL*Plus will automatically extract the information and display it on the screen for you. 6.1.4.1 The DBMS_OUTPUT.GET_LINE procedureThe GET_LINE procedure retrieves one line of information from the buffer. Here's the specification for the procedure: PROCEDURE DBMS_OUTPUT.GET_LINE (line OUT VARCHAR2, status OUT INTEGER); The parameters are summarized in the following table.
The line can have up to 255 bytes in it, which is not very long. If GET_LINE completes successfully, then status is set to 0. Otherwise, GET_LINE returns a status of 1. Notice that even though the PUT and PUT_LINE procedures allow you to place information into the buffer in their native representations (dates as dates, numbers and numbers, and so forth), GET_LINE always retrieves the information into a character string. The information returned by GET_LINE is everything in the buffer up to the next newline character. This information might be the data from a single PUT_LINE or from multiple calls to PUT. 6.1.4.1.1 ExampleThe following call to GET_LINE extracts the next line of information into a local PL/SQL variable: FUNCTION get_next_line RETURN VARCHAR2 IS return_value VARCHAR2(255); get_status INTEGER; BEGIN DBMS_OUTPUT.GET_LINE (return_value, get_status); IF get_status = 0 THEN RETURN return_value; ELSE RETURN NULL; END IF; END; 6.1.4.2 The DBMS_OUTPUT.GET_LINES procedureThe GET_LINES procedure retrieves multiple lines from the buffer with one call. It reads the buffer into a PL/SQL string table. Here's the specification for the procedure: PROCEDURE The parameters for this procedure are summarized in the following table.
The lines parameter is a PL/SQL table TYPE declared in the specification of the package. It is described at the beginning of this chapter. The values retrieved by GET_LINES are placed in the first numlines rows in the table, starting from row one. As indicated in the PL/SQL table structure, each line (row in the table) may contain up to 255 bytes. Notice that numlines is an IN OUT parameter. The IN aspect of the parameter specifies the number of lines to retrieve. Once GET_LINES is done retrieving data, however, it sets numlines to the number of lines actually placed in the table. If you ask for ten rows and there are only six in the buffer, then you need to know that only the first six rows of the table are defined. Notice also that even though the PUT and PUT_LINE procedures allow you to place information into the buffer in their native representations (dates as dates, numbers and numbers, and so forth), GET_LINES always retrieves the information into a character string. The information in each line returned by GET_LINES is everything in the buffer up to the next newline character. This information might be the data from a single PUT_LINE or from multiple calls to PUT. While GET_LINES is provided with the DBMS_OUTPUT package, it is not needed to retrieve information from the DBMS_OUTPUT buffer -- at least when used inside SQL*Plus. In this interactive query tool, you simply execute calls to PUT_LINE, and when the PL/SQL block terminates, SQL*Plus will automatically dump the buffer to the screen. 6.1.4.2.1 ExampleThe following script demonstrates both the kind of code you would write when using the GET_LINES procedure, and also the way in which the PL/SQL table is filled: /* Filename on companion disk: getlines.tst */* DECLARE output_table DBMS_OUTPUT.CHARARR; /* output_buf_tab */ a_line VARCHAR2(10) := RPAD('*',10,'*'); status INTEGER; max_lines CONSTANT NUMBER := 15; BEGIN output_table (0) := 'ABC'; output_table (12) := 'DEF'; /* Output 10 lines */ FOR linenum IN 1..10 LOOP DBMS_OUTPUT.PUT_LINE (a_line || TO_CHAR (linenum); END LOOP; /* retrieve 15 lines, status will receive the line count */ status := max_lines; DBMS_OUTPUT.GET_LINES ( output_table, status); DBMS_OUTPUT.PUT_LINE ('lines retrieved= ' || status)); FOR linenum in 0..max_lines LOOP BEGIN DBMS_OUTPUT.PUT_LINE (linenum || ':' || NVL (output_table(linenum),'<null>') ); EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE (linenum || ':' || sqlerrm ); END; END LOOP; EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE ('Exception, status=' || status); DBMS_OUTPUT.PUT_LINE (SQLERRM ); END; / Here is the output from the execution of this script: lines retrieved= 10 0:ORA-01403: no data found 1:**********1 2:**********2 3:**********3 4:**********4 5:**********5 6:**********6 7:**********7 8:**********8 9:**********9 10:**********10 11:<null> 12:ORA-01403: no data found 13:ORA-01403: no data found 14:ORA-01403: no data found 15:ORA-01403: no data found You can therefore deduce the following rules:
6.1.5 Tips on Using DBMS_OUTPUTAs noted at the beginning of the chapter, DBMS_OUTPUT comes with several handicaps. The best way to overcome these handicaps is to create your own layer of code over the built-in package. This technique is explored in the Section 6.1.6 " section. Regardless of the use of an encapsulation package, you should keep the following complications in mind as you work with DBMS_OUTPUT:
If you get this error and simply continue with your testing, you may be surprised to find that you are not getting any output. If you remember that DBMS_OUTPUT relies on package variables for its settings, this makes perfect sense. So when you get the preceding error, you should immediately "re-enable" DBMS_OUTPUT with a command such as the following: SQL> set serveroutput on size 1000000 format wrapped I usually just re-execute my login.sql script, since I may be initializing several different packages: SQL> @login.sql When will you get this error? I have found that it occurs when I have multiple sessions connected to Oracle. Suppose that I am testing program A in session USER1. I run it and find a bug. I fix the bug and recompile program A in session USER2 (the owner of the code). When I try to execute program A from session USER1 again, it raises the ORA-04068 error. If you do encounter this error, don't panic. Just reset your package variables and run the program again. It will now work fine; the error is simply the result of a quirk in Oracle's automatic recompilation feature. 6.1.6 DBMS_OUTPUT ExamplesThis section contains several longer examples of DBMS_OUTPUT operations. 6.1.6.1 Encapsulating DBMS_OUTPUTSure, it was nice of Oracle Corporation to give us the DBMS_OUTPUT package. Without it, as users of PL/SQL 1.0 found, we are running blind when we execute our code. As is the case with many of the developer-oriented utilities from Oracle, however, the DBMS_OUTPUT package is not a polished and well-planned tool. It offers nothing more than the most basic functionality, and even then it is crippled in some important ways. When I started to use it in real life (or whatever you might call the rarified atmosphere of authoring a book on software development), I found DBMS_OUTPUT.PUT_LINE to be cumbersome and limiting in ways. I hated having to type "DBMS_OUTPUT.PUT_LINE" whenever I simply wanted to display some information. That's a mouthful and a keyboardful. I felt insulted that they hadn't even taken the time to overload for Booleans, requiring me to write silly IF logic just to see the value of a Boolean variable or function. I also found myself growing incensed that DBMS_OUTPUT would actually raise a VALUE_ERROR exception if I tried to pass it a string with more than 255 characters. I had enough errors in my code without having to worry about DBMS_OUTPUT adding to my troubles. I decided that all this anger and frustration was not good for me. I needed to move past this nonconstructive lashing out at Oracle. I needed, in short, to fix my problem. So I did -- with a package of my own. I am not going to provide a comprehensive explanation of my replacement package, but you can read about it (there are actually two of them) in my other books as follows:
The following section shows you the basic elements involved in constructing an encapsulation around DBMS_OUTPUT.PUT_LINE, which compensates for many of its problems. You can pursue building one of these for yourself, but I would strongly suggest that you check out the PL/Vision p package. That will leave you more time to build your own application-specific code. 6.1.6.2 Package specification for a DBMS_OUTPUT encapsulatorThe absolute minimum you need for such an encapsulator package is an overloading of the "print" procedure for dates, strings, and numbers. Let's at least add Booleans to the mix in this prototype: /* Filename on companion disk: prt.spp */* CREATE OR REPLACE PACKAGE prt IS c_prefix CONSTANT CHAR(1) := '*'; c_linelen CONSTANT INTEGER := 80; PROCEDURE ln (val IN VARCHAR2); PROCEDURE ln (val IN DATE); PROCEDURE ln (val IN NUMBER); PROCEDURE ln (val IN BOOLEAN); END; / The prefix constant is concatenated to the beginning of any string to be displayed to avoid the problem of truncated spaces and ignored lines in SQL*Plus. The line length constant is used when the string is longer than 255 bytes. Finally, each of the prt.ln procedures prints a different type of data. A complete implementation of this package would allow you to change the line length and the prefix, specify a date format for conversion, and so on. Again, check out the p package of PL/Vision for such a package. Here is the body of the prt package: /* Filename on companion disk: prt.spp */* CREATE OR REPLACE PACKAGE BODY prt IS PROCEDURE ln (val IN VARCHAR2) IS BEGIN IF LENGTH (val) > 255 THEN PLVprs.display_wrap (val, c_linelen); ELSE DBMS_OUTPUT.PUT_LINE (c_prefix || val); END IF; EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.ENABLE (1000000); DBMS_OUTPUT.PUT_LINE (c_prefix || val); END; PROCEDURE ln (val IN DATE) IS BEGIN ln (TO_CHAR (val)); END; PROCEDURE ln (val IN NUMBER) IS BEGIN ln (TO_CHAR (val)); END; PROCEDURE ln (val IN BOOLEAN) IS BEGIN IF val THEN ln ('TRUE'); ELSIF NOT val THEN ln ('FALSE'); ELSE ln ('NULL BOOLEAN'); END IF; END; END; / Here are a few things to notice about the package implementation:
The prt package should give you a solid idea about the way to encapsulate a built-in package inside a package of your own construction. Copyright (c) 2000 O'Reilly & Associates. All rights reserved. | ||||||||||||||||||||||||||||||||||||
|