1.1.1 Frequently Accessed URL.: SQL Plus FAQ
1.1.1 Frequently Accessed URL.: SQL Plus FAQ
SQL*Plus FAQ
An example using an Easy Connection identifier to connect to the HR schema in the MYDB database
running on mymachine is:
sqlplus hr@//mymachine.mydomain:port/MYDB
Net Service Names can be stored in a number of places, including Oracle Names. See the Net Services
Reference Guide for more information.
If you want to use Net Service Names configured in a local Oracle Net tnsnames.ora file, then set the
environment variable TNS_ADMIN to the directory containing the tnsnames.ora file. For example, on
UNIX, if your tnsnames.ora file is in /home/user1 and it defines the Net Service Name MYDB2:
TNS_ADMIN=/home/user1
export TNS_ADMIN
sqlplus hr@MYDB2
This example assumes the ORACLE_HOME environment variable is set, and the
$ORACLE_HOME/network/admin/tnsnames.ora or ORACLE_HOME\network\admin\tnsnames.ora
file defines the Net Service Name MYDB3:
sqlplus hr@MYDB3
The TWO_TASK (on UNIX) or LOCAL (on Windows) environment variable can be set to a
connection identifier. This removes the need to explicitly enter the connection identifier whenever a
connection is made in SQL*Plus or SQL*Plus Instant Client. This UNIX example connects to the
database known as MYDB4:
TNS_ADMIN=/home/user1
export TNS_ADMIN
TWO_TASK=MYDB4
export TWO_TASK
sqlplus hr
Windows 7:
C:\Users\skandan>echo %TNS_ADMIN%
C:\app\oracle\product\11.1.0\db_1\NETWORK\ADMIN
C:\Users\skandan>echo %ORACLE_HOME%
C:\app\oracle\product\11.1.0\db_1
If TNS_ADMIN is not set, then an operating system dependent set of directories is examined to find
tnsnames.ora. This search path includes looking in the directory specified by the ORACLE_HOME
environment variable for network/admin/tnsnames.ora. This is the only reason to set the
ORACLE_HOME environment variable for SQL*Plus Instant Client. If ORACLE_HOME is set when
running Instant Client applications, it must be set to a directory that exists.
To remove the sample tables, perform the same steps but substitute HR_DROP.SQL for
HR_MAIN.SQL.
Example
$ORACLE_HOME/lib
Example
american_america.utf8
Examples:
d:\oracle\10g
/u01/app/oracle/product/v10g
ORA_NLS10 Environment variable to specify the locations of the NLS data and the user
boot file in SQL*Plus 10.2. The default location is
$ORACLE_HOME/nls/data. In a system with both Oracle9i and 10g, or a
system under version upgrade, you should set ORA_NLS10 for Oracle 10g
and set ORA_NLS33 for 9i. The default NLS location in 9i was
Parameter or Variable Description
$ORACLE_HOME/common/nls/admin/data.
PATH Environment variable to specify the path to search for executables, and
DLLs in Windows. Typically includes ORACLE_HOME/bin
ORACLE_HOME\SQLPLUS\MESG
TNS_ADMIN Environment variable to specify the location of the tnsnames.ora file. If not
specified, $ORACLE_HOME/network/admin is used
Example
h:\network
/var/opt/oracle
Example
Parameter or Variable Description
TWO_TASK=MYDB
export TWO_TASK
sqlplus hr
sqlplus hr@MYDB
Note that you need not specify database login credentials in this CONNECT statement. Instead your
system looks for database login credentials in the client wallet.
See Also:
Oracle Database Administrator's Guide for information about configuring your client to use secure
external password store and for information about managing credentials in it.
1.1.4.1 Compatibility
A new command line argument (-c) has been added to allow the SQLPLUSCOMPATIBILITY option
to be specified such that "sqlplus -c 9.2" equates to "SET SQLPLUSCOMPATIBILITY 9.2".
SqExample:
sqlplus hr/hr@(DESCRIPTION= (ADDRESS=(PROTOCOL=tcp)(HOST=siva-pc)(PORT=1521))
(CONNECT_DATA= (SERVICE_NAME=siva-pc))) ( Not tested )
sqlplus hr/hr@siva-pc:1521/orcl
When connecting to SQL*Plus from the command line as a privileged user it is no longer necessary to
use quotes, meaning both of the following are valid:
The location of the comment prevents SQL*Plus from recognizing the command as a command.
SQL*Plus submits the PL/SQL block to the server when it sees the slash "/" at the beginning of the
comment, which it interprets as the "/" statement terminator. Move the comment to avoid this error. For
example:
CREATE OR REPLACE PROCEDURE
2 /* HELLO */
3 HELLO AS
4 BEGIN
5 DBMS_OUTPUT.PUT_LINE('HELLO');
6 END;
7 /
Procedure created.
• Do not put comments after statement terminators (period, semicolon or slash). For example, if
you enter:
SELECT 'Y' FROM DUAL; -- TESTING
SQL*Plus expects no text after a statement terminator and is unable to process the command.
• Do not use ampersand characters '&' in comments in a SQL statement or PL/SQL block. For
example, if you enter a script such as:
SELECT REGION_NAME, CITY
/* THIS & THAT */
FROM EMP_DETAILS_VIEW
WHERE SALARY>12000;
@@ (double at sign)
START file_name
@SALES
http://download.oracle.com/docs/cd/B28359_01/server.111/b31189/ch12003.htm#BACIEHDJ
Examples
Suppose that you have the following script named PRINTRPT:
SELECT DEPARTMENT_ID, CITY FROM EMP_DETAILS_VIEW WHERE SALARY>12000;
@EMPRPT.SQL
@@ WKRPT.SQL
When you START PRINTRPT and it reaches the @ command, it looks for the script named EMPRPT
in the current working directory and runs it. When PRINTRPT reaches the @@ command, it looks for
the script named WKRPT in the same path as PRINTRPT and runs it.
Suppose that the same script PRINTRPT was located on a web server and you ran it with START
HTTP://machine_name.domain:port/PRINTRPT. When it reaches the @ command, it looks for the
script named EMPRPT in the current working directory and runs it. When PRINTRPT reaches the @@
command, it looks for the script named WKRPT in the same url as PRINTRPT,
HTTP://machine_name.domain:port/WKRPT.SQL and runs it.
You can include a WHENEVER SQLERROR command in a script to automatically exit SQL*Plus
with a return code should your script generate a SQL error. Similarly, you can include a WHENEVER
OSERROR command to automatically exit should an operating system error occur. In iSQL*Plus, the
script is stopped and focus is returned to the Workspace. See the WHENEVER SQLERROR command,
and the WHENEVER OSERROR command for more information.
C:\OraHome1\bin>type x.bat
@echo off
sqlplus -silent scott/tiger @x.sql
echo ERRORLEVEL is %ERRORLEVEL%
C:\OraHome1\bin>type x.sql
WHENEVER OSERROR EXIT OSCODE;
SPOOL invalid_dir/output.lst;
SELECT 'X' FROM DUAL;
SPOOL OFF;
EXIT 0;
C:\OraHome1\bin>x
SP2-0332: Spoolfil kan ikke oprettes.
O/S-meddelelse: No such file or directory
Format: { EXIT | QUIT } [ SUCCESS | FAILURE | WARNING | n |
<variabel> | :<tilknytningsvariabel> ] [ COMMIT | ROLLBACK ]
ERRORLEVEL is 3
Code:
sqlplus vikas/vikas << END
WHENEVER SQLERROR EXIT;
WHENEVER OSERROR EXIT;
spool /oracle/vikas/output.txt
desc WHITELIST;
desc USERS;
desc TRANSACTION;
desc computer;
spool off;
!echo ALL SUCCESSFUL
END
if [ $? -ne 0 ];
then
echo "ERROR! SQL*Plus failed..."; exit 1
else
echo "\n\nOne or more query has failed if --- ALL SUCCESSFUL -- is not
echoed !!!"
fi
In the following START command, SQL*Plus would substitute PU_CLERK for &1 and 3100 for &2 in
the script MYFILE:
INPUT
Save this file as PROMPT2. Next, run this script. SQL*Plus prompts for the value of ENUMBER
using the text you specified with PROMPT and ACCEPT:
START PROMPT2
CLEAR SCREEN
Before continuing to the next section, reset all columns to their original formats and headings by
entering the following command:
CLEAR COLUMNS
You reference bind variables in PL/SQL by typing a colon (:) followed immediately by the name of the
variable. For example
:ret_val := 1;
To change this bind variable in SQL*Plus, you must enter a PL/SQL block. For example:
BEGIN
:ret_val:=4;
END;
/
PRINT RET_VAL
BEGIN
OPEN :employee_info FOR SELECT EMPLOYEE_ID, SALARY
FROM EMP_DETAILS_VIEW WHERE
JOB_ID='SA_MAN' ;
END;
/
PRINT employee_info
VARIABLE cv REFCURSOR
EXECUTE EmpPack.EmpInfoRpt(:cv)
PRINT cv
Default Display
The default width of datatype columns is the width of the column in the database. The column width of
a LONG, BLOB, BFILE, CLOB, NCLOB or XMLType defaults to the value of SET
LONGCHUNKSIZE or SET LONG, whichever is the smaller.
The default width and format of unformatted DATE columns in SQL*Plus is determined by the
database NLS_DATE_FORMAT parameter. Otherwise, the default format width is A9. See the
FORMAT clause of the COLUMN command for more information on formatting DATE columns.
Left justification is the default for datatypes.
To insert a new record containing warehouse_id and warehouse_spec values into the new warehouses
table, enter
INSERT into warehouses (warehouse_id, warehouse_spec)
VALUES (100, sys.XMLTYPE.createXML(
'<Warehouse whNo="100">
<Building>Owned</Building>
</Warehouse>'));
To set the XMLType column width to 20 characters and then select the XMLType column, enter
COLUMN Building FORMAT A20
SELECT
w.warehouse_spec.extract('/Warehouse/Building/text()').getStringVal()
"Building"
FROM warehouses w;
To compute the sum of salaries for departments 10 and 20 without printing the
compute label:
COLUMN DUMMY NOPRINT;
COMPUTE SUM OF SALARY ON DUMMY;
BREAK ON DUMMY SKIP 1;
Next, enter the following commands into the file, using your text editor:
SPOOL TEMP
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES
SET PAGESIZE 24
SET NEWPAGE 0
SET LINESIZE 70
SPOOL OFF
If you do not want to see the output on your screen, you can also add SET TERMOUT OFF to the
beginning of the file and SET TERMOUT ON to the end of the file. Save and close the file in your text
editor (you will automatically return to SQL*Plus). Now, run the script EMPRPT:
@EMPRPT
Example01:
SQLPLUS -S -M "HTML ON TABLE 'BORDER="2"'" hr/hr@orcl @depart.sql > depart.html
Example02:
SPOOL report.html
SPOOL OFF
The </BODY> and </HTML> tags are appended to the spool file, report.html, before it
is closed.
To use this feature, you must create a PLAN_TABLE table in your schema and then have the
PLUSTRACE role granted to you. DBA privileges are required to grant the PLUSTRACE role. For
information on how to grant a role and how to create the PLAN_TABLE table, see the Oracle Database
SQL Language Reference.
For more information about the roles and the PLAN_TABLE, see the Oracle Database SQL Language
Reference and the AUTOTRACE variable of the SET command.
Creating a PLAN_TABLE
Run the following commands from your SQL*Plus session to create the PLAN_TABLE in the HR
schema:
CONNECT HR
@%ORACLE_HOME%/rdbms/admin/utlxplan.sql
Execution Plan
The Execution Plan shows the SQL optimizer's query execution path. Execution Plan output is
generated using EXPLAIN PLAN and DBMS_XPLAN.
For information about interpreting the output of DBMS_XPLAN, see the Oracle Database Performance
Tuning Guide.
Statistics
The statistics are recorded by the server when your statement executes and indicate the system
resources required to execute your statement. The results include the following statistics.
Database Statistic
Name Description
recursive calls Number of recursive calls generated at both the user and system level. Oracle
Database maintains tables used for internal processing. When Oracle Database
needs to make a change to these tables, it internally generates an internal SQL
statement, which in turn generates a recursive call.
db block gets Number of times a CURRENT block was requested.
consistent gets Number of times a consistent read was requested for a block
physical reads Total number of data blocks read from disk. This number equals the value of
"physical reads direct" plus all reads into buffer cache.
redo size Total amount of redo generated in bytes
bytes sent through Total number of bytes sent to the client from the foreground processes.
SQL*Net to client
bytes received Total number of bytes received from the client over Oracle Net.
through SQL*Net
from client
SQL*Net round- Total number of Oracle Net messages sent to and received from the client
trips to/from client
sorts (memory) Number of sort operations that were performed completely in memory and did
not require any disk writes
sorts (disk) Number of sort operations that required at least one disk write
rows processed Number of rows processed during the operation
To monitor disk reads and buffer gets.
SET AUTOTRACE TRACEONLY STATISTICS
How does one trace (and explain) SQL statements from SQL*Plus?
Method 1: Autotrace Facility
When the AUTOTRACE setting is enabled, SQL*Plus will print an EXPLAIN PLAN and execution
statistics after each SQL statement. Look at this example:
SQL> set autotrace on
SQL> select * from dept where deptno = 40;
DEPTNO DNAME LOC
---------- -------------- -------------
40 OPERATIONS BOSTON
Execution Plan
----------------------------------------------------------
0 SELECT STATEMENT Optimizer=CHOOSE (Cost=1 Card=1 Bytes=18)
1 0 TABLE ACCESS (BY INDEX ROWID) OF 'DEPT' (Cost=1 Card=1 Bytes=18)
2 1 INDEX (UNIQUE SCAN) OF 'PK_DEPT' (UNIQUE)
Statistics
----------------------------------------------------------
0 recursive calls
0 db block gets
2 consistent gets
0 physical reads
0 redo size
499 bytes sent via SQL*Net to client
503 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
1 rows processed
PLAN_TABLE_OUTPUT
-----------------------------------------------------------------------------------
----
Plan hash value: 2852011669
-----------------------------------------------------------------------------------
----
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time
|
-----------------------------------------------------------------------------------
----
| 0 | SELECT STATEMENT | | 1 | 20 | 1 (0)|
00:00:01 |
| 1 | TABLE ACCESS BY INDEX ROWID| DEPT | 1 | 20 | 1 (0)|
00:00:01 |
|* 2 | INDEX UNIQUE SCAN | PK_DEPT | 1 | | 0 (0)|
00:00:01 |
-----------------------------------------------------------------------------------
----
2 - access("DEPTNO"=40)
14 rows selected.
• HR
• CLASS1
• % (all users)
ATTRIBUTE Must contain the name (in uppercase) of the SQL, SQL*Plus, or PL/SQL
command to disable (for example, RUN). If you are disabling a role, it must
contain the character string "ROLES". You cannot enter a wildcard. See PUP
Table Administration for a list of SQL and SQL*Plus commands you can
disable. See Creating and Controlling Roles for information on how to disable a
role.
SCOPE Not used, it is recommended that you enter NULL. Other products may store
specific file restrictions or other data in this column.
NUMERIC_VALUE Not used, it is recommended that you enter NULL. Other products may store
numeric values in this column.
PUP Column Description
CHAR_VALUE Must contain the character string "DISABLED" to disable a SQL, SQL*Plus, or
PL/SQL command. If you are disabling a role, it must contain the name of the
role you wish to disable. You cannot use a wildcard. See Disabling Commands
with SQLPLUS -RESTRICT for information on disabling a role.
DATE_VALUE Not used, it is recommended that you enter NULL. Other products may store
DATE values in this column.
LONG_VALUE Not used, it is recommended that you enter NULL. Other products may store
LONG values in this column.
http://download.oracle.com/docs/cd/B28359_01/server.111/b31189/ch12001.htm
http://download.oracle.com/docs/cd/B28359_01/server.111/b31189/ch12001.htm
Example:
DEFINE _EDITOR=vi
4. To delete this row and remove the restriction from the user HR, CONNECT again as SYSTEM
and enter:
DELETE FROM PRODUCT_USER_PROFILE WHERE USERID = 'HR';
Note:
When you enter "PUBLIC" or "%" for the Userid column, you disable the role for all users. You should
only use "%" or "PUBLIC" for roles which are granted to "PUBLIC". If you try to disable a role that
has not been granted to a user, none of the roles for that user are disabled.
The Scope, Numeric_Value, and Date_Value columns should contain NULL. For example:
PRODUCT USERID ATTRIBUTE SCOPE NUMERIC CHAR DATE LONG
VALUE VALUE VALUE VALUE
------- ------ --------- ----- -------- ------ ----- -----
SQL*Plus HR ROLES ROLE1
SQL*Plus PUBLIC ROLES ROLE2
During login, these table rows are translated into the command
SET ROLE ALL EXCEPT ROLE1, ROLE2
To ensure that the user does not use the SET ROLE command to change their roles after login, you can
disable the SET ROLE command.
To re-enable roles, delete the row containing the restriction.
For more information about database startup, see the Oracle Database Concepts guide. For more
information about starting a database, see the STARTUP command.
Example 10-1 Starting an Instance
To start an Oracle Database instance, without mounting the database, enter
STARTUP NOMOUNT
where SALES is the database name specified in the DB_NAME parameter in the INITSALES.ORA
parameter file.
Database closed.
Database dismounted.
ORACLE instance shut down.
To list the details of the current log file being archived, enter
ARCHIVE LOG LIST
ARCHIVE LOG {LIST | STOP} | {START | NEXT | ALL | integer } [TO destination]
ARCHIVE LOG
ARCHIVE LOG {LIST | STOP} | {START | NEXT | ALL | integer } [TO destination]
ARCHIVE LOG LIST
The following command copies the entire EMPLOYEES table to a table named WESTEMPLOYEES.
Note that the tables are located in two different databases.
COPY FROM HR@HQ TO JOHN@WEST -
REPLACE WESTEMPLOYEES -
USING SELECT * FROM EMPLOYEES
The following command copies selected records from EMPLOYEES to the database to
which SQL*Plus is connected. SQL*Plus creates SALESMEN through the copy. SQL*Plus
copies only the columns EMPLOYEE_ID and LAST_NAME, and at the destination names
them EMPLOYEE_ID and SA_MAN.
Note:
In general, the COPY command was designed to be used for copying data between Oracle and non-
Oracle databases. You should use SQL commands (CREATE TABLE AS and INSERT) to copy data
between Oracle databases.
1.1.15 Refernces
SET ARRAYSIZE Sets the number of rows that SQL*Plus will fetch from the database at one
time. Valid values are 1 to 5000.
The effectiveness of setting ARRAYSIZE depends on how well Oracle
Database fills network packets and your network latency and throughput. In
recent versions of SQL*Plus and Oracle Database, ARRAYSIZE may have
little effect. Overlarge sizes can easily take more SQL*Plus memory which
may decrease overall performance.
SET TERMOUT SET TERMOUT OFF suppresses the display so that you can spool output
from a script without seeing it on the screen.
SET TRIMOUT ON SET TRIMOUT ON or SET TRIMSPOOL ON removes trailing blanks at the
SET TRIMSPOOL ON end of each displayed or spooled line.
PRINT MOD
To create the table EMPLOYEE that contains a nested object, EMPADDR, of type ADDRESS, enter
CREATE TABLE EMPLOYEE
(LAST_NAME VARCHAR2(30),
EMPADDR ADDRESS,
JOB_ID VARCHAR2(20),
SALARY NUMBER(7,2)
);
/
'tst.sql :
PROMPT Enter a valid employee ID
PROMPT For Example 145, 206
SQL>
SQL>
SQL> set echo on
SQL> @tst
SQL> PROMPT Enter a valid employee ID
Enter a valid employee ID
SQL> PROMPT For Example 145, 206
For Example 145, 206
SQL>
SQL> ACCEPT ENUMBER NUMBER PROMPT 'Employee ID. :'
Employee ID. :145
SQL>
SQL> SELECT FIRST_NAME, LAST_NAME, SALARY
2 FROM EMP_DETAILS_VIEW
3 WHERE EMPLOYEE_ID=&ENUMBER;
old 3: WHERE EMPLOYEE_ID=&ENUMBER
new 3: WHERE EMPLOYEE_ID= 145
SET ERRORLOGGING ON
@myfile
To view the errror log written to the default error log table, SPERRORLOG, enter:
Example
If you include the character '$' in your filename, then
SET ESCCHAR $
RUN MYFILE$
Use the SHOW MARKUP command to view the status of MARKUP options.
Example
SET MARKUP HTML ON SPOOL ON HEAD "<TITLE>SQL*Plus Report</title> -
<STYLE TYPE='TEXT/CSS'><!--BODY {background: ffffc6} --></STYLE>"
SET ECHO OFF
SPOOL employee.htm
SELECT FIRST_NAME, LAST_NAME, SALARY
FROM EMP_DETAILS_VIEW
WHERE SALARY>12000;
SPOOL OFF
SET MARKUP HTML OFF
SET ECHO ON
As this script contains SQL*Plus commands, do not attempt to run it with / (slash) from the buffer
because it will fail. Save the script in your text editor and use START to execute it:
START employee.sql
DUAL
1.1.15.2.1 CLEAR
CLEAR CL[EAR] option ...
where option represents one of the following clauses:
BRE[AKS]
BUFF[ER]
COL[UMNS]
COMP[UTES]
SCR[EEN]
SQL
TIMI[NG]
Resets or erases the current value or setting for the specified option.
Clears the text from SQL buffer. CLEAR SQL has the same effect as CLEAR BUFFER,
unless you are using multiple buffers.
1.1.15.2.2 BREAK
Example
BREAK ON DEPARTMENT_ID SKIP PAGE ON JOB_ID -
SKIP 1 ON SALARY SKIP 1
Examples
To set a bottom title with CORPORATE PLANNING DEPARTMENT on the left and a date on the
right, enter
BTITLE LEFT 'CORPORATE PLANNING DEPARTMENT' -
RIGHT '1 JAN 2001'
To set a bottom title with CONFIDENTIAL in column 50, followed by six spaces and a date, enter
BTITLE COL 50 'CONFIDENTIAL'
TAB 6
'1 JAN 2001'
1.1.15.2.3 COMPUTE
To sum salaries for departments <= 20 without printing the compute label, enter
COLUMN DUMMY NOPRINT
COMPUTE SUM OF SALARY ON DUMMY
BREAK ON DUMMY SKIP 1
SELECT DEPARTMENT_ID DUMMY, DEPARTMENT_ID, LAST_NAME, SALARY
FROM EMP_DETAILS_VIEW
WHERE DEPARTMENT_ID <= 20
ORDER BY DEPARTMENT_ID;
1.1.15.2.4 INPUT
Syntax
I[NPUT] [text]
Examples
Assume the SQL buffer contains the following command:
SELECT LAST_NAME, DEPARTMENT_ID, SALARY, COMMISSION_PCT
FROM EMP_DETAILS_VIEW
2* FROM EMP_DETAILS_VIEW
2* FROM EMP_DETAILS_VIEW
INPUT
3 WHERE JOB_ID = 'SA_MAN'
4 AND COMMISSION_PCT=.25
5
INPUT prompts you for new lines until you enter an empty line or a period. The SQL buffer now
contains the following lines:
SELECT LAST_NAME, DEPARTMENT_ID, SALARY, COMMISSION_PCT
FROM EMP_DETAILS_VIEW
WHERE JOB_ID = 'SA_MAN'
AND COMMISSION_PCT = .25
ORDER BY LAST_NAME
1.1.15.2.5 LIST
Term Description
n Lists line n.
nm Lists lines n through m.
n* Lists line n through the current line.
n LAST Lists line n through the last line.
* Lists the current line.
*n Lists the current line through line n.
* LAST Lists the current line through the last line.
LAST Lists the last line.
Examples
To list the contents of the buffer, enter
LIST
or enter
;
1 SELECT LAST_NAME, DEPARTMENT_ID, JOB_ID
2 FROM EMP_DETAILS_VIEW
3 WHERE JOB_ID = 'SH_CLERK'
4* ORDER BY DEPARTMENT_ID
To list from the current line (now line 2) to the last line, enter
LIST * LAST
1.1.15.2.6 PRINT
VARIABLE n NUMBER
BEGIN
:n := 1;
END;
/
PRINT n
N
----------
1
1.1.15.2.7 REPFOOTER
Examples
To define "END EMPLOYEE LISTING REPORT" as a report footer on a separate page and to center
it, enter:
REPFOOTER PAGE CENTER 'END EMPLOYEE LISTING REPORT'
TTITLE RIGHT 'Page: ' FORMAT 999 SQL.PNO
SELECT LAST_NAME, SALARY
FROM EMP_DETAILS_VIEW
WHERE SALARY > 12000;
LAST_NAME SALARY
------------------------- ----------
King 24000
Kochhar 17000
De Haan 17000
Russell 14000
Partners 13500
Hartstein 13000
----------
sum 98500
Page: 2
END EMPLOYEE LISTING REPORT
6 rows selected.
REPHEADER
1.1.15.2.8 SET
http://download.oracle.com/docs/cd/B28359_01/server.111/b31189/ch12040.htm
1.1.15.2.9 SPOOL
To stop spooling and print the file on your default printer, enter
SPOOL OUT
1.1.15.2.10 START
1.1.15.2.11 STARTUP
Syntax
STARTUP options | upgrade_options
where options has the following syntax:
[FORCE] [RESTRICT] [PFILE=filename] [QUIET] [ MOUNT [dbname] | [ OPEN [open_options]
[dbname] ] | NOMOUNT ]
where open_options has the following syntax:
READ {ONLY | WRITE [RECOVER]} | RECOVER
and where upgrade_options has the following syntax:
[PFILE=filename] {UPGRADE | DOWNGRADE} [QUIET]
Starts an Oracle Database instance with several options, including mounting and opening a database.
Terms
FORCE
Shuts down the current Oracle Database instance (if it is running) with SHUTDOWN mode ABORT,
before restarting it. If the current instance is running and FORCE is not specified, an error results.
FORCE is useful while debugging and under abnormal circumstances. It should not normally be used.
RESTRICT
Only enables Oracle Database users with the RESTRICTED SESSION system privilege to connect to
the database. Later, you can use the ALTER SYSTEM command to disable the restricted session
feature.
PFILE=filename
Causes the specified parameter file to be used while starting up the instance. If PFILE is not specified,
then the default STARTUP parameter file is used. The default file used is platform specific. For
example, the default file is $ORACLE_HOME/dbs/init$ORACLE_SID.ora on UNIX, and
ORACLE_HOME\database\initORCL.ora on Windows.
QUIET
Suppresses the display of System Global Area information for the starting instance.
MOUNT dbname
Mounts a database but does not open it.
dbname is the name of the database to mount or open. If no database name is specified, the database
name is taken from the initialization parameter DB_NAME.
OPEN
Mounts and opens the specified database.
NOMOUNT
Causes the database not to be mounted upon instance startup.
Cannot be used with MOUNT, or OPEN.
RECOVER
Specifies that media recovery should be performed, if necessary, before starting the instance.
STARTUP RECOVER has the same effect as issuing the RECOVER DATABASE command and
starting an instance. Only complete recovery is possible with the RECOVER option.
UPGRADE
Starts the database in OPEN UPGRADE mode and sets system initialization parameters to specific
values required to enable database upgrade scripts to be run. UPGRADE should only be used when a
database is first started with a new version of the Oracle Database Server.
See the Oracle Database Upgrade Guide for details about preparing for, testing and implementing a
database version upgrade.
When run, upgrade scripts transform an installed version or release of an Oracle database into a later
version, for example, to upgrade an Oracle9i database to Oracle Database 10g. Once the upgrade
completes, the database should be shut down and restarted normally.
DOWNGRADE
Starts the database in OPEN DOWNGRADE mode and sets system initialization parameters to specific
values required to enable database downgrade scripts to be run.
See the Oracle Database Upgrade Guide for details about preparing for, testing and implementing a
database version downgrade.
When run, downgrade scripts transform an installed version or release of Oracle Database into a
previous version, for example, to downgrade an Oracle10g database to an Oracle9i database. Once the
downgrade completes, the database should be shut down and restarted normally.
Usage
You must be connected to a database as SYSOPER, or SYSDBA. You cannot be connected to a shared
server via a dispatcher.
STARTUP with no arguments is equivalent to STARTUP OPEN.
STARTUP OPEN RECOVER mounts and opens the database even when recovery fails.
Examples
To start an instance using the standard parameter file, mount the default database, and open the
database, enter
STARTUP
or enter
STARTUP OPEN database
To start an instance using the standard parameter file, mount the default database, and open the
database, enter
STARTUP FORCE RESTRICT MOUNT
To start an instance using the parameter file TESTPARM without mounting the database, enter
STARTUP PFILE=testparm NOMOUNT
To shutdown a particular database, immediately restart and open it, allow access only to users with the
RESTRICTED SESSION privilege, and use the parameter file MYINIT.ORA. enter
STARTUP FORCE RESTRICT PFILE=myinit.ora OPEN database
STARTUP MOUNT
1.1.15.2.12 VARIABLE
Syntax
VAR[IABLE] [variable [type] ]
where type represents one of the following:
NUMBER
CHAR
CHAR (n [CHAR | BYTE])
NCHAR
NCHAR (n)
VARCHAR2 (n [CHAR | BYTE])
NVARCHAR2 (n)
BLOB
BFILE
CLOB
NCLOB
REFCURSOR
BINARY_FLOAT
BINARY_DOUBLE
To free resources used by BLOB, BFILE, CLOB and NCLOB bind variables, you may need to
manually free temporary LOBs with:
EXECUTE DBMS_LOB.FREETEMPORARY(:cv)
Example.
The following example illustrates automatically displaying a bind variable:
SET AUTOPRINT ON
VARIABLE a REFCURSOR
BEGIN
OPEN :a FOR SELECT LAST_NAME, CITY, DEPARTMENT_ID
FROM EMP_DETAILS_VIEW
WHERE SALARY > 12000
ORDER BY DEPARTMENT_ID;
END;
/
Example:
VARIABLE ret_val NUMBER
BEGIN
:ret_val:=4;
END;
/
PRINT ret_val
Example.
VARIABLE rc REFCURSOR
BEGIN
OPEN :rc FOR SELECT DEPARTMENT_NAME, LAST_NAME, SALARY
FROM EMP_DETAILS_VIEW
WHERE SALARY > 12000
ORDER BY DEPARTMENT_NAME, LAST_NAME;
END;
/
Example.
The following example illustrates producing a report containing a CLOB column, and then displaying
it with the SET LOBOFFSET command.
VARIABLE T CLOB
BEGIN
SELECT CLOB_COL INTO :T FROM CLOB_TAB;
END;
/
To print 200 characters from the column clob_col, enter
SET LINESIZE 70
SET LONG 200
PRINT T
T
----------------------------------------------------------------------
Remember to run the Departmental Salary Bill report each month This r
eport contains confidential information.
T
----------------------------------------------------------------------
Departmental Salary Bill report each month This report contains confi
dential information.
1.1.15.2.13 XQUERY
The SQL*Plus XQUERY command enables you to perform an XQuery 1.0 query on a specified
database.
XML output from the XQUERY command is displayed as native XML according to the active SET
command options. SET LONG typically needs to be set. It may be useful to consider the following
settings:
• Linesize for rows longer than the default 80 characters (SET LINESIZE).
• LOB, LONG and XML Type Size for rows longer than the default 80 characters (SET LONG).
• Output Page Setup to match output (SET PAGESIZE).
• Display Headings to repress the "Result Sequence" column heading (SET HEADING OFF).
There are four SET commands specific to the XQUERY command. The SHOW XQUERY command
gives the status of these settings. They are:
Table 12-6 XQUERY SET commands
SET Command
SET XQUERY BASEURI
SET XQUERY ORDERING
SET XQUERY NODE
SET XQUERY CONTEXT
For more information about the SET XQUERY commands, see :
• SET XQUERY BASEURI {text}
• SET XQUERY ORDERING {UNORDERED | ORDERED | DEFAULT}
• SET XQUERY NODE {BYVALUE | BYREFERENCE | DEFAULT}
• SET XQUERY CONTEXT {text}
Examples
The XQuery statement in the following script queries the EMP_DETAILS_VIEW view of the HR
schema:
set long 160
set linesize 160
xquery for $i in
ora:view("EMP_DETAILS_VIEW")
return $i
/