Introduction to Oracle: SQL and PL/SQL Using Procedure Builder CĆ2... Introduction to Oracle: SQL and PL/SQL Using Procedure Builder CĆ4The SQL*Plus Environment... Introduction to Oracle
Trang 1Using SQL*Plus to Create Reports and Manage PL/SQL
Code
C
Trang 2Introduction to Oracle: SQL and PL/SQL Using Procedure Builder CĆ2
Trang 3This lesson covers formatting query output to produce simple reports,
controlling the SQL*Plus environment, and manipulating PL/SQL code using SQL*Plus.
At the end of this lesson, you should be able to
D Differentiate between SQL and SQL*Plus commands
D Identify SET commands used to control the SQL*Plus environment
D Customize reports using SQL*Plus formatting commands
D Create and modify anonymous blocks and program units with SQL*Plus and theonline editor
D Execute SQL*Plus commands, anonymous blocks, program units, and SQLstatements
D Compile procedures and functions
D Embed messages to assist with debugging code
Trang 4Introduction to Oracle: SQL and PL/SQL Using Procedure Builder CĆ4
The SQL*Plus Environment
Trang 5SQL*Plus is an environment in which you can
D Execute SQL statements to retrieve, modify, add, and remove data from databasetables
D Format, perform calculations on, store, and print query results in the form ofreports
D Issue SQL statements to create, alter, and remove database tables
D Create anonymous blocks, subprograms, database triggers using procedurallanguage extension, PL/SQL
SQL*Plus has a variety of commands you need to use to execute subprograms, passvalues in and out of PL/SQL blocks, and debug your code
SQL*Plus commands may be divided into the following main categories
Environment Affects the general behavior of SQL statements for the
session
Format Formats query results
File manipulation Saves, loads, and runs script files
Execution Sends SQL or PL/SQL commands from SQL buffer to
Oracle7 Server
Edit Modifies SQL commands in the buffer
Interaction Allows users to create and pass variables to SQL
statements, print variable values, and print messages tothe screen
Miscellaneous Various commands to connect to the database,
manipulate the SQL*Plus environment, and displaycolumn definitions
Trang 6Introduction to Oracle: SQL and PL/SQL Using Procedure Builder CĆ6
Entering Commands in SQL*Plus
Trang 7Entering Commands in SQL*Plus
Once you log in to SQL*Plus, you see the command prompt Issue all your
commands at this prompt Three types of commands can be entered at this prompt
D SQL commands to manipulate data and structures in the database
D SQL*Plus command to format query results, set the environment, edit commands,and create variables
D PL/SQL blocks to work with information in the database in a procedural method
To execute commands, type them at the command prompt SQL*Plus commands donot need to be terminated with a semicolon (;) SQL statements and PL/SQL blocks
do need to be terminated with a semicolon to send the statement to the Oracle7Server
Trang 8Introduction to Oracle: SQL and PL/SQL Using Procedure Builder CĆ8
Trang 9Comparison of SQL and SQL*Plus Commands
This table compares SQL and SQL*Plus commands They are distinctly differentprograms, but are used together to perform some tasks, such as to format data in areport and to control command files
Is a language for communicating with
the Oracle Server to access data
Recognizes SQL commands, and sendsthem to the server
Is based on American National
Standards Institute (ANSI) standard
Does not have a continuation character Has a dash “-” as a continuation
character if the command is longer thanone line
Cannot be abbreviated Can be abbreviated
Uses a termination character to execute
commands required
Does not require termination characters;commands are immediately executed.Uses functions to perform some
formatting
Uses commands to format data
Trang 10Introduction to Oracle: SQL and PL/SQL Using Procedure Builder CĆ10
Trang 11SQL*Plus SET Commands
Control the environment in which SQL*Plus is currently operating by using the SETcommands
Syntax
SET system_variable value
where: system_variable is a variable that controls one aspect of the
session environment
value is a value for the system variable
Default Settings Using the login.sql File
The login.sql file contains standard SET and other SQL*Plus commands that you
may require for every session The file is read and commands are implemented at log
in When you log out of your session, all customized setting are lost
Changing the Default Settings
The settings implemented by login.sql can be changed during the current session.
Changes made are only current for that session As soon as you log out, those settingsare lost
Add permanent changes to settings to the login.sql file.
For more information, see
SQL*Plus User’s Guide and Reference, Release 3.3, “Command Reference.”
Trang 12Introduction to Oracle: SQL and PL/SQL Using Procedure Builder CĆ12
Trang 13SQL* Plus SET Commands
Some Useful SET Commands
SET Variable and Values Description
ARRAY[SIZE] {20|n} Sets the database data fetch size
COLSEP { |text} Sets text to be printed between columns Default
is single space
FEED[BACK] {6|n|OFF|ON} Displays the number of records returned by a
query when the query selects at least n records.
HEA[DING]{OFF|ON} Determine whether column headings are
PAGES[IZE] {24|n} Specifies the number of lines per page of output
PAU[SE] {OFF|ON|text} Allows you to control scrolling of your terminal
You must press [Return] after seeing each pause.TERM[OUT] {OFF|ON} Determines whether output is displayed to the
screen
Guidelines
D Use the SHOW command to view current values for any of these settings, forexample SHOW PAUSE To see all SET variable values, use the SHOW ALLcommand
D The value n represents a numeric value.
D Underlined values shown above indicate default values If you enter no value withthe variable, then SQL*Plus assumes the default value
Trang 14Introduction to Oracle: SQL and PL/SQL Using Procedure Builder CĆ14
Trang 15Creating a Report
Script File
You can create a script file (or command file) that includes both a SQL SELECT
statement and SQL*Plus commands used to format and reset command values Scriptfiles are useful for saving both a SQL statement and any SQL*Plus settings specific
to that statement
Additionally, you can create a file to hold all your default SQL*Plus commands,which may be executed at any time to reset your settings This file can be executedfrom within your command file
SQL*Plus Format Commands
You can control the report features described above by using the following
commands:
COL[UMN] [column option] Controls column formats
TTI[TLE] [text|OFF|ON] Specifies a header to appear at the top of each
page of the report
BTI[TLE] [text|OFF|ON] Specifies a footer to appear at the bottom of
each page of the report
Guidelines
D All format commands remain in effect until the end of the SQL*Plus session, oruntil the format setting is overwritten or cleared
D Remember to reset your SQL*Plus settings to default values after every report
D There is no command for setting a SQL*Plus variable to its default value; youmust know the specific value or log out and log in again
D If you give an alias to your column, you must reference the alias name, not thecolumn name
Trang 16Introduction to Oracle: SQL and PL/SQL Using Procedure Builder CĆ16
Trang 17Creating a Report continued
TTITLE and BTITLE Commands
Use the TTITLE command to format page headers and the BTITLE command forfooters Footers appear at the end of the page according to the PAGESIZE value
Syntax
The syntax for BTITLE and TTITLE is identical Only the TTITLE syntax is shown.You can use the vertical bar (|) to split the text of the title across several lines
TTI[TLE] [printspec [text|variable]][OFF|ON]
where: printspec is an option to specify the type of settings
text represents the title text Enter single quotes if
the text is more than one word
variable is a system-maintained value
Example
Set the report header to display Salary centered on one line, and Report centeredbelow it
SQL> TTITLE ’Salary|Report’
Display or Clear Settings
To show or clear the current header and footer command settings, use the followingcommands
TTITLE Displays the current setting for the header
Trang 18Introduction to Oracle: SQL and PL/SQL Using Procedure Builder CĆ18
Trang 19Creating a Report continued
Creating the Script File to Run a Report
You can either enter each of the SQL*Plus commands at the SQL prompt or put allthe commands, including the SELECT statement, in a command (or script) file Atypical script consists of at least one SELECT statement and several SQL*Plus
commands
Steps to Create a Script File
1. Create the SQL SELECT statement at the SQL prompt Ensure that the datarequired for the report is accurate before you save the statement to a file andapply formatting commands Ensure that the relevant ORDER BY clause isincluded if you intend to use breaks
2. Save the SELECT statement to a script file
3. Edit the script file to enter the SQL*Plus commands
4. Add the required formatting commands before the SELECT statement Be certainnot to place SQL*Plus commands within the SELECT statement
5. Verify that the SELECT statement is followed by a run character, either a
semicolon (;) or a slash (/)
6. Add the format-clearing SQL*Plus commands after the run character As analternative, you can call a reset file which contains all the format-clearing
commands
7. Save the script file with your changes
8. In SQL*Plus, run the script file by entering START filename or @filename This
command is required to read and execute the script file
Guidelines
D You can include blank lines between SQL*Plus commands in a script
D You can abbreviate SQL*Plus commands
D Include reset commands at the end of the file in order to restore the originalSQL*Plus environment
Trang 20Introduction to Oracle: SQL and PL/SQL Using Procedure Builder CĆ20
12
Trang 21Creating a Report continued
REM ** This report covers all employees who are notREM ** vice presidents or warehouse managers
SET ECHO OFF
COLUMN title HEADING ’Job|Category’ FORMAT A22
COLUMN last_name HEADING ’Employee’ FORMAT A22
COLUMN salary HEADING ’Salary’ FORMAT $99,999.99
REM ** Insert SELECT statement
SELECT title, last_name, salary
WHERE title NOT LIKE ’VP%’
ORDER BY title, last_name, salary
Trang 22Introduction to Oracle: SQL and PL/SQL Using Procedure Builder CĆ22
Declaring and Creating PL/SQL Blocks
Trang 23Declaring and Creating PL/SQL Blocks
You can use two methods to process PL/SQL blocks in SQL*Plus
D Define a block in the SQL buffer, then execute the contents of the buffer
D Define a block as part of a SQL*Plus script file, then start the file
Declaring PL/SQL Blocks in the SQL Buffer
A PL/SQL block is treated as one continuous statement in the buffer, and the
semicolons (;) within the block do not close or execute the contents of the buffer.
SQL*Plus detects the start of a PL/SQL block when you enter either DECLARE orBEGIN at the prompt You can close the buffer without executing the block by
entering a period (.) at the number prompt of the buffer
To run the buffered PL/SQL block, enter the RUN command or a slash (“/”) at theprompt If the block executes successfully, without unhandled exceptions or compileerrors, you will see a message
Creating SQL*Plus Files Containing PL/SQL Blocks
You can include PL/SQL blocks in files of SQL and SQL*Plus commands Create the
file using the operating system editor SQL*Plus commands may not occur inside the
PL/SQL block itself, but you can include them elsewhere in the file
You can reference SQL*Plus substitution variables inside the block, but rememberthat they are substituted with the variable’s contents before the code is parsed orexecuted This means that if you reference a SQL*Plus substitution variable in aPL/SQL loop, then a value is substituted for the variable once, and not for eachiteration of the loop
Trang 24Introduction to Oracle: SQL and PL/SQL Using Procedure Builder CĆ24
SQL*Plus Commands
Trang 25Entering Commands in SQL*Plus
SQL*Plus contains an array of commands to format reports and initiate the users’environment
SQL*Plus Command Description
ACCEPT Reads input from the user and stores the input into a
variable
VARIABLE Declares a bind, or host, variable that can be
referenced in PL/SQL with a preceding colon (:).PRINT Displays the current value of bind variables
EXECUTE Executes a single PL/SQL statement
For more information, see
SQL*Plus User’s Guide and Reference, Release 3.3.
Trang 26Introduction to Oracle: SQL and PL/SQL Using Procedure Builder CĆ26
Trang 27Passing Input and Output Values
A substitution variable, or parameter, preceded by an ampersand (&) is used to represent a value to be passed into a statement A global variable preceded by a colon
(:)is used to pass information out of the PL/SQL block
2. Within the PL/SQL block, embed the SQL*Plus substitution parameter wherever
it is needed as input, referencing it with the ampersand (&) prefix
Syntax
ACCEPT variable PROMPT message
where: variable is the name of the substitution variable to store
the value
message is the message displayed
Trang 28Introduction to Oracle: SQL and PL/SQL Using Procedure Builder CĆ28
Trang 29Passing Input and Output Values continued
Output Values
Output a value from the PL/SQL block into SQL*Plus by using a SQL*Plus globalvariable Follow the steps listed below
1. Outside the PL/SQL block, declare a SQL*Plus global variable with the
SQL*Plus VARIABLE command
2. Within the PL/SQL block, embed the SQL*Plus global variable wherever it isneeded as output, referencing it with the colon (:) prefix
3. Outside the PL/SQL block, print the output value on the screen with the
SQL*Plus PRINT command
Syntax
VARIABLE variable [NUMBER|CHAR|CHAR(n)|VARCHAR2(n)]
PRINT variable
where: variable is the name of the bind variable
n is the maximum length for the datatype
Trang 30Introduction to Oracle: SQL and PL/SQL Using Procedure Builder CĆ30
Trang 31Debugging in SQL*Plus
When you execute your PL/SQL code, one of two types of errors might appear Onetype is a compilation error For anonymous blocks, you will see the errors appear onthe screen For stored subprograms, the compilation errors are stored in the
USER_ERRORS data dictionary table To access those errors, enter either of thefollowing commands at the prompt:
Trang 32Introduction to Oracle: SQL and PL/SQL Using Procedure Builder CĆ32
Trang 33Debugging in SQL*Plus continued
One method for debugging your PL/SQL block using SQL*Plus is to embed globalvariables at specific points with a message Each message can contain informationabout how many times a loop was executed, or which statements were executed Youcan print the results of the global variables using the SQL*Plus PRINT command
Example
Print a message indicating which DML statement was executed
VARIABLE g_debug VARCHAR2(50)
ACCEPT p_num PROMPT ’Enter a number: ’
Trang 34-Introduction to Oracle: SQL and PL/SQL Using Procedure Builder CĆ34
Trang 35Displaying Contents of a Subprogram
You can obtain the text of a stored procedure or a function from USER_SOURCEdata dictionary view
Example
Display contents of the procedure CHANGE_SALARY
SQL> SELECT text
TEXT
––––––––––––––––––––––––––––––––––––––––––––––––––––
(v_emp_id IN NUMBER, v_new_salary IN NUMBER) IS
BEGIN
UPDATE s_emp SET salary = v_new_salary WHERE id = v_emp_id;
COMMIT;
END change_salary;