0% found this document useful (0 votes)
52 views16 pages

Chapt 14

This document discusses using SQL*Plus to create reports from Oracle databases. It describes how to format columns, add titles and footers, sort and group data, and write query results to files using SQL*Plus commands like COLUMN, TTITLE, BTITLE, SPOOL, and ORDER BY. The document provides examples of these commands and their proper syntax.

Uploaded by

Arsalan Ahmed
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views16 pages

Chapt 14

This document discusses using SQL*Plus to create reports from Oracle databases. It describes how to format columns, add titles and footers, sort and group data, and write query results to files using SQL*Plus commands like COLUMN, TTITLE, BTITLE, SPOOL, and ORDER BY. The document provides examples of these commands and their proper syntax.

Uploaded by

Arsalan Ahmed
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

SQL*Plus for Reports

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

Formatting reports Grouping and summarizing

SQL*Plus: A Programming Tool


What is the difference between SQL and SQL*Plus? SQL is the standard database query language all relational databases use to manipulate data. SQL*Plus is a programming environment in Oracle8 in which you can write and execute SQL. SQL language consists of two kinds of commands: DDL and DML. DDL (Data Definition Language) commands define database Objects. CREATE TABLE is a DDL command. DML (Data Manipulation Language) commands work with the data in Objects. INSERT and UPDATE commands are DML commands. SQL*Plus consists of an environment command set for the following tasks: 3 Edit, save, retrieve, and run files of SQL commands 3 Perform report-generating tasks, such as: Summarizing Calculating Using titles, headers, and footers Using Column titles Using page breaks Printing reports or saving results to files 3 Work directly with the Oracle8 procedural programming language, PL/SQL, without compiling programs

278

Chapter 14 3 SQL*Plus for Reports

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

Basic Report Commands


When writing a report with SQL*Plus, start by creating the query. (This chapter does not cover how to write the basic query. See Chapter 9 for information on writing basic queries.) Once you complete a basic query, you can add query and report features such as Column headings, titles, and so forth using SQL*Plus environment commands. This section discusses how to: 3 Modify the format and heading for a Column

Chapter 14 3 Basic Report Commands

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

The resulting Column heading follows:


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.

Table 14-1 Formats in the SQL*Plus COLUMN Command


Datatype Number Number Number Character Character Sample Format Patterns 999,999.00 000,000.00 $9999.99 A10 A20 Sample Results 4,550.00 004,550.00 $4550.00 Supercalif Supercalifragilistic

280

Chapter 14 3 SQL*Plus for Reports

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

The resulting report appears:


SQL> SELECT ANIMAL_NAME, MARKINGS_DESCRIPTION FROM AQUATIC_ANIMAL; ANIMAL_NAME MARKINGS_D ----------------------------------------Flipper Gray with Pink tongue Skipper Small scar on right fin

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.

Table 14-2 Date Conversion in the TO_CHAR(DATE) Function


Abbreviation Meaning Day (01 through 31) Day of the week with initial letter capitalized (such as: Saturday) Month (01 through 12) Month spelled out and initial letter capitalized First three letters of month in capital letters

DD Day MM Month MON

Chapter 14 3 Basic Report Commands

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)

YY YYYY RR RRRR MI HH HH24 SS

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 and BTITLE


See Reference Section

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

Chapter 14 3 SQL*Plus for Reports

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.

ORDER BY for sorting results


Sorting query results is easy. Use the ORDER BY clause, which comes at the end of your query. The general format follows:
SELECT ... FROM ... WHERE ... ORDER BY columnname1 [ASC | DESC ] , columnname2 [ASC | DESC ] ...

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.

Chapter 14 3 Group Functions

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

The results follow:


TANK_NO BIRTH_DAT ANIMAL_NAME ------------------------------1 01-FEB-68 Flipper 1 01-JAN-78 Skipper 1 11-MAR-90 Bopper 2 06-JUN-96 Batty 2 06-JUN-96 Shorty 2 06-JUN-96 Squacky 2 14-MAY-97 Paintuin 3 05-JAN-90 Nosey 3 01-OCT-94 Rascal 9 Rows selected. SQL>

Sorting the query results is very important when using the grouping and breaking functions shown in the next sections.

Group functions (SUM, AVG, and so forth)


SQL provides you with group functions to summarize your data. The basic syntax follows:
SELECT function(column1)...

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

The results of the query follow:


SUM(TOTAL_CREDIT) ----------------98095.97

284

Chapter 14 3 SQL*Plus for Reports

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.)

Table 14-3 Group Functions


Function Description Average value of values in a Column, ignoring null values. Maximum value of values in a Column. Number of rows in which the Column being counted is not null. If all rows are null or do not match the query criteria, COUNT equals zero. Sum of values in a Column. Minimum value of values in a Column. Standard deviation of values in a Column. Sum of values in a Column. Variance of values in a Column.

AVG MAX COUNT SUM MIN STDDEV SUM VARIANCE

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)

Chapter 14 3 Group Functions

285

FROM AQUATIC_ANIMAL A, TANK WHERE TANK.TANK_NO = A.TANK_NO GROUP BY TANK_NAME ORDER BY TANK_NAME

The results follow:


TANK_NAME MIN(BIRTH ------------------------------------------------Dolphin Tank 01-FEB-68 Penguin Pool 06-JUN-96 Sea Lion Den 05-JAN-90

Be sure to include an ORDER BY clause that matches the GROUP BY clause. Otherwise, your results may appear sorted incorrectly.

BREAK and COMPUTE


See Reference Section

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

Chapter 14 3 SQL*Plus for Reports

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

The results follow:


C_NAME TANK_NO ID_NO ANIMAL_NAME ----------------------------------------------Harold Kamalii 1 100 Flipper 105 Skipper 112 Bopper ********* ----count 3 *************** count Jan Neeleson 3 ********* count *************** count Joseph Kalama 2 ----3 199 Nosey 202 Rascal 240 Snoops ----3 ----3 145 Squacky

C_NAME TANK_NO ID_NO ANIMAL_NAME ----------------------------------------------Joseph Kalama 2 151 Batty 166 Shorty 175 Paintuin ********* ----count 4 *************** count ----4 ----10

count 10 rows selected.

The next section shows more additions you can make to your reports.

Chapter 14 3 Variables and Parameters

287

Variables and Parameters


Variables help you write flexible queries. This section shows how to define variables and pass parameters to SQL*Plus scripts.

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

Chapter 14 3 SQL*Plus for Reports

SQL*Plus prompts once and then replaces both variables with the assigned value.

Executing reports with @


See Reference Section

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.

Figure 14-1: SQL*Plus executes a file and prompts for a variable.

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%

Chapter 14 3 Variables and Parameters

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.

Figure 14-2: SQL*Plus executes a file and uses a parameter.

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

Chapter 14 3 SQL*Plus for Reports

Report Formatting
This section describes useful SQL*Plus commands for formatting reports.

PAGESIZE and LINESIZE


See Reference Section

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 with SYSDATE


See Reference Section

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 /

Chapter 14 3 Report Formatting

291

02/12/98 09:55 ID_NO ANIMAL_NAME --------------------100 Flipper 105 Skipper 112 Bopper

The Animal Report

The first line of the SQL*Plus script follows:


TTITLE LEFT TODAYS_DATE CENTER The Animal Report SKIP 2

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.

RECSEP and RECSEPCHAR


See Reference Section

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

Chapter 14 3 SQL*Plus for Reports

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.

You might also like