create or replace procedure INSPROCxmlDoc IN CLOB, tableName IN VARCHAR2 is insCtx DBMS_XMLSave.ctxType; rows number; begin insCtx := DBMS_XMLSave.newContexttableName; -- get the context
Trang 1<xsd:attributeGroup ref="productDetails"/>
</xsd:complexType>
</xsd:element>
<xsd:attributeGroup name="productDetails">
<xsd:attribute name="productID" use="required" type="xsd:ID"/>
<xsd:attribute name="name" use="required" type="xsd:string"/>
<xsd:attribute name="description" use="required" type="xsd:string"/>
<xsd:attribute name="unit" type="xsd:positiveInteger"/>
<xsd:attribute name="price" use="required" type="xsd:decimal"/>
<xsd:attribute name="stock" type="xsd:integer"/>
Uniqueness is declared at the same level as the complex type definition for the “Product” element
Thetc: namespace is for the schema you are creating and is declared in the xsd:schema element The
xsd:selector value specifies the elements to constrain (the “Product” elements), and xsd:field specifies
the attribute to constrain (productID)
You can use xsd:key and xsd:keyref to create references between elements For example, youcan create a “Customer” element and then reference it from multiple “Invoice” elements:
To allow an element to be NULL, use thenillable attribute:
<xsd:element name="FlightDinner" nillable="true"/>
Using XSU to Select, Insert, Update,
and Delete XML Values
You can use Oracle’s XML-SQL Utility (XSU) to convert the result of a SQL query to XML XSU
Trang 2You can access XSU via Java and PL/SQL APIs (application programming interfaces) The XSUJava classes are part of the Oracle kernel software The PL/SQL API is a wrapper that publishes
the Java classes to PL/SQL (see Chapter 39) Because the XSU classes are stored in the database,
you can write new stored procedures to directly access XSU’s Java classes Because a PL/SQL
API is available, XSU’s functionality can be accessed directly through SQL
For example, you can generate the XML version of the RATING table via the XSU PL/SQLprocedures The following listing creates a procedure named PRINTCLOBOUT that will be called
as part of the data-output process The data will be read in as a CLOB
create or replace procedure PRINTCLOBOUT(result IN OUT NOCOPY CLOB)
Now that the PRINTCLOBOUT procedure exists, run the following anonymous PL/SQL block
This block queries the RATING table, so that table must be accessible from your schema (see the
set up the query context
queryCtx := DBMS_XMLQuery.newContext('select * from rating');
get the result
Trang 3The result is the RATING table, formatted with XML tags:
PL/SQL procedure successfully completed
Insert, Update, and Delete Processing with XSU
To insert a document into a table or view, use the DBMS_XMLSave package XSU will parse the
document and create an insert statement that inserts the values into all the columns of the table
or view An absent element is treated as a NULL value.
create or replace procedure INSPROC(xmlDoc IN CLOB,
tableName IN VARCHAR2) is
insCtx DBMS_XMLSave.ctxType;
rows number;
begin
insCtx := DBMS_XMLSave.newContext(tableName); get the context
rows := DBMS_XMLSave.insertXML(insCtx,xmlDoc); insert the doc
DBMS_XMLSave.closeContext(insCtx); close the handle
end;
/
You can now pass in XML documents as CLOB input values to the INSPROC procedure,along with the table name INSPROC will take the XML document and insert its values into the
Trang 4create or replace procedure UPDATEPROC ( xmlDoc IN clob) is
DBMS_XMLSave.closeContext(updCtx); close contextend;
/
In this example, the Rating column is the key column used for the update’s where clause:
DBMS_XMLSave.setKeyColumn(updCtx,'RATING'); set RATING as keyThe new values are passed in as an XML document in CLOB format, and the RATING tablevalues are updated based on the contents of the XML document
Delete operations function in much the same way The following procedure takes an XML
document as its input, establishes the Rating column as the key for the RATING table, and performs
the delete based on the key values in the input document Note that newContext takes the table
name RATING as its input value, whereas setKeyColumn takes the key column name (which in
this case happens to also be Rating)
create or replace procedure DELETEPROC(xmlDoc IN clob) is
XSU and Java
If you prefer, you can perform the XSU DML operations via calls to Java classes instead of the PL/
SQL procedures In place of the DBMS_XMLQuery package, you should execute the oracle.xml.sql
.query.OracleXMLQuery class In place of the DBMS_XMLSave package, use oracle.xml.sql.dml
.OracleXMLSave
For example, the Oracle-provided sample Java program for XML queries is customized slightly
in the following listing It relies on connection management in a fashion very similar to that shown in
the JDBC examples (see Chapter 38) The program imports the oracle.xml.sql.query.OracleXMLQuery
class, enabling it to get the XML string; Java’s System.out.println method is then called to display the
output
Trang 6create function GET_XML (in_SQL varchar2)
The data will be returned in CLOB format, so you can use the set long command to set the
maximum display length (the default is 80 characters) You can call GET_XML from within SQL
queries, as shown in the following listing:
set pagesize 100 long 2000
select GET_XML('select * from category') from DUAL;
Trang 7</ROW>
</ROWSET>
Using XMLType
You can use XMLType as a datatype in your tables XMLType can be used to store and query
XML data in the database As a type, XMLType has member functions (see Chapter 33) to access,
extract, and query XML data using a class of operations known as Xpath expressions The SYS_
XMLGEN, SYS_XMLAGG, and DBMS_XMLGEN packages create XMLType values from existing
object-relational data When you designate a column as using the XMLType datatype, Oracle will
store the data internally in a CLOB datatype
The following listing shows the creation of a table using the XMLType datatype:
create table MY_XML_TABLE
If you increase the describe depth, you will see the member functions for the XMLType column
as well The following listing shows the first few of the many functions and methods available:
set describe depth 5
-STATIC FUNCTION CREATEXML RETURNS XMLTYPE
Argument Name Type In/Out Default?
- - -
-XMLDATA CLOB IN
METHOD
Trang 8
-MEMBER FUNCTION EXISTSNODE RETURNS NUMBER
Argument Name Type In/Out Default?
-MEMBER FUNCTION GETNUMBERVAL RETURNS NUMBER
You can now insert values into MY_XML_TABLE by calling XMLType’s CREATEXML method:
insert into MY_XML_TABLE (Key1, Xml_Column)
Trang 9You can create functional indexes on columns created with theXMLType datatype to improve the performance of queries
Other Features
This chapter has shown a very high-level view of the interaction of XML data with the Oracle
database There are many other possibilities, including the use of style sheets for data formatting,
and creating XSQL pages You can even create text indexes on XMLType columns:
create index XML_INDEX on MY_XML_TABLE (Xml_Column)
indextype is ctxsys.context;
NOTE
See Chapter 25 for further details on text indexes
Oracle provides the following packages to interact with XML data:
DBMS_XMLGEN Converts the results of SQL queries to canonical XML format, returning
them as a CLOB DBMS_XMLGEN is implemented in C and compiled
in the database kernel DBMS_XMLGEN is similar in functionality to theDBMS_XMLQuery package
SYS_XMLGEN Generates XML within SQL queries DBMS_XMLGEN and other packages
operate at a query level, giving aggregated results for theentire query SYS_
XMLGEN operates on asingle argument inside a SQL query and convertsthe result to XML
SYS_XMLGEN takes in a scalar value, object type, or an XMLTypeinstance to be converted to an XML document It also takes an optionalXMLGenFormatType object to specify formatting options for the result
SYS_XMLGEN returns an XMLType
SYS_XMLAGG Aggregates over a set of XMLTypes SYS_XMLAGG aggregates all the
input XML documents/fragments and produces a single XML document
by concatenating XML fragments and adding a top-level tag that defaults
to ROWSET
Oracle provides utilities to support additional uses, such as oraxml (a command-line interface
to parse an XML document) and oraxsl (a command-line interface used to apply a style sheet on
multiple XML documents) A full discussion of every utility and data-access method is beyond the
scope of this book; see the XML documentation provided with Oracle Database 10g for additional
options and sample programs See the Alphabetical Reference for descriptions of functions that
act on XMLType instances, including EXTRACT, EXTRACTVALUE, SYS_XMLAGG, SYS_XMLGEN,
UPDATEXML, XMLAGG, XMLCONCAT, and XMLELEMENT
Trang 10PART IX Alphabetical Reference
Copyright © 2003, 2004, Oracle Corporation All rights reserved This appendix contains OracleCorporation User Documentation reproduced herein with permission of Oracle Corporation,
Trang 11T his chapter contains references for most major Oracle commands, keywords, features,and functions, with cross-referencing of topics The reference is intended for use by
both developers and users of Oracle, but assumes some familiarity with the products
Reading the introduction to this reference will help you make the most productive use
of the entries
What This Alphabetical Reference Includes
This alphabetical reference contains entries for virtually every Oracle command in SQL, PL/SQL, and
SQL*Plus, as well as definitions of all relevant terms used in Oracle Database 10g and SQL Each
command is listed with its correct format or syntax, an explanation of its purpose and use, the product
or products in which it is used, and important details, restrictions, and hints about it, along with examples
to illustrate proper usage Topics are in alphabetical order and are cross-referenced, both within the
alphabetical reference and to preceding chapters in the book
What This Alphabetical Reference
Does Not Include
This is not a tutorial; it does not explain the screen-oriented development and administration tools
Additionally, there are a few areas where usage is likely to be so specialized or infrequent that inclusion
here did not seem of much benefit In these instances, the text refers you to the Oracle manual in which
you can find the needed information
General Format of Entries
Entries in this reference are typically either definitions of terms or descriptions of functions, commands,
and keywords These are usually structured in seven sections: the keyword, its type, the products in
which it is used, a SEE ALSO cross-reference, the format in which the keyword appears, a description
of its components, and an example of its use A typical entry looks like the following:
RPAD
SEE ALSO CHARACTER FUNCTIONS, LPAD, LTRIM, RTRIM, TRIM, Chapter 7
FORMAT RPAD(string,length [,'set'])
DESCRIPTION Right PAD RPAD makes a string a certain length by adding a certain set of characters
to the right Ifset is not specified, the default pad character is a space
Trang 12SEE ALSO suggests other topics that are closely related to the keyword, or gives the chapter orchapters in the book that give detailed descriptions of how the keyword is used in practice Occasionally
you will be referred to an Oracle manual or other reference book that contains detail beyond the scope
of this reference
FORMAT generally follows the notation of Oracle manuals, with all SQL and other keywords inuppercase In actual use, these must be entered exactly as they are shown (except that case is irrelevant)
Variables and variable parameters are shown in lowercaseitalic This indicates that some appropriate
value should be substituted When parentheses are shown, they must be entered where they appear,
as must words shown in uppercase
Standard Usages for Variables
Some standard usages for variables follow:
This Variable Indicates
column The name of a column
database The name of a database
password A password
segment The name of a segment
table The name of a table
tablespace The name of a tablespace
Other Formatting Guidelines
Some other guidelines for formatting follow:
■ character means the value must be a single character.
■ string typically represents a character column or an expression or column that can be treatedlike a CHAR or VARCHAR2 column after automatic data conversion
■ value usually represents a NUMBER column or an expression or column that can be treatedlike a NUMBER column after automatic data conversion
■ date usually represents a DATE column or an expression or column that can be treated like
a DATE column after automatic data conversion
■ datetime usually represents a TIMESTAMP column or an expression or column that can betreated like a TIMESTAMP column after automatic data conversion
■ integer must be a whole number, such as –3, 0, or 12.
■ expression means any form of a column This could be a literal, a variable, a mathematicalcomputation, a function, or virtually any combination of functions and columns whose finalresult is a single value, such as a string, a number, or a date
Trang 13■ Optional items are enclosed in square brackets, as in [user.], meaning that user is not necessarilyrequired.
■ Alternative items in a list are separated by a single broken vertical bar, as in OFF | ON,which should be read “OFF or ON.” On some systems, this vertical bar is displayed as
a solid vertical bar
■ Required options, where one item of a list of items is required, are surrounded by curly braces,
as in {OFF | ON}.
■ The default item in a list, if there is one, will be listed first.
■ Three periods (an ellipsis) indicate that the preceding expression can be repeated any number
of times, as in column [,column] ., which means that ,column may be any number of additional
columns separated by commas
■ In rare instances, normal notation is either insufficient or inappropriate for what is being shown.
In these cases, the DESCRIPTION section spells out more fully what is intended in the FORMAT
section
Other Elements of a Listing
A few commands have a return type, which indicates the datatype of the value returned by a function
DESCRIPTION is an explanation of the command and its parts Boldface words within the description
usually refer to either commands or variables shown in the FORMAT section
EXAMPLE shows either the results of a function or how a keyword is used in a real command Thestyle of the examples is not the same as the style of the FORMAT section Instead, it follows the style of
the first part of this book (described in Chapter 3), since that style is more typical of real coding practice
The Order of the Keywords
This reference is in alphabetical order, with all entries that begin with symbols coming before the first
entry beginning with the letterA
Words that are hyphenated or that have an underscore character in them are alphabetized as if thehyphen or underscore were a space
Symbols
The symbols are listed in order of appearance with a short definition or name
_ underline (also called underscore, underbar)
Trang 15! (Exclamation Mark)
SEE ALSO $, =, CONTAINS, SOUNDEX, Chapter 25
FORMAT Within SQL, ! is used as part of the “not equal” expression, != For example, you can
select all the city values that are not in the continent of Asia:
select City
from LOCATION
where Continent != 'ASIA';
For CONTEXT text indexes, ! signals the text engine to perform a SOUNDEX search The terms to search for will be expanded to include terms that sound like the search term, using the text’s SOUNDEX
value to determine possible matches
select Title
from BOOK_REVIEW_CONTEXT
where CONTAINS(Review_Text, '!grate')>0;
" (Double Quotation Mark)
SEE ALSO ALIAS, TO_CHAR, Chapters 7 and 10
DESCRIPTION " surrounds a table or column alias that contains special characters or a space,
or surrounds literal text in a date format clause of TO_CHAR.
EXAMPLE Here " is used as an alias:
select NEXT_DAY(CycleDate,'FRIDAY') "Pay Day!"
from PAYDAY;
And here it is used as a formatting portion of TO_CHAR:
select FirstName, Birthdate, TO_CHAR(BirthDate,
'"Baby Girl on" fmMonth ddth, YYYY, "at" HH:MI "in the Morning"')
"Formatted"
from BIRTHDAY
where FirstName = 'VICTORIA';
FIRSTNAME BIRTHDATE Formatted
- -
-VICTORIA 20-MAY-49 Baby Girl on May 20th, 1949,
at 3:27 in the Morning
# (Pound Sign)
SEE ALSO REMARK, /* */, Chapter 6
DESCRIPTION # completes a block of documentation in a SQL*Plus start file where the block
is begun by the word DOCUMENT SQL*Plus ignores all lines from the line where it sees the word
DOCUMENT until the line after the #
Trang 16FORMAT For SQL*Plus:
$ host_command
In UNIX environments, the $ symbol can be replaced with ! when executing host commands.
For CONTEXT text indexes:
select column
from table
where CONTAINS(text_column, '$search_term') >0;
DESCRIPTION $ passes any host command back to the operating system for execution without
exiting SQL*Plus $ is shorthand for HOST This doesn’t work on all hardware or operating systems.
For a CONTEXT text index, $ instructs the search engine to perform a stem expansion on the search
term A stem expansion includes in the search those words that have the same word stem For example,
a stem expansion of the word 'sing' would include 'singing', 'sang', and 'sung'
where CONTAINS(text_column, '?term')>0;
DESCRIPTION For CONTEXT text indexes, ? instructs the text engine to perform a fuzzy match
search The terms to search for will be expanded to include terms that are spelled similarly to the search
term, using the text index as the source for possible matches
DESCRIPTION %FOUND is a success flag for select, insert, update, and delete.cursor is the
name of an explicit cursor declared in a PL/SQL block, or the implicit cursor named SQL %FOUND
can be attached to a cursor name as a suffix The two together are a success flag for the execution of
SELECT, INSERT, UPDATE, and DELETE statements in PL/SQL blocks.
PL/SQL temporarily sets aside a section of memory as a scratchpad for the execution of SQL statements,and for storing certain kinds of information (orattributes) about the state of that execution If the SQL
statement is a select, this area will contain one row of data.
Trang 17Testing %FOUND for the condition of an explicit cursor before it is OPENed raises an EXCEPTION
(error code ORA-01001, INVALID CURSOR)
%ISOPEN
SEE ALSO SQL CURSOR, Chapter 29
FORMAT
cursor%ISOPEN
DESCRIPTION cursor must be either the name of an explicitly declared cursor or the implicit
cursor named SQL %ISOPEN evaluates to TRUE if the named cursor is open, and to FALSE if it
is not SQL%ISOPEN willalways evaluate to FALSE, because the SQL cursor is opened and closed
automatically when a SQL statement not explicitly declared is executed (see SQL CURSOR) %ISOPEN
is used in PL/SQL logic; it cannot be a part of a SQL statement
DESCRIPTION cursor must be either the name of an explicitly declared cursor or the implicit cursor
named SQL cursor%ROWCOUNT contains the cumulative total number of rows that have been fetched
from the active set in this cursor %ROWCOUNT can be used to intentionally process only a fixed
number of rows, but is more commonly used as an exception handler for selects that are intended to
return just one row (for example, select into) In these cases, %ROWCOUNT is set to 0 if no rows
are returned (%NOTFOUND can make this test as well), and to 2 if more than one row is returned,
regardless of the actual number
%ROWCOUNT is used in PL/SQL logic; it cannot be a part of a SQL statement If SQL%ROWCOUNT
is used, it can only refer to the most recently opened implicit cursor If no implicit cursor has been opened,
SQL%ROWCOUNT returns NULL.
%ROWTYPE
SEE ALSO FETCH, Chapter 29
FORMAT
{[user.]table | cursor}%ROWTYPE
DESCRIPTION %ROWTYPE declares a record variable to have the same structure as an entire
row in a table (or view), or as a row retrieved by the named cursor %ROWTYPE is used as part of a
variable declaration and assures that the variable will contain the appropriate fields and datatypes to
handle all of the columns being fetched If [user.]table is used, the table (or view) must exist in the
database
Trang 18table.column used in SQL statements select .into and fetch .into are the only methods for loading
an entire record variable Individual fields within the record can be loaded using :=, as shown here:
BOOKSHELF_RECORD.Publisher := 'PANDORAS';
If a cursor is used as the prefix for %ROWTYPE, then it can contain a select statement with only as many columns as are needed However, if a column that is fetched from a named cursor is an expression,
rather than a simple column name, the expression must be given an alias in the select statement before
it can be referenced using this technique
%TYPE
SEE ALSO %ROWTYPE, Chapter 29
FORMAT
{[user.]table.column | variable}%TYPE
DESCRIPTION %TYPE is used to declare a variable to be of the same type as a previously declared
variable, or as a particular column in a table that exists in the database you’re connected to
EXAMPLE In this example a new variable, Writer, is declared to be the same type as the AuthorName
column in the AUTHOR table Since Writer now exists, it can be used to declare yet another new variable,
Coauthor
Writer AUTHOR.AuthorName%TYPE;
Coauthor Writer%TYPE;
& or && (Ampersand or Double Ampersand)
SEE ALSO :, ACCEPT, DEFINE, START, CONTAINS, Chapter 25
FORMAT For SQL*Plus:
where CONTAINS(Review_Text, 'property & harvests')>0;
DESCRIPTION & and && can be used in several ways (&& applies only to the second definition):
■ As a prefix for parameters in a SQL*Plus start file Values are substituted for &1, &2, etc.See
START.
■ As a prefix for a substitution variable in a SQL command in SQL*Plus SQL*Plus will prompt
for a value if an undefined & or && variable is found && will define the variable and thereby preserve its value; & will not define or preserve the value, but only substitute what is entered
one time.See ACCEPT and DEFINE.
■ When using CONTEXT indexes, & is used to signal an AND condition for text searches
Trang 19' (Single Quotation Mark)
SEE ALSO " (Double Quotation Mark), Chapter 7
FORMAT
'string'
DESCRIPTION ' surrounds a literal, such as a character string or date constant To use one
quotation mark or an apostrophe in a string constant, use two ' marks (not a double quotation mark)
Avoid the use of apostrophes in data (and elsewhere) whenever possible
SEE ALSO PRECEDENCE, SUBQUERY, UPDATE, Chapters 13 and 15
DESCRIPTION Parentheses enclose subqueries or lists of columns, or control precedence within
DESCRIPTION value1 * value2 means value1 multiplied by value2 For CONTEXT indexes, * is
used to weight the individual search terms differently
** (Exponentiation)
SEE ALSO POWER
FORMAT
x ** y
DESCRIPTION x is raised to the power y x and y may be constants, variables, columns, or
expressions Both must be numeric
EXAMPLE 4**4 = 256
Trang 20DESCRIPTION value1 – value2 means value1 minus value2 For CONTEXT indexes, a – tells the
text search of two terms to subtract the score of the second term’s search from the score of the first term’s
search before comparing the result to the threshold score For CTXCAT indexes, a – tells the text search
engine to exclude the row from the result set if the term following the – is found.
-DESCRIPTION SQL*Plus command continuation; a - continues a command on the following line
EXAMPLE
ttitle left 'Current Portfolio'
right 'November 1st, 1999' skip 1
-center 'Industry Listings ' skip 4;
(Comment)
SEE ALSO /* */, REMARK, Chapter 6
FORMAT
any text
DESCRIPTION tells Oracle a comment has begun Everything from that point to the end of the
line is treated as a comment These delimiters are used only within SQL itself or in PL/SQL and must
appear before the SQLTERMINATOR.
EXAMPLE
select Feature, Section, Page
this is just a comment
from NEWSPAPER this is another comment
where Section = 'F';
(Period or Dot [Form 1]) (SQL*Plus)
Trang 21DESCRIPTION The is a variable separator, which is used in SQL*Plus to separate the variable
name from a suffix so that the suffix is not considered a part of the variable name
EXAMPLE Here, the suffix “st” is effectively concatenated to the contents of the variable &Avenue:
define Avenue = 21
select '100 &Avenue.st Street' from DUAL;
produces this:
100 21st Street
This same technique might also be used in a WHERE clause.
(Period or Dot [Form 2])
SEE ALSO SYNTAX OPERATORS, Chapter 21
FORMAT
[user.][table.]column
DESCRIPTION The is a name separator, used to specify the complete name of a column, including
(optionally) its table or user The is also used to address columns within abstract datatypes during
selects, updates, and deletes.
EXAMPLE
select Practice.BOOKSHELF.Title
from Practice.BOOKSHELF, Practice.BOOKSHELF_AUTHOR
where Practice.BOOKSHELF.Title = Practice.BOOKSHELF_AUTHOR.Title;
If the table contains columns based on an abstract datatype, the datatype’s attributes may be accessed
via the notation
Trang 22DESCRIPTION / executes the SQL in the SQL buffer without displaying it, unlike RUN, which
DESCRIPTION /* tells Oracle a comment has begun Everything Oracle sees from that point
forward, even for many words and lines, it regards as a comment until it sees the ending */, which
ends the comment Comments cannot be embedded within comments; that is, a /* is terminated by
the first following */, even if there is an intervening /*
EXAMPLE
select Feature, Section, Page
/* this is a multi-line commentused to extensively document the code */
from NEWSPAPER
where Section = 'F';
: (Colon, Host Variable Prefix)
SEE ALSO INDICATOR VARIABLE
FORMAT
:name
DESCRIPTION name is the name of a host variable When PL/SQL is embedded in a host language
through an Oracle precompiler, host variables can be referenced from within the PL/SQL blocks by
prefixing their host language names with a colon In effect, this is the host variable If PL/SQL changes
its value through an assignment (:=), the value of the host variable is changed Host variables may be
used anywhere a PL/SQL variable can be used The one exception is in assigning the value NULL to a
host variable, which is not supported directly, but requires the use of an indicator variable
EXAMPLE
int BookCount;
select COUNT(*) into :BookCount from BOOKSHELF;
:= (Set Equal To)
SEE ALSO DECLARE, FETCH, SELECT INTO, Chapter 29
FORMAT
variable := expression
DESCRIPTION The PL/SQLvariable is set equal to the expression, which may be a constant, NULL,
or a calculation with other variables, literals, and PL/SQL functions
Trang 23Extension := Quantity * Price;
Title := 'BARBERS WHO SHAVE THEMSELVES';
Name := NULL;
; (Semicolon)
SEE ALSO / (Slash), BUFFER, EDIT, GET, RUN, SQLTERMINATOR, CONTAINS, NEAR, Chapter 25
DESCRIPTION ; executes the SQL or the command that precedes it For CONTEXT indexes, ;
indicates that a proximity search should be executed for the specified text strings If the search terms
are 'summer' and 'lease', then a proximity search for the two terms could be
select Text
from SONNET
where CONTAINS(Text,'summer;lease') >0;
When evaluating the text search results, text with the words 'summer' and 'lease' near to each other
in the text will have higher scores than text with the words 'summer' and 'lease' farther apart
< < > > (PL/SQL Label Name Delimiter)
See BEGIN, BLOCK STRUCTURE, END, GOTO, LOOP, Chapter 29.
@ (“At” Sign [Form 1]) (SQL*Plus)
SEE ALSO @@, START
FORMAT
@file
DESCRIPTION @ starts the SQL*Plus start file namedfile @ is similar to START, but does not
allow command-line arguments
@ (“At” Sign [Form 2])
SEE ALSO CONNECT, COPY, DATABASE LINK, Chapter 23
FORMAT
CON[NECT] user[/password] [@database];
COPY [FROM user/password@database]
[TO user/password@database]
{APPEND | CREATE | INSERT | REPLACE}
table [ (column, [column] ) ]USING query;
SELECT FROM [user.]table[link] [, [user.]table[@link] ]
DESCRIPTION @ prefixes a database name in a CONNECT or COPY command, or a link name
in a FROM clause.
@@ (Double “At” Sign) (SQL*Plus)
Trang 24@@file
DESCRIPTION @@ starts a nested SQL*Plus start file namedfile @@ is similar to @, but differs in
that @@, when used in a command file, will search for a start file in the same directory as the command
file that called it (rather than in the directory you are in when you execute the command file)
{ } (Curly Braces)
SEE ALSO CONTAINS, Chapter 25, Chapter 37
FORMAT For text searches, {} indicate that the enclosed text should be considered part of the search
string even if it is a reserved word For example, if the search term is 'in and out', and you want to search for
the entire phrase, then you must enclose the word 'and' within braces:
REM CONTAINS method for CONTEXT indexes:
select Title
from BOOK_REVIEW_CONTEXT
where CONTAINS(Review_Text, 'transactions {and} finances')>0;
Within Java, {} indicate the beginning and ending of a block See Chapter 37 for examples of Java
DESCRIPTION When used in a SQL*Plus COLUMN, TTITLE, or BTITLE command, | is the default
HEADSEP character, and is used to denote the splitting of a line onto a second line (When used in
listings in this Reference, | denotes a break between alternative choices:variable | literal would be
read “variable or literal.” On some machines this shows as a solid vertical bar.) Within text queries,
| signals an OR condition for searches involving two search terms If either of the search terms is found,
and its search score exceeds the specified threshold value, the text will be returned by the search
EXAMPLE Here’s how | is used as a HEADSEP character.
TTITLE 'This is the First Line|and This is the Second'
produces this:
This is the First Line
and This is the Second
Here’s how | is used as an OR clause in a text search query:
REM CONTAINS method for CONTEXT indexes:
select Title
from BOOK_REVIEW_CONTEXT
where CONTAINS(Review_Text, 'property | harvests')>0;
Trang 25|| (Concatenation)
SEE ALSO (Period or Dot [Form 1]), CONCAT, SUBSTR, Chapter 7
FORMAT
expression1 || expression2
DESCRIPTION || concatenates two strings together
EXAMPLE Use || to display a column of cities, followed by a comma, a space, and the country:
select City||', '||Country from LOCATION;
ABS (Absolute Value)
SEE ALSO NUMBER FUNCTIONS, Chapter 9
Abstract datatypes are datatypes that consist of one or more attributes Rather than being constrained
to the standard datatypes of NUMBER, DATE, and VARCHAR2, abstract datatypes can consist of multiple
attributes and/or other, previously defined abstract datatypes Abstract datatypes are also known as
user-defined types (UDTs) See Chapter 33 for examples, and CREATE TYPE for creation syntax.
ACCEPT
SEE ALSO &, &&, DEFINE
FORMAT
ACC[EPT] variable [NUM[BER]|CHAR|DATE|BINARY_FLOAT|BINARY_DOUBLE] [FOR[MAT]
format] [DEF[AULT] default] [PROMPT text | NOPR[OMPT]] [HIDE]
DESCRIPTION ACCEPT takes input from a user’s keyboard and puts it in the named variable
with the specified datatype If the variable has not been previously DEFINEd, it is created FORMAT
specifies the input format for the reply (such as A20) DEFAULT sets the default value if a reply is not
given PROMPT displays the text to the user before accepting the input NOPROMPT skips a line
and waits for input without displaying any prompt Using neither PROMPT nor NOPROMPT causes
ACCEPT to invent a prompt asking for the value of the variable HIDE suppresses the user’s entry,
Trang 26ACCEPT Temperature NUMBER PROMPT 'How hot? '
DESCRIPTION ACOS returns the arc cosine of a value Input values range from –1 to 1; outputs
are expressed in radians
ADD_MONTHS
SEE ALSO DATE FUNCTIONS, Chapter 10
FORMAT
ADD_MONTHS(date,integer)
DESCRIPTION ADD_MONTHS adds a number of months todate, and returns the date that is
that many months in the future.date must be a legitimate Oracle date integer must be an integer; a
noninteger value will be truncated to the next smallest integer A negative value forinteger will return
a date in the past
EXAMPLE ADD_MONTHS adds 1 month and 0.3 month to April 22, 2001:
SEE ALSO Chapter 9
DESCRIPTION An aggregate function computes a single summary value (such as sum or average)
from the individual number values in a group of values This is an alphabetical list of all current group
functions in the Oracle version of SQL Each of these is listed elsewhere in this reference under its own
name, with its proper format and use Aggregate functions are useful in select lists and ORDER BY and
HAVING clauses.
FUNCTION NAME AND USE
AVG gives the average of the values for a group of rows.
COLLECT takes the inputcolumn value and creates a nested table of the input type out of therows selected
CORR returns the coefficient of correlation of a set of number pairs.
Trang 27COVAR_SAMP returns the sample covariance of a set of number pairs.
CUME_DIST calculates the cumulative distribution of a value in a group of values.
DENSE_RANK computes the rank of a row in an ordered group of rows.
FIRST operates on a set of values from a set of rows that ranks as the first with respect to a given
sorting specification
GROUP_ID distinguishes duplicate groups resulting from a GROUP BY specification.
GROUPING distinguishes superaggregate rows from regular grouped rows.
GROUPING_ID returns a number corresponding to the GROUPING bit vector associated with a row.
LAST operates on a set of values from a set of rows that ranks as the last with respect to a given
sorting specification
MAX gives the maximum of all values for a group of rows.
MEDIAN gives the median value for a group of rows, ignoring NULLs.
MIN gives the minimum of all values for a group of rows.
PERCENT_RANK performs a percent ranking calculation.
PERCENTILE_CONT is a percentile calculation function that assumes a continuous distribution model.
PERCENTILE_DISC is a percentile calculation function that assumes a discrete distribution model.
RANK calculates the rank of a value in a group of values.
REGR functions perform linear regression analysis on a group of values.
STATS_BINOMIAL_TEST tests the difference between a sample proportion and a given proportion.
STATS_CROSSTAB analyzes two nominal values.
STATS_F_TEST tests whether two variables are significantly different.
STATS_KS_TEST tests whether two variables are from the same population.
STATS_MODE returns the value that occurs with the greatest frequency in a group.
STATS_MW_TEST tests two independent samples against a null hypothesis.
STATS_ONE_WAY_ANOVA is a one-way analysis of variance.
STATS_T_TEST_* functions measure the significance of a difference of means.
STATS_WSR_TEST determines whether the differences between samples are significantly different
from zero
STDDEV gives the standard deviation of all values for a group of rows.
STDDEV_POP computes the population standard deviation and returns the square root of the
population variance
STDDEV_SAMP computes the cumulative sample standard deviation and returns the square root
of the sample variance
SUM gives the sum of all values for a group of rows.
VAR_POP returns the population variance of a set of numbers after discarding the NULLs in this set.
VAR_SAMP returns the sample variance of a set of numbers after discarding the NULLs in this set.
VARIANCE gives the variance of all values for a group of rows.
ALIAS
An alias is a temporary name assigned to a table or a column within a SQL statement and is used to refer
to it elsewhere in the same statement (if a table) or in a SQL*Plus command (if a column) You can use
the AS keyword to separate the column definition from its alias.See " (Double Quotation Mark), AS, and
SELECT When used for a table, the alias is referred to as acorrelation name
ALL
Trang 28operator ALL list
DESCRIPTION != ALL is the equivalent of NOT IN.operator can be any one of =, >, >=, <, <=,
or !=, andlist can be a series of literal strings (such as 'Talbot', 'Jones', 'Hild'), a series of literal numbers
(such as 2, 43, 76, 32.06, 444), or a column from a subquery, where each row of the subquery becomes
a member of the list, such as this:
LOCATION.City != ALL (select City from WEATHER)
Thelist value can be a series of columns in the WHERE clause of the main query, as shown here:
Prospect != ALL (Vendor, Client)
RESTRICTIONS list cannot be a series of columns in a subquery, such as this:
Prospect != ALL (select Vendor, Client from )
Many people find this operator and the ANY operator very difficult to remember, because the logic for some of their cases is not immediately intuitive As a result, some form of EXISTS is usually substituted.
The combination of an operator with ALL and a list can be illustrated with the following explanations:
Page = ALL (4,2,7) Page is equal to every item in the list—no number qualifies A subquerycouldreturn
a list where all the items were identical, and a value of Page could be equal to every one of them, but this would be very rare.
Page > ALL (4,2,7) Page is greater than the greatest item in the list (4,2,7)—anything larger than 7 qualifies.
Page >= ALL (4,2,7) Page is greater than or equal to the greatest item in the list (4,2,7)—anything equal
to or larger than 7 qualifies.
Page < ALL (4,2,7) Page is less than the lowest item in the list (4,2,7)—anything below 2 qualifies.
Page <= ALL (4,2,7) Page is less than or equal to the lowest item in the list (4,2,7)—anything equal to or
lower than 2 qualifies.
Page != ALL (4,2,7) Page is not equal to any item in the list—any number qualifies except 4, 2, and 7.
ALLOCATE (Embedded SQL)
SEE ALSO DECLARE CURSOR,Programmer’s Guide to the Oracle Precompilers
FORMAT
EXEC SQL [AT { db_name | :host_variable }]
ALLOCATE { :cursor_variable | :host_ptr }
[[INDICATOR] :ind_ptr]
DESCRIPTION The ALLOCATE clause allocates a cursor variable that will be referenced in a
PL/SQL block See theProgrammer’s Guide to the Oracle Precompilers for details on ALLOCATE
and related clauses such as the host pointer
ALTER CLUSTER
Trang 29ALLOCATE EXTENT
( SIZE size_clause DATAFILE ’ filename ’ INSTANCE integer
)
DEALLOCATE UNUSED
KEEP size_clause
Trang 30parallel_clause::=
DESCRIPTION Descriptions of the parameters can be found under CREATE TABLE They have the
same purpose and effect, except that here they are used to alter a cluster Size is described under CREATE
CLUSTER In order to alter a cluster, you must either own the cluster or have ALTER ANY CLUSTER system
privilege
All tables in a cluster use the values for PCTFREE, PCTUSED, INITRANS, TABLESPACE, and STORAGE set by CREATE CLUSTER ALTER CLUSTER changes these values for future cluster blocks, but does
not affect those that already exist ALTER CLUSTER does not allow changing the extent parameters in
STORAGE The DEALLOCATE UNUSED clause allows the cluster to shrink in size, freeing unused space.
Trang 31recovery_clauses::=
general_recovery::=
Trang 33cancel_clause::=
finish_clause::=
Trang 34ONLINE OFFLINE
FOR DROP RESIZE size_clause autoextend_clause END BACKUP
integer
K M G T
Trang 35UNLIMITED size_clause
TEMPFILE
’ filename ’ filenumber
,
RESIZE size_clause autoextend_clause DROP
INCLUDING DATAFILES ONLINE
OFFLINE
ARCHIVELOG
MANUAL NOARCHIVELOG
NO FORCE LOGGING RENAME FILE ’ filename ’
,
TO ’ filename ’ CLEAR
UNARCHIVED
LOGFILE logfile_descriptor
,
UNRECOVERABLE DATAFILE add_logfile_clauses
drop_logfile_clauses supplemental_db_logging
Trang 36redo_logfile_spec ,
MEMBER ’ filename ’
REUSE ,
TO logfile_descriptor
,
DATA (
ALL PRIMARY KEY UNIQUE FOREIGN KEY ,
) COLUMNS
Trang 37parallel_clause
Trang 38maximize_standby_db_clause::=
register_logfile_clause::=
commit_switchover_clause::=
Trang 39stop_standby_clause::=
default_settings_clauses::=
set_time_zone_clause::=
Trang 40redo_thread_clauses::=
security_clause::=
DESCRIPTION To alter a database, you must have the ALTER DATABASE system privilege
database is the database name, and must be eight or fewer characters long
When a database is first created, it is MOUNTed in EXCLUSIVE mode, meaning no one but its creator has access to it To allow multiple instances to access the database, use MOUNT PARALLEL
if you have installed the Oracle Real Application Clusters option
After mounting a database, you OPEN it RESETLOGS resets the redo log, cleaning out any redo
entries You use this option to restore a database after a partial recovery from a media failure The
NORESETLOGS option leaves everything the same when you OPEN the daabase.
You can recover the database with a RECOVER clause This command performs media recovery
for a lost database You can use multiple recovery processes to apply redo entries to datafiles for each
instance.See RECOVER You can BACKUP a CONTROLFILE to the specified file or to a trace file.
STANDBY databases provide a mechanism for automated failover in the event of a database failure.
See theOracle Database Administrator’s Guide for details on the creation and management of standby
databases
RENAME changes the name of an existing database or redo log file DBAs can also CREATE DATAFILEs and CREATE TEMPFILEs and manage the increments by which datafiles autoextend The
AUTOEXTEND clause can be used to dynamically extend datafiles as needed, in increments of NEXT
size, to a maximum of MAXSIZE (or UNLIMITED) You can use the RESIZE clause to increase or decrease
the size of an existing datafile You can bring a file ONLINE or take it OFFLINE with the DATAFILE
clause You can CREATE a new DATAFILE to replace an old one to re-create a datafile lost without
backup
ARCHIVELOG and NOARCHIVELOG define the way redo log files are used NOARCHIVELOG is
the default, and using it means that redo log files will be reused without saving their contents elsewhere
This provides instance recovery except from a media failure, such as a disk crash ARCHIVELOG forces
redo log files to be archived (usually to another disk or a tape), so that you can recover from a media
FLASHBACK
ON OFF