Chapt 14
Chapt 14
racle8 still has the grand old standby, SQL*Plus, for creating reports quickly. The SQL*Plus environment enables you to assign titles, headers, footers, and breaks, and even prompt for variables. This chapter highlights the major steps to completing reports quickly.
14
C H A P T E R
In This Chapter
278
3 Send and receive variable information to and from an end User 3 Display the Column definitions for any Table, View, or Synonym in the database 3 Copy data between two databases Examples of SQL*Plus commands follow: 3 COLUMN 3 TTITLE 3 BREAK 3 SET 3 EDIT
Tip
You cannot use SQL*Plus environment commands outside of SQL*Plus. For example, you cannot change Column headings in SQL Worksheet. You can use SQL*Plus in command line mode and window mode. The Enterprise Manager supports SQL*Plus in a window. You can use your mouse to cut, paste, and so forth within the window. The next section describes some of the most useful commands for creating reports in SQL*Plus.
On the CD-ROM
You can run all the SQL examples in this chapter in SQL*Plus if you install the sample Schema from the CD-ROM. Appendix A contains instructions on how to install the sample Schema into an Oracle8 database. Chapter 9 shows how to start SQL*Plus using Enterprise Manager. Chapter 9 also contains a section called How to use SQL*Plus for queries that describes the editing capabilities available in SQL*Plus. Review the section before continuing with this chapter if you plan to follow along and type in the examples.
CrossReference
279
3 Add a title to the report 3 Write the formatted query results (report) to a file
COLUMN
The COLUMN command enables you to change the heading of a Column and several characteristics derived from the Column by default.
COLUMN columnname HEADING headingtext FORMAT formattext WORD_WRAPPED
Replace columnname with the actual Column name and replace headingtext with your desired Column heading. If the name includes spaces, enclose it in double quotes (). To make a heading that contains two lines, use the vertical bar (|) as a divider. For example, the following Column command results in a heading with Birth and Date aligned vertically for the Column named BIRTH_DATE.
COLUMN BIRTH_DATE HEADING Birth|Date
Replace formattext with the your desired format. The format parameter defines the report Column width and the appearance of numbers.
See Reference Section
FORMAT NUMBER
Table 14-1 lists examples of formatting commands. You place the sample format pattern in the COLUMN command; the sample results column displays the formatting results on sample data.
280
For text Columns, use A(n), in which n is the number of characters. Wrap text data within the Column by adding the WORD_WRAP parameter to the COLUMN command. For example, the following COLUMN command allows the MARKINGS_DESCRIPTION Column to wrap data:
COLUMN MARKINGS_DESCRIPTION FORMAT A10 WORD_WRAP
WORD_WRAPPED is optional. If used, long text Columns wrap to the width specified in the format and break at a new word, rather than at a certain number of characters.
For number Columns, use a pattern of nines and zeros. The format 990.00, for example, ably lines up dollar amounts.
See Reference Section
FORMAT DATE
For date Columns, you cannot define the appearance of the date. You can define the width of the report Column to match the format of the date, however. Define the data format in your SELECT clause by using the TO_CHAR function. Table 14-2 shows the common formatting characters for dates (see the Command Reference section for a complete list). The RR and RRRR functions, new format options for Oracle8, defaults the century with the current century instead of 1900.
281
Abbreviation
Meaning Year (00 through 99) Year (including 1900 century, such as 1999 or 1901) Year (00 through 99) Year (including current century, such as 1999 or 2001) Minute (00 through 59) Hour (01 through 12) Hour (01 through 24) Second (00 through 59)
Watch out for the small but critical difference between MM (the month abbreviation) and MI (the minute abbreviation). The COLUMN command stays in effect as long as you reside in SQL*Plus.
TTITLE
A title makes a query look like a regular report. The TTITLE command has two versions. The first version enables you to put a simple line of text at the top of your report:
TTITLE justify "title text"
Replace justify with CENTER, RIGHT, or LEFT to justify the text of the title. Replace title text with your desired title text. Enclose it in double quotes. The second version provides more flexibility. You can format pieces of the title on the left, center, and right sides of one title, and also include your querys Columns in the title. This version of title is most often used with a report that is sorted and grouped by categories.
See Reference Section
BTITLE
The BTITLE command places a footer in your report page. BTITLE uses the same syntax as TTITLE.
282
SPOOL
See Reference Section
SPOOL SPOOL is a very useful command that writes the results of your query to a file. Later,
you can retrieve the file and print it. Hard copy is so much more convincing than pixels on a screen.
SPOOL Filename[.suffix]
Replace Filename with your desired file name. If you do not specify a suffix in your file name, SQL*Plus automatically adds a suffix to the file name (usually .lis or .lst). When spooling starts, SQL*Plus sends everything to this file. To stop the spooling, issue this command:
SPOOL OFF
Spooling also ends as soon as you exit SQL*Plus. Use the SPOOL command to write reports to a file that you can later print.
Group Functions
See Reference Section
SELECT
Use the group functions of SQL in combination with the SQL*Plus commands for creating report breaks.
Replace columnname1 and columnname2 with the names of the Columns you want to use when sorting. List the Columns according to the order in which you want them to be sorted. To sort in descending order, add the DESC parameter next to each Column you want to sort in descending order. Ascending order is the default.
283
The ORDER BY clause also enables you to list the sorting Columns by their positions in the SELECT clause, rather than by the Column names. For example, the following query sorts by TANK_NO, BIRTH_DATE, and ANIMAL_NAME:
SELECT TANK_NO, BIRTH_DATE, ANIMAL_NAME FROM AQUATIC_ANIMAL WHERE DEATH_DATE IS NULL ORDER BY 1, 2, 3
Sorting the query results is very important when using the grouping and breaking functions shown in the next sections.
For example, you may want to see the sum of the TOTAL_CREDIT Column in the PARK_REVENUE Table. The following SQL uses the SUM function:
SELECT SUM(TOTAL_CREDIT) FROM PARK_REVENUE
284
Oracle8 has many group functions you can use in queries. Table 14-3 shows a list of these functions. All these functions perform grouping on the rows selected in the query. If your WHERE clause returns 15 rows from a Table of 200 rows, the group function is performed on those 15 rows. (See the Command Reference section for a complete description of each of these functions.)
GROUP BY
The group functions enable you to create summary reports. What if you want a report that contains several groups of results? Add the GROUP BY clause to your query. The GROUP BY clause appears after the WHERE clause and before the ORDER BY clause. A simplified version of the syntax follows:
SELECT column1, column2, group_function (column3) FROM ... WHERE ... GROUP BY column1, column2 ORDER BY ...
Suppose a query contains Columns (or expressions) outside of a group function and also contains Columns in one or more group functions. You must list all the nongrouped Columns in the GROUP BY clause. For example, a query to show the birth date of the oldest animal in each tank in the Sea Park follows:
SELECT TANK_NAME, MIN(BIRTH_DATE)
285
FROM AQUATIC_ANIMAL A, TANK WHERE TANK.TANK_NO = A.TANK_NO GROUP BY TANK_NAME ORDER BY TANK_NAME
Be sure to include an ORDER BY clause that matches the GROUP BY clause. Otherwise, your results may appear sorted incorrectly.
BREAK COMPUTE
SQL*Plus also provides a way to summarize and group sets of rows in a report. Using the BREAK and COMPUTE commands, you can make a report with details, breaks, and summaries. The general syntax of the BREAK command follows:
BRE[AK] [ON Report_element [action] ]
You specify the timing of a break in your report. When there is a new value in the Column named in the BREAK command, SQL*Plus executes your specifications (such as skip a line or skip a page). In addition, SQL*Plus prints summary information about the rows in the group. Use the COMPUTE command for printing summary information on breaks. The general syntax of the COMPUTE command follows:
COMP[UTE] [function [LABEL] text OF expression|column|alias ON expression | column | alias | report | row]
For example, using the SEAPARK Tables, you create a report showing the number of animals each caretaker handles, listed by the caretaker name and then by the tank number. You report a count of animals for each tank, each caretaker, and the entire report. The SQL*Plus script follows:
COLUMN C_NAME FORMAT A15 BREAK ON REPORT ON C_NAME SKIP 2 ON TANK_NO SKIP 1
286
COMPUTE COUNT OF ID_NO ON REPORT COMPUTE COUNT OF ID_NO ON C_NAME COMPUTE COUNT OF ID_NO ON TANK_NO SELECT T.CHIEF_CARETAKER_NAME C_NAME, T.TANK_NO, A.ID_NO, A.ANIMAL_NAME FROM TANK T, AQUATIC_ANIMAL A WHERE T.TANK_NO = A.TANK_NO ORDER BY T.CHIEF_CARETAKER_NAME, T.TANK_NO, A.ID_NO
C_NAME TANK_NO ID_NO ANIMAL_NAME ----------------------------------------------Joseph Kalama 2 151 Batty 166 Shorty 175 Paintuin ********* ----count 4 *************** count ----4 ----10
The next section shows more additions you can make to your reports.
287
DEFINE
See Reference Section
DEFINE
Define a variable so you can run the same SQL query for varying results. You can substitute a variable anywhere in your SQL query that you would place a Column or expression. Use a variable in the WHERE clause to return different sets of rows from your query. Variables can be defined using the DEFINE command:
DE[FINE] [variable]|[variable = text]
In addition, variables can be defined by simply referencing the variable (preceded by an ampersand (&)) in the SQL query itself. SQL*Plus prompts you for input unless you have assigned a value to the variable. Heres an example:
SELECT ID_NO, ANIMAL_NAME FROM AQUATIC_ANIMAL WHERE ANIMAL_NAME LIKE &STARTS_WITH%
When you execute the query, Oracle8 asks you to define the STARTS_WITH variable. The User types a letter B in the following example and then presses Enter. Next, Oracle8 shows how it uses the variable and displays the results of the query as follows:
Enter value for starts_with: B old 3: WHERE ANIMAL_NAME LIKE &STARTS_WITH% new 3: WHERE ANIMAL_NAME LIKE B% ID_NO ANIMAL_NAME --------------------112 Bopper 151 Batty
Tip
When you must reference a variable more than once in a query, use double ampersands (&&) to tell SQL*Plus to prompt for the variable only once and then reuse the results. For example, the following query causes a single prompt for the STARTS_WITH variable:
SELECT ANIMAL_NAME, Begins with a ||&&STARTS_WITH FROM AQUATIC_ANIMAL WHERE ANIMAL_NAME LIKE &&STARTS_WITH%
288
SQL*Plus prompts once and then replaces both variables with the assigned value.
You can run a query from the command line using the @filename parameter. In the preceding example, assume the query has been saved in a file named find.sql. The end of the query contains an execute command (semi-colon (;) or slash(/)). The operating system command to run the file follows:
sqlplus SEAPARK/SEAPARK @find
Oracle8 starts SQL*Plus and runs the file. Then SQL*Plus prompts you for a value and runs the query. Figure 14-1 shows the resulting prompts and query findings.
You can also call SQL*Plus, run a query (or other SQL command) from the operating system command line, and pass the variable value using a parameter. To facilitate this sequence, SQL*Plus provides a default set of parameters numbered by their order in the command line. Using the same example query, modify the query so the variable name is &1:
SELECT ID_NO, ANIMAL_NAME FROM AQUATIC_ANIMAL WHERE ANIMAL_NAME LIKE &1%
289
The operating system command to run the file, sending the letter B as parameter 1, follows:
sqlplus SEAPARK/SEAPARK @find B
Oracle8 starts SQL*Plus and runs the file. SQL*Plus grabs the letter B and replaces the &1 variable in the query. Figure 14-2 shows the resulting prompts and query findings.
SET
See Reference Section
SET
When generating reports, you often do not want extraneous information on the report. Suppress this information from SQL*Plus by using these commands: 3 SET FEEDBACK OFF. Tells SQL*Plus to suppress the display of row counts at the end of queries. 3 SET VERIFY OFF. Tells SQL*Plus to suppress the display of variable substitution. 3 SET TERMOUT OFF. Tells SQL*Plus to suppress all display to the terminal. This command is useful for spooling reports to a file. 3 SET ECHO OFF. Tells SQL*Plus to suppress the repetition of the SQL command prior to execution. Use SET ECHO ON to display the commands before execution. Refer to the Command Reference section for more information about the SET command.
290
Report Formatting
This section describes useful SQL*Plus commands for formatting reports.
SET
The following SQL code changes the number of lines per page to 60:
SET PAGESIZE 60
The following command changes the number of characters per line to 132 (a good number for printing landscape-style reports):
SET LINESIZE 132
Experiment with these settings by spooling and printing test reports. Your printer may need a slightly different setting.
TTITLE PSEUDOCOLUMN
Oracle8 always stores the current date and time in the pseudocolumn SYSDATE. To place the current date into your report title, you must do three things: 1. Add the pseudocolumn SYSDATE to your query and give it an alias. 2. Add a COLUMN command for the alias. 3. Add a TTITLE command containing the alias. An example of the finished code and the resulting report follows:
TTITLE LEFT TODAYS_DATE CENTER The Animal Report SKIP 2 COLUMN TODAYS_DATE NEW_VALUE TODAYS_DATE NOPRINT SELECT TO_CHAR (SYSDATE, MM/DD/YY HH:MI) TODAYS_DATE, ID_NO, ANIMAL_NAME FROM AQUATIC_ANIMAL WHERE TANK_NO = 1 /
291
02/12/98 09:55 ID_NO ANIMAL_NAME --------------------100 Flipper 105 Skipper 112 Bopper
This example tells Oracle8 to place TODAYS_DATE on the left side of the top line. The TTITLE command states that the words The Animal Report are centered on the page and on the top line of the report. The SKIP 2 portion of the command tells Oracle8 to go down two lines before displaying the rest of the report. The second line of the SQL*Plus script follows:
COLUMN TODAYS_DATE NEW_VALUE TODAYS_DATE NOPRINT
The NEW_VALUE command tells Oracle8 to update the Column before printing it in your report. Otherwise, Oracle8 does not know the Column is a Column and treats it as a literal (a word or phrase used exactly as typed). Without NEW_VALUE, Oracle8 prints the word TODAYS_DATE rather than the value of the current date. The NOPRINT command tells Oracle8 not to print or display the TODAYS_DATE Column as part of the query results.
SET RECSEP means record separator. The RECSEP setting tells SQL*Plus what to do between two rows of your report. The RECSEPCHAR setting tells SQL*Plus what repeating character(s) to print on the line (if any) between two rows of your report.
Oracle8 has a default setting of WRAP for the RECSEP setting and a blank space for the RECSEPCHAR setting. These defaults means SQL*Plus adds a blank line between two rows in the query results, but only when the top row contains at least one Column whose data has wrapped to a second line. Other setting possibilities include: 3 SET RECSEP OFF. Never place a line between two rows in your report. 3 SET RECSEP EACH. Always place a line between rows in your report.
292
For example, the following SQL*Plus commands insert a line between each row with the specified words on the line:
SET RECSEP EACH SET RECSEPCHAR * SELECT ID_NO, TANK_NO FROM AQUATIC_ANIMAL / ID_NO TANK_NO --------------100 1 ******************************* 105 1 ******************************* 112 1 ******************************* 145 2 ******************************* 151 2 ******************************* 166 2 ******************************* 175 2 ******************************* 199 3 ******************************* 202 3 ******************************* 240 3 ******************************* 10 Rows selected.
After completing this chapter, you now have a good set of report-writing tools. Mix and match the SQL*Plus commands to write useful scripts.
Summary
SQL*Plus is a programming environment that enables you to write and execute SQL, PL/SQL, and SQL*Plus commands. This chapter focuses on how to write and format reports using SQL and SQL*Plus. The group functions are SQL functions that create summary reports. Two alternatives to the group functions, the BREAK and COMPUTE commands, format reports in an outline format. You can set page breaks, headings, Column headings, variables, parameters, and other formatting details by using the SQL*Plus commands described here. This chapter concludes the nuts and bolts part of the book. The next part covers the more advanced subjects of tuning and backups.