36

< a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle
Loreen V Haakonson
Cramsession™ for Oracle 8.0 SQL-PL/SQL
Loreen V Haakonson
This study guide will help you to prepare for the Oracle Exam 1Z0-001, Oracle 8.0 SQL-PL/SQL. Exam topics include New Features of SQL*Plus 8.0, Manipulating Data, Creating and Managing Tables, Object Naming, and Writing Executable Statements.
Loreen V Haakonson
Notice: While every precaution has been taken in the preparation of this material, neither the author nor BrainBuzz.com assumes any liability in the event of loss or damage directly or indirectly caused by any inaccuracies or incompleteness of the material contained in this document. The information in this document is provided and distributed "as-is", without any expressed or implied warranty. Your use of the information in this document is solely at your own risk, and Brainbuzz.com cannot be held liable for any damages incurred through the use of this material. The use of product names in this work is for information purposes only, and does not constitute an endorsement by, or affiliation with BrainBuzz.com. Product names used in this work may be registered trademarks of their manufacturers. This document is protected under US and international copyright laws and is intended for individual, personal use only. For more details, visit our
Loreen V Haakonson
legal page.
Loreen V Haakonson
Check for the newest version of this Cramsession
Loreen V Haakonson
Rate this Cramsession
Loreen V Haakonson
Feedback Forum for this Cramsession/Exam
Loreen V Haakonson
More Cramsession Resources:
Loreen V Haakonson
Search for Related Jobs
Loreen V Haakonson
IT Resources & Tech Library
Loreen V Haakonson
SkillDrill - skills assessment
Loreen V Haakonson
CramChallenge - practice questions
Loreen V Haakonson
Certification & IT Newsletters
Loreen V Haakonson
Discounts, Freebies & Product Info
Loreen V Haakonson
http://cramsession.brainbuzz.com/checkversion.asp?V=2451957&FN=oracle/8SQL_PL.pdf
Loreen V Haakonson
http://cramsession.brainbuzz.com/cramreviews/reviewCram.asp?cert=Oracle+8%2E0+SQL%2DPL%2FSQL
Loreen V Haakonson
http://boards.brainbuzz.com/boards/vbt.asp?b=681
Loreen V Haakonson
http://jobs.brainbuzz.com/JobSearch.asp?R=&CSRE=
Loreen V Haakonson
http://itresources.brainbuzz.com
Loreen V Haakonson
http://skilldrill.brainbuzz.com
Loreen V Haakonson
http://www.cramsession.com/signup/default.asp#day
Loreen V Haakonson
http://www.cramsession.com/signup/
Loreen V Haakonson
http://www.cramsession.com/signup/prodinfo.asp
Loreen V Haakonson
© 2000 All Rights Reserved - BrainBuzz.com
Page 2: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

1

Contents:

Contents: ..................................................................................................................................... 1

SUMMARY OF NEW FEATURES IN SQL*Plus 8.0 ............................................................................. 4

Basic SQL.............................................................................................................................. 5

Group Functions .......................................................................................................................10

Subqueries...............................................................................................................................11

SQL*Plus: Formatting Output, Runtime Variables, DEFINE and ACCEPT ...........................................11

OTHER SQL*PLUS INFO.............................................................................................................12

SQL*Plus Editor and Commands:................................................................................................13

Manipulating Data.....................................................................................................................13

Creating and Managing Tables....................................................................................................13

Object Naming Conventions .......................................................................................................14

DATE ...................................................................................................................................16

CHAR(size)...........................................................................................................................17

Constraints ..............................................................................................................................18

PRIMARY KEY CONSTRAINTS ..................................................................................................18

UNIQUE CONSTRAINTS..........................................................................................................18

FOREIGN KEY CONSTRAINTS..................................................................................................19

NOT NULL CONSTRAINTS .......................................................................................................19

Oracle Data Dictionary ...........................................................................................................22

Other Oracle Database Objects...................................................................................................23

SEQUENCES .........................................................................................................................23

INDEXES..............................................................................................................................24

SYNONYMS...........................................................................................................................25

PL/SQL ....................................................................................................................................28

PL/SQL Processing.................................................................................................................28

PL/SQL BLOCKS ....................................................................................................................28

VARIABLES IN PL/SQL ...........................................................................................................28

Writing Executable Statements ...................................................................................................29

Interacting with the Oracle Server...........................................................................................30

Writing Control Structures ......................................................................................................30

Cursors ................................................................................................................................32

Exceptions............................................................................................................................34

Page 3: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

2

While this guide does contain a wealth of information, it is not intended to cover every single detail that you should know for the test. You are expected to know the basics of SQL and ORACLE SQL*Plus. Some sections of this guide will contain some very basic information and in other cases will simply list what you should be familiar with for the test. In either case, you need to have practice all the commands and create some examples of your own. Rote memorization of the examples in this or any other guide will not be enough for you to pass this test!

Overview of Relational Databases, SQL, and PL/SQL

Relational database management systems (RDBMS) have 3 major theoretical characteristics:

1. Structures - objects such as tables, indexes, and views that are manipulated by operations.

2. Operations - well-defined actions that act upon the data and structures and conform to predefined integrity rules.

3. integrity rules - control the type of actions allowed on data or objects in the database.

5 step system development cycle and what happens in each:

1. "Needs assessment" - analysis phase 2. Design - create entity-relationship diagram (ERD) and translate ERD into

logical data model. 3. Build and document - Map logical data model to physical data model 4. Transition - Move from development to production, user acceptance testing,

final documentation. 5. Production - Code is locked down and change control process is implemented.

Summary of SQL operation categories

• DCL (Data Control Language) REVOKE, ALTER USER, GRANT • DML (Data Manipulation Language) SELECT, UPDATE, DELETE, INSERT • DDL (Data Definition Language) CREATE, DROP, ALTER, TRUNCATE • TCO (Transaction Control Operations) ROLLBACK, COMMIT, SAVEPOINT, and

SET TRANSACTION

Benefits of an RDBMS

• Physical data is stored separate from the logical database structure.

Page 4: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

3

• Easy access to data in many variations. • Database design is not constrained and has a very high degree of flexibility. • Data can be stored very efficiently, with minimal redundancy.

ORDBMS (object relational database management system)

• Oracle's object-relational model gives the ability to define objects and have them used within the RDBMS.

• Objects have a name, attributes and methods. • The name uniquely identifies and object. • Attributes are the columns or fields defined for an object to model a real

world entity.

Methods are functions or procedures that define the actions an application can execute on the data stored in the object.

Each object has a constructor method that actually creates a new instance of the given object

These procedures can be written in PL/SQL and stored within the database or written in a language like C and stored external to the database.

ERD (entity relationship diagram) Symbols and Cardinality: Solid line = A must have relation

with no fork = cardinality of 1

with fork = cardinality of 1 or many.

...

Dashed line = A maybe relation

with no fork = cardinality of 0 or 1

with fork = cardinality of 0 or many.

...

# is a UID (unique identifier)

...

Rectangle with rounded edges is a dependent entity.

Page 5: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

4

Rectangle with straight edges is an independent entity.

Read mixed solid and dashed lines from the FROM side of the relationship.

The diagram should be read this way:

A street MAY have MANY signs.

Many signs MUST have ONE street.

Benefits of PL/SQL

• The PL/SQL code is stored and managed within the database. • The PL/SQL source code and execution privileges are managed using common

Oracle database object syntax. • PL/SQL uses native Oracle communication and is tightly integrated. • PL/SQL provides support for SQL and SQL data types. • PL/SQL provides support for Oracle object oriented programming, allowing

you to create software components that are modular, maintainable, and reusable.

• PL/SQL provides for better client server performance by processing PL/SQL procedures stored on the backend and reducing network traffic.

• PL/SQL is portable across any O/S and platform running Oracle.

SUMMARY OF NEW FEATURES IN SQL*Plus 8.0

• New ATTRIBUTE command. Displays attributes for a given column.

• New PASSWORD command, passwords can be changed with no echo of password to input device.

• CONNECT command prompts user to change an expired password.

Page 6: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

5

• EXIT command has a :BindVariable clause and can referenced in PL/SQL or other subprograms. The :BindVariable exits the subprogram and returns SQL*Plus.

• LONG and LONGCHUNKSIZE datatypes determine limits of CLOB and NCLOB datatypes.

• SET command has a LOBOFFSET clause that sets the starting position from which CLOB and NCLOB data is retrieved.

• SET NEWPAGE command has a NONE clause, when used prints no blank lines and no formfeed between pages.

• SET command has a SHIFTINOUT clause which allows correct alignment for terminals that display shift characters.

• SHOW ERRORS includes the TYPE and TYPE BODY clauses.

• VARIABLE command includes clauses NCHAR, NVARCHAR2 (NCHAR VARYING), CLOB and NCLOB.

• The maximum length of CHAR and NCHAR bind variables are 2000.

• The maximum length of VARCHAR2 and NVARCHAR2 are 4000.

Basic SQL

• Oracle SQL commands are 100% complaint to the entry level ANSI/ISO 1992 standard.

• Oracle SQL*PLUS extends ANSI92 SQL to include additional commands and functions.

• The SQL SELECT command is used to query and retrieve data from the database.

• The simplest form of the SELECT command is:

SELECT table_name.column_name, table_name.column_name, ...

FROM schema.table_name ;

• The semi-colon is always required to end a SQL statement.

Page 7: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

6

- The DUAL table is a special table consisting of one column and all null values. Used for arithmetic operations on a

constant value.

Ex. SELECT 2+2 FROM DUAL ; Will return the number 4.

SQL Operator Precedence:

• + - unary arithmetic operators • * / arithmetic operators • + - binary arithmetic operators and the || character operator • All comparison operators (includes is [not] null) • NOT logical operator • AND logical operator • OR logical operator

Arithmetic Operator Precedence:

• + - unary arithmetic operators • * / arithmetic operators • + - binary arithmetic operators

Restricting and Sorting Data

• Use the WHERE clause to screen data.

SELECT table_name.column_name, table_name.column_name, ...

FROM schema.table_name

WHERE condition

ORDER BY table_name.column_name, table_name.column_name, ... ;

• A NULL value does not equate to blank or zero. Use special relational operator to filter.

WHERE field IS NULL or WHERE field IS NOT NULL.

• Can use a column number reference in the ORDER BY clause.

Page 8: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

7

Ex. SELECT student.name, student.phone

FROM student

WHERE student.name IS NOT null

ORDER BY 1 ;

In the example above the output will be sorted by ascending student.name.

• Using ORDER BY to reference a column not in the SELECT statement is OK. The exception is when DISTINCT is used. If DISTINCT is used, ORDER BY field must be in select phrase.

• You cannot use ORDER BY in a subquery.

• You must use column number reference in ORDER BY for compound queries containing set operators such as UNION, INTERSECT, etc... . In these type of queries the ORDER BY must be in the LAST query! Controls all rows returned by complete compound query.

• ORDER BY clause can contain up to a maximum of 255 expressions.

• Maximum ORDER BY columns for a single table equal the number of columns in the table.

• When using ORDER BY and GROUP BY clauses in the same SQL statement, the ORDER BY expressions are subject to the same restrictions as the expressions in the SELECT list described for the GROUP BY clause.

Wildcards:

• % (percent sign) is the multicharacter wildcard. • _ (underscore) is the single character wildcard. • Escape "\" (backslash) is required to use either one of these in a LIKE phrase.

$ and / can be used as a literal.

• Review and know all the relational operators in SQL*PLUS.

• An escape character (or escape phrase) is required to use a % or _ literally.

Page 9: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

8

Ex. SELECT field

FROM table

WHERE field LIKE '%A\%B\%C%" ESCAPE \ ;

will match the character pattern = A%B%C

Be sure you know the use of the escape character in the WHERE clause!!!

Single Row Functions

• A single row function returns a single result for each row of a table or view. A group function returns a single result for groups of rows from a table or view.

Some common single row functions to be familiar with:

to_char( ) to_date( ) to_number( ) length( ) upper( ) lower( ) concat( ) (also know the || concatenation symbol)

mod( ) round( ) trunc( ) sysdate( )

Some of the to_char( ) format options. Be sure to know all of them including ones not listed here:

9 determines length of returned character

0 prefixes value with leading zeros

B returns zero value as blank instead of "0"(zero).

S returns the sign + or -.

MI returns "-" after negative values

PR returns negative values in <angle brackets>

Page 10: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

9

• Know all the date format models, prefixes, suffixes, and case control options for the to_date and to_char functions!!!

• SUBSTR(): The following substr() command takes the last 5 values from a string field named "f1" in a table named "t1".

Example:

if F1 = ‘1234567890’

SELECT substr(f1,-5) FROM t1 ;

Returns the value: '67890'.

• In order of operations, nested functions are evaluated first.

• Use the NVL function to set a value for a column that is null. If a field is null value will be substituted. Value must be of the same type as field (e.g. char or numeric).

o Syntax: NVL(field,value)

• The MONTHS_BETWEEN() date function returns a numeric value.

• Date arithmetic results in a numeric expression which represent the number of days.

o select to_date('30-JAN-99') - to_date('15-JAN-99') from dual ; returns 15

Displaying Data From Multiple Tables

• You can assign an alias to a table and use it to prefix field names.

o Example: SELECT A.field1 as AF1, B.field1 as BF1 FROM tablea A, tableb B ;

• If you alias a table name in a FROM clause you must reference the alias in the SELECT statement. You CANNOT use the full table name.

• An inner join, also called equijoin, is the equality (=) linking of common columns in two tables. Only returns rows where joined values exist and are shared in both tables.

Page 11: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

10

• An outer join returns data from table A, even if there are no matching records in table B. Use the (+) , plus sign in parenthesis, on the table that may have "missing" rows; In this example table B is considered the "outer table".

o SELECT A.F1, B.F1 FROM A , B WHERE A.F1=B.F1(+) ;

• A self join, or recursive join, is when a table is joined to itself. You must use table aliases. Good for identifying duplicate rows.

• AND and = can be used in an outer join. IN and OR cannot be used in an outer-join.

• The minimum number of join statements required to join N tables = N-1. This avoids a Cartesian product.

Group Functions

• Be familiar with the syntax and usage of the following group functions:

o AVG( ) COUNT( ) COUNT(DISTINCT) MAX( ) MIN( ) SUM( )

• You can use aggregate columns in the sum() function.

o Example: SELECT sum(empid * salary) from emp;

• The order of multiple GROUP BY columns must match the order of columns in the SELECT phrase.

• Generally, the group functions (also called aggregate functions) are placed last in the SELECT phrase.

• You cannot use an alias or positional column reference in a GROUP BY clause.

• Use the HAVING clause to restrict rows returned by a group function.

SELECT f1, COUNT(f2)

FROM t1

WHERE f1 = 'XYZ'

GROUP BY f1

HAVING COUNT(f2) > 10 ;

Page 12: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

11

• The HAVING clause can contain a subquery.

Subqueries

• Subqueries provide a way to determine unknown criteria based upon known methods for obtaining it.

• Subqueries answer questions that have multiple parts. A subquery answers the first part of the question and the parent query answers the second part of the question.

• A subquery may itself contain subqueries. This is called nested subqueries.

• Inner most queries are resolved first.

• A subquery is evaluated once for the entire parent query.

• A correlated subquery is evaluated once for each row in the parent query

• Know how to identify a correlated subquery as opposed to a regular subquery.

• The equality "=" operator expects a single row to be returned from a subquery.

• Operators such as IN and EXISTS are used when multiple rows are returned from a subquery.

• ORDER BY is not allowed in a subquery.

• Be very familiar with complex nested subqueries.

SQL*Plus: Formatting Output, Runtime Variables, DEFINE and ACCEPT

• A column alias that is specified without double quotes will always display in upper case. If double quotes are used the case is retained for display.

• Aliases: You can assign an alias to a field in the following way. The alias will display as the column name on output. SELECT field1 AS alias FROM table;

• Numeric fields are right justified by default in output display. Text fields are left justified by default in output display.

• Dividing by a null value will result in a null value. Not the keyword literal "null", but just a null value.

• DEFINE: Defines CHAR or VARCHAR values only.

• DEFINE by itself lists the value and variable type of all defined variables.

Page 13: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

12

• DEFINE variable_name lists the value and variable type of a single defined variable.

• ACCEPT: Must use ACCEPT to define a NUMBER variable.

• ACCEPT variable_name NUMBER PROMPT "text" - needs double quotes if prompt phrase contains imbedded blanks.

• A report can accept a maximum of 9 parameters (& variables)

• Know how to examine and set the SQL*Plus environment, using such SHOW and SET commands as:

- SET VERIFY ON

- SHOW ALL

- SET NUMWIDTH

- SET LINESIZE, etc...

• Know how to execute a SQL*Plus script using the START command or the @ symbol. Using @@ symbol to run a script from within another script requires the script to exist in the same directory as the parent script.

OTHER SQL*PLUS INFO

• The DESCRIBE (DESC) command displays column name, not null columns, and column data types.

• The dash "-" is the SQL*Plus continuation character.

• The DISTINCT function must appear before the field list in the select phrase.

SELECT field1, DISTINCT field2, field3 FROM table 1; will generate an error!

instead:

SELECT DISTINCT field1, field2, field3 FROM table 1;

• Know the variations on the SPOOL command. SPOOL OUT sends data to default printer.

Page 14: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

13

SQL*Plus Editor and Commands:

• Be familiar with all the basic SQL*Plus editor commands.

• Buffer name = afiedt.buf

• A[PPEND] adds specified text to end of the current line.

• To include a single blank enter two spaces between APPEND and text.

• To include a semi-colon at end of appended text, use two semicolons.

• DEL deletes the current line from the buffer.

• I[NPUT] adds one or more lines of text after the current line in the buffer.

• The command buffer can be terminated (and therefore executed) in 3 ways: with slash (/) , semicolon(;) or by pressing ENTER twice.

• The GET command requires a previously save file.

• DDL statements and exiting SQL*Plus cause an implicit COMMIT.

• Bombing out of SQL*Plus causes an implicit ROLLBACK.

Manipulating Data

• DML commands are used to INSERT, UPDATE, DELETE, and SELECT data.

• Be very familiar with the syntax rules for insert, update, and delete commands.

• DML commands can be rolled back (undone) until a transaction is committed.

• DDL and DCL transactions both issue an implicit commit and will commit any outstanding DML commands.

• If the values listed in the values portion of an INSERT statement do not correspond positionally and by datatype to ALL the actual fields in the table, then the field names must be specified in the INSERT statement. Otherwise an error will occur.

Creating and Managing Tables

• The main database objects are listed below. Be sure you can describe each one.

o clusters

o database links

o database triggers

o external procedure libraries

Page 15: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

14

o index-only tables

o indexes

o packages

o sequences

o stored functions

o stored procedures

o synonyms

o tables

o views

• Review and understand the syntax for the CREATE TABLE, ALTER TABLE, DROP TABLE, RENAME TABLE, AND TRUNCATE TABLE commands.

• Know the syntax for the CREATE TABLE... AS SELECT statement. Do not specify data types for columns using this command because data types are automatically taken from the AS SELECT table.

• Oracle will automatically create an index based upon the field or fields specified as the primary key, if one does not already exist.

Object Naming Conventions

Must be between 1 to 30 characters long except for the following exceptions: 1) database names are limited to 8 characters max and 2) database links can be as long as 128 characters max.

- Cannot contain quotation marks.

- Names are not case sensitive.

- Must begin with an alphabetic character from database character set unless surrounded by double quotes.

- Can contain only alphanumeric characters from your database character set and the characters _, $, and #.

- Database link names can contain periods (.) and at signs (@).

- Cannot be an Oracle reserved word.

- Do not use the word DUAL.

Page 16: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

15

• No two objects in the same namespace can have the same name. Note that tables and indexes are in different namespaces and can contain the same name.

• Columns in the same table or view cannot have the same name.

• A name can be enclosed in double quotation marks. These names can contain any combination of characters including spaces. If you give a schema object a name enclosed in double quotation marks, you must use double quotation marks whenever you refer to the object.

• Enclosing a name in double quotes allows it to contain spaces, be case sensitive, begin with a character other than an alphabetic character, such as a numeric character, contain characters other than alphanumeric characters and _, $, and # , and be a reserved word.

• If you give a user or password a quoted name, the name cannot contain lowercase letters.

• Database link names cannot be quoted.

• Know the various datatypes such as VARCHAR2, CHAR, NUMBER, etc... The list below has some of the more common values used:

VARCHAR2(size) This is a variable-length character string data type. The size value specified becomes the maximum length in bytes. Maximum size is 4000 and minimum is 1. You must specify size for a VARCHAR2.

NUMBER(p,s) This is a number data type specified with precision p and scale s. The precision p can range from 1 to 38. The scale s can range from -84 to 127.

NUMBER This is a number data type with no precision or scale specified. Can be used to store zero, positive and negative fixed and floating-point numbers. By default has 38 digits of precision.

LONG This is the data type used to store character data of variable length up to 2 gigabytes.

LONG columns can be referenced in the following places:

Page 17: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

16

• SELECT lists

• SET clauses of UPDATE statements

• VALUES clauses of INSERT statements

LONG column restrictions:

• Only 1 LONG column per table.

• No LONG columns in integrity constraints except for NULL and NOT NULL.

• Cannot index a LONG column.

• A LONG value cannot be returned by a stored function.

LONG columns cannot appear in the following parts of SQL statements:

• WHERE, GROUP BY, ORDER BY, or CONNECT BY clauses.

• Used with the DISTINCT operator in SELECT statements.

• UNIQUE clause of a SELECT statement.

• SQL functions such as SUBSTR or INSTR.

• Expressions or conditions.

• SELECT lists of queries containing GROUP BY clauses.

• SELECT lists of subqueries or queries combined by set operators.

• SELECT lists of CREATE TABLE ... AS SELECT statements.

• SELECT lists in subqueries in INSERT statements.

DATE

This is the data type used to store dates.

ROWID

This is a special Oracle datatype that is a hexadecimal string that represents the unique address of a row in its table. The Oracle 8 rowid is made up of the following pieces:

• The data object number of the object

• The data block in the datafile

• The row in the data block in the datafile.

Page 18: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

17

CHAR(size)

This is a fixed length character data type of length size in bytes. Maximum size is 2000 bytes. The default and minimum size is 1 byte.

CLOB

This is the data type for a character large object containing single-byte characters. Variable-width character sets are not supported. The maximum size is 4 gigabytes.

BLOB

• This is the data type for a binary large object. Maximum size is 4 gigabytes.

• Some of the things that the ALTER TABLE command can be used for in Oracle 8 are listed below:

o Add a column

o Add an integrity constraint

o Redefine a column (datatype, size, default value)

o Modify storage characteristics or other parameters

o Modify the real storage attributes of a nonpartitioned table or the default attributes of a partitioned table

o Enable, disable, or drop an integrity constraint or trigger

o Explicitly allocate an extent

o Explicitly deallocate the unused space of a table

o Allow or disallow writing to a table

o Modify the degree of parallelism for a table

o Modify the logging attributes of a non-partitioned table, partitioned table or table partition(s)

o Modify the CACHE/NOCACHE attributes

o Add, modify, split, move, drop, or truncate table partitions rename a table or a table partition

o Add or modify index-organized table characteristics

o Add or modify LOB columns

o Add or modify object type, nested table type, or VARRAY type column

Page 19: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

18

o Add integrity constraints to object type columns

• The RENAME command in Oracle 8 can be used to rename a TABLE, VIEW, SEQUENCE, or PRIVATE SYNONYM for a table view or sequence.

Constraints

• There are 5 main type of constraints. Be sure you know how to define each of them and what conditions violate each.

• Be sure you know the difference in syntax for table-constraints vs. column-constraints. Be sure you know how to add constraints to an existing table using the ALTER TABLE command.

• Be sure you know how to enable and disable each type of constraint.

• User-defined constraints are used to enforce business rules.

PRIMARY KEY CONSTRAINTS

• Index is automatically created

• Field is NOT NULL and UNIQUE by default

• Only one per table

• Maximum of 16 columns for a composite (multi-column) primary key.

• Composite primary keys must be defined with the table-constraint syntax instead of the column-constraint syntax.

The primary key constraint creates three constraints if they are not already defined: 1) primary key, 2) unique index, and 3) not null.

UNIQUE CONSTRAINTS

• Index is automatically created

• Can define a single column unique index using a column-constraint clause

• Maximum of 16 columns for a composite (multi-column) unique constraint.

• Composite indexes must be defined with the table-constraint syntax instead of the column-constraint syntax.

Page 20: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

19

FOREIGN KEY CONSTRAINTS

• Foreign key constraints are also called Referential Integrity (RI) constraints.

• A unique or primary key constraint must exist on the field referenced in the parent table.

• The unique or primary key constraint in the parent table must be enabled before enabling the foreign key constraint.

• An RI constraint made up of one field can be defined using the column-constraint syntax.

• All RI constraints can be defined using the table-constraint syntax.

• Can not define an RI constraint in a CREATE TABLE ....AS clause. The RI constraint can be added after the table is created using the ALTER TABLE command.

NOT NULL CONSTRAINTS

• Can only be defined at the column level in the create or alter table commands.

• CHECK CONSTRAINTS

• A CHECK constraint can be added at the column or table level and can apply to any column in the table, not just the column on which it is defined.

• Can impose rules on any column in the table, not just the one it is defined on.

• A single column can contain multiple check constraint definitions.

Various examples for adding and dropping column constraints:

add/drop PRIMARY KEY CONSTRAINT:

Syntax: ALTER TABLE table_name ADD(CONSTRAINT [constraint_name] PRIMARY KEY (col1, col2,…col16));

Examples:

• ALTER TABLE t1 ADD (CONSTRAINT pk_t1 PRIMARY KEY (F1));

• ALTER TABLE t1 DROP CONSTRAINT pk_t1;

• ALTER TABLE t1 DROP PRIMARY KEY;

Page 21: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

20

Note: The maximum columns allowed for composite primary key, unique index, or foreign key is 16.

Add/drop UNIQUE CONSTRAINT:

Syntax: ALTER TABLE table_name ADD(CONSTRAINT [constraint_name] UNIQUE (col1, col2,…col16));

Examples:

• ALTER TABLE t1 ADD (CONSTRAINT ak_t1 UNIQUE (F1));

• ALTER TABLE t1 DROP CONSTRAINT ak_t1;

• ALTER TABLE t1 DROP UNIQUE(f1);

Add/drop FOREIGN KEY CONSTRAINT:

Syntax: ALTER TABLE table_name ADD(CONSTRAINT [constraint_name] FOREIGN KEY (col1, col2,…col16) REFERENCES table_name (col1, col2,…col16) [ON DELETE CASCADE] ) ;

Examples:

• ALTER TABLE t2 ADD(CONSTRAINT fk_t1_t2 FOREIGN KEY (f1) REFERENCES t1 (f1) ON DELETE CASCADE) ;

• ALTER TABLE t2 DROP CONSTRAINT fk_t1_t2;

Add/drop CHECK CONSTRAINT:

Syntax: ALTER TABLE table_name ADD(CONSTRAINT [constraint_name] CHECK (condition));

Examples:

• ALTER TABLE t1 ADD(CONSTRAINT ck_t1 CHECK (F2 = F1)) ; • ALTER TABLE t1 DROP CONSTRAINT ck_t1; •

Page 22: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

21

Adding NOT NULL constraint:

Syntax: ALTER TABLE table_name MODIFY (column_name NOT NULL);

Examples:

• ALTER TABLE t1 MODIFY (f2 NOT NULL); • ALTER TABLE t1 MODIFY (f2 NULL);

o A CHECK constraint can be added at the column or table level and can apply to any column in the table, not just the column on which it is defined.

Views

• Can use the DESC command to see the fields in a view.

• Views can be based upon tables and other views.

• A view’s query cannot contain ORDER BY or FOR UPDATE clauses.

• A view’s query cannot select the CURRVAL or NEXTVAL pseudocolumns.

• If a view’s query selects the ROWID, ROWNUM, or LEVEL pseudocolumns, they must have aliases in the view’s query.

• No INSERTs, UPDATEs, or DELETEs are allowed on a view if it contains any of the following constructs:

o Set operators o Group functions o GROUP BY, CONNECT BY, or START WITH clauses o The DISTINCT operator

• If a view contains pseudocolumns or expressions, you can only update the view with an UPDATE statement that does not refer to any of these pseudocolumns or expressions.

• The WITH READ ONLY clause specifies that no inserts, updates, or deletes can be performed through the view.

• A simple view with the WITH CHECK OPTION will restrict DML to those rows that can be included in the view.

• For example if a view statement contains WHERE DEPT = 10, then all rows inserted, updated, or deleted from the view must have a DEPT value equal to 10.

Page 23: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

22

• A complex view (i.e. view based upon two or more tables) will allow inserts on only one of the joined tables. The table must have a primary key (key controlled table).

• A complex view that includes the WITH CHECK OPTION will not generate a compile error, even though it is unallowed syntax and meaningless.

• Query USER_UPDATABLE_COLUMNS to see fields in a view that can be updated.

• CREATE OR REPLACE VIEW will redefine the view and preserve the present security authorizations. Performing a DROP and then a CREATE VIEW will not. You will need to recreate the necessary privileges.

• ALTER VIEW recompiles a database view, affecting dependencies.

• You must have CREATE VIEW system privilege to create a view in your own schema.

• You must have the CREATE ANY VIEW system privilege to create a view in another user’s schema.

• The owner of a view must be explicitly granted the required security. This cannot be acquired through a role.

• Using the FORCE keyword in a view definition will create the view even if all the views base tables are not present or the owner of the view schema has not been granted the required privileges. However, no action can be performed upon the view until those missing conditions are met.

Oracle Data Dictionary

• The data dictionary consists at its lowest level of X$ and K$ C structures, not normally viewable or used by DBA.

• The ALL_ data dictionary views show the user all the database objects that are accessible to them.

• The USER_ data dictionary views show the user all the objects that are owned by the user.

• The DBA_ views allow those who have access to them to see all the database objects.

• The V$_ views display database server performance information.

• Know the basic data and who can access it for the following data dictionary views:

Page 24: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

23

o USER_, ALL_ , DBA_OBJECTS

o USER_, ALL_ , DBA_TABLES

o USER_, ALL_ , DBA_INDEXES

o USER_, ALL_ , DBA_VIEWS

o USER_, ALL_ , DBA_SEQUENCES

o USER_, ALL_ , DBA_USERS

o USER_, ALL_ , DBA_CONSTRAINTS

o USER_, ALL_ , DBA_CONS_CONSTRAINTS

o USER_, ALL_ , DBA_IND_COLUMNS

• The TABLE_PRIVILEGES view displays the grants on objects that the user has granted.

Other Oracle Database Objects

SEQUENCES

• Know what sequences are and how to create them. Be very familiar with the Oracle default values used for creating sequences.

• Increment by defaults to 1. If negative value sequence descends.

• Start with defaults to minvalue for positive sequences or maxvalue for negative sequences.

• Nomaxvalue is the default if maxvalue is not specified.

• Nominvalue is the default if minvalue is not specified.

• Nocycle is the default if cycle is not specified.

• Minimum cache value = 2. Can not cache more values than are in a given sequence cycle.

• If cache and nocache are both NOT specified, the default is to cache 20 values.

• if noorder and order are both NOT specified, noorder is the default.

• To create a sequence in your own schema, you must have CREATE SEQUENCE privilege.

• To create a sequence in another user's schema, you must have CREATE ANY SEQUENCE privilege.

Page 25: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

24

• To drop a sequence in your own schema you must have DROP SEQUENCE privilege.

• To drop another users sequence you must have DROP ANY SEQUENCE privilege.

CURRVAL and NEXTVAL can be used:

• The SELECT list of a SELECT statement that is not contained in a subquery, snapshot, or view.

• The SELECT list of a subquery in an INSERT statement.

• The VALUES clause of an INSERT statement.

• The SET clause of an UPDATE statement.

CURRVAL and NEXTVAL cannot be used:

• A subquery in a DELETE, SELECT, or UPDATE statement.

• A SELECT statement with the DISTINCT operator. A SELECT statement with a GROUP BY or ORDER BY clause.

• A SELECT statement that is combined with another SELECT statement with the UNION, INTERSECT, or MINUS set operator.

• The WHERE clause of a SELECT statement.

• DEFAULT value of a column in a CREATE TABLE or ALTER TABLE statement. The condition of a CHECK constraint.

o Initialize a sequence with NEXTVAL before using CURRVAL, in any given session.

o Oracle will increment the sequence only once in any single SQL Statement. Multiple references to NEXTVAL for a sequence in a single SQL statement, will return the same value.

o If a single SQL statement contains references to both CURRVAL and NEXTVAL, Oracle increments the sequence and returns the same value for both CURRVAL and NEXTVAL regardless of their order within the statement.

INDEXES

• Be very familiar with the syntax for creating indexes. Understand composite indexes(16 columns max).

Page 26: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

25

• Understand the difference between a unique and non-unique index.

• Understand how Oracle creates and uses Binary Search Tree (B-Tree) indexes.

• Know when indexes are automatically created by Oracle.

• Indexes on small tables can sometimes slow down access.

• Indexes work best on columns with a wide range of values.

• Indexes are used in WHERE clauses.

• If field cardinality is low (not many different values i.e. y/n fields) use a BITMAP index.

• If field cardinality high (many different values i.e. ssn field) use a B-Tree (default) index.

SYNONYMS

• Used for security and convenience.

• They can mask the name and owner of an object, provide location transparency for remote objects of a distributed database, and simplify SQL statements for database users

• Can create both public and private synonyms.

• A public synonym is owned by the special user group named PUBLIC and every user in a database can access it.

• A private synonym is in the schema of a specific user who has control over its availability to others.

• Know the syntax for creating both public and private synonyms.

Controlling User Access

• Users are created, altered, and dropped by using the CREATE USER, ALTER USER, AND DROP USER commands. Be sure you know the syntax for each of these, including the CASCADE clause.

• A user is implicitly granted the privilege to alter their password at the time their user id is created.

• Users with the ALTER USER system privilege can alter any user.

• System privileges allow a user to perform a particular system wide action or perform an action on a particular type of object. Be familiar with the system privileges.

Page 27: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

26

• Object privileges allow a user to perform particular action on a specific object. Object privileges always include the name of the object. Be familiar with the object privileges.

• Be able to distinguish between a system and an object privilege.

• The DBA_SYS_PRIVS view displays all the system privileges granted to users.

• Users can see the system privileges granted to them in the USER_SYS_PRIVS view.

• In order to do anything in the Oracle database the user must have the CREATE SESSION privilege.

• The roles OSOPER and OSDBA are created at the O/S level by Oracle when the executables are installed. Know what each of these roles can do.

• OSDBA is a super set of the OSOPER role and has the WITH ADMIN OPTION.

• The privileges assigned to SYSOPER correspond to OSOPER.

• The privileges assigned to SYSDBA correspond to OSDBA.

• The CONNECT, RESOURCE, and DBA roles are automatically created by Oracle when a database is created. They are available for backwards compatibility.

• When a user is created using Server Manager, they are automatically granted the CONNECT role. The CONNECT role grants the following system privileges:

ALTER SESSION

CREATE CLUSTER

CREATE DATABASE LINK

CREATE SEQUENCE

CREATE SESSION

CREATE SYNONYM

CREATE TABLE

CREATE VIEW

• The role RESOURCE grants UNLIMITED TABLESPACE and the following system privileges:

Page 28: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

27

CREATE CLUSTER

CREATE PROCEDURE

CREATE SEQUENCE

CREATE TABLE

CREATE TRIGGER

• The DBA role includes all system privileges and EXP_FULL_DATABASE and IMP_FULL_DATABASE.

• The USER_ROLE_PRIVS view contains all the roles that have been granted to a particular user.

• INDEX and REFERENCES object privileges can only be granted to a user, not a role.

• catalog.sql creates EXP_FULL_DATABASE and IMP_FULL_DATABASE roles by calling catexp.sql.

• Object privileges will cascade on delete, but system privileges will not.

• All system privileges can be granted to a role except for the privilege UNLIMITED TABLESPACE.

• You cannot assign a privilege that includes the WITH GRANT OPTION to a role.

• The WITH GRANT OPTION is not considered to add a system privilege.

• If roles are controlled at the operating system level the Multithreaded Server Option (MTS) cannot be used.

• Specifying the CASCADE option with DISABLE or DROP allows Oracle to cascade the operation to all dependent integrity constraints.

• A table owner can grant the following object privileges to other users:

o ALTER o DELETE o INDEX o INSERT o REFERENCES o SELECT o UPDATE o EXECUTE (for stored functions, procedures, and packages)

Page 29: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

28

PL/SQL

Be very familiar with all the PL/SQL syntax and be sure you can look at some code and identify what will cause it to error.

PL/SQL Processing

• The PL/SQL engine processes PL/SQL blocks submitted from the server manager.

• The PL/SQL parses blocks into procedural statements and SQL statements.

• The PL/SQL engine passes parsed procedural statements to the procedural statement executor, which processes data local to applications.

• Parsed SQL statements are passed by the PL/SQL engine, as needed to the Oracle7 server SQL statement executor.

PL/SQL BLOCKS

There are 2 types of PL/SQL blocks: anonymous blocks and named blocks.

Anonymous blocks may have the following Keywords:

• DECLARE

o Declare variables in this section (not required)

• BEGIN

o This is the executable section (required)

• EXCEPTIONS

o This is the error handling section (not required)

• END;

• At a minimum an anonymous block must have the BEGIN and END keywords.

• An anonymous block is available in all PL/SQL environments.

• Named blocks are create using the CREATE OR REPLACE PROCEDURE command and are stored as objects in the database.

• In a named block the header, executable, and end subprogram components are required.

VARIABLES IN PL/SQL

• Local variables are scoped to the current block except when a block is named using a label. In this situation, the following PL/SQL block can reference a

Page 30: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

29

variable from the preceding block using the LABEL_NAME.VARIABLE_NAME notation.

• Aggregate variables are implicitly declared in a CURSOR FOR LOOP.

• BINARY INTEGER is better than NUMBER for defining the data-type for a counter variable because it is more efficient than NUMBER.

• A variable that has a colon ( : ) in front of it is a BIND variable. These are defined and assigned a value in SQL*PLUS and used in PL/SQL like a global variable.

• Multiple variables can not be declared in the same statement. For example: "var1, var2 VARCHAR2(10)" is an invalid expression.

Writing Executable Statements

Functions:

• All functions must specify their return variable type using the RETURN clause immediately following the CREATE OR REPLACE statement.

Function Syntax:

CREATE OR REPLACE FUNCTION function_name [ (parameters {IN|OUT| IN OUT} ) ]

RETURN return_datatype

IS | AS

<declaration statements>

BEGIN

<executable statements>

[EXCEPTION]

<exception handler statements>

END function_name ;

Note that RETURN is a clause not a keyword.

• Functions must return a single value. A procedure does not have to return anything. A procedure can return multiple values.

Page 31: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

30

Interacting with the Oracle Server

• The in parameter mode in a PL/SQL block allows the parameter to be an expression.

• A parameter passed into a PL/SQL block with the IN mode acts as a constant.

• Two advantages of using the %TYPE attribute are 1: the underlying database column datatype may be unknown. 2: the underlying database column datatype may change at runtime.

Writing Control Structures

-if-then-elsif syntax

IF condition1 THEN statements ;

ELSIF condition2...n THEN statements ;

ELSE statements ;

END IF;

Various Loop Constructs:

<<label_name>>

LOOP

<statements> - if no EXIT condition is coded into the loop PL/SQL will error out on an indefinite loop.

IF condition THEN EXIT label_name ;

END LOOP label_name ;

...

<<label_name>>

LOOP

<statements>

EXIT label_name WHEN expression;

END LOOP label_name ;

...

Page 32: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

31

WHILE expression LOOP

<statements>

END LOOP;

...

FOR index IN [REVERSE] lower_bound..higher_bound LOOP

<statements>

END LOOP;

Composite Datatypes

• A PL/SQL RECORD datatype can be declared in three ways. In all cases, referencing the record "values" is the same.

Example 1:

my_rec table_name%rowtype

...

Example 2:

TYPE my_rec IS RECORD

(f1 integer,

f2 varchar2(10),

f3 table1.field1%type);

...

Example 3:

CURSOR get_my_rec IS

SELECT f1, f2, f3

FROM table1 ;

my_rec get_my_rec%rowtype

Page 33: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

32

• Example of referencing "record members" directly using dot notation:

o IF my_rec.f1 > 10 THEN ….

• Example of passing record type variable into a procedure:

o PROCEDURE some_procedure (ME_REC) ;

• Example of assigning expression to a "record":

o my_rec.f2 := ‘Rick’;

o PL/SQL Tables:

• A PL/SQL table is an object of type table. It is a table in memory. It must have at least one field and one primary key. It can based upon column(s) taken from an existing base-table column or defined explicitly. All three examples below are valid:

o TYPE my_table IS TABLE OF some_table.some_column%type INDEX BY BINARY_INTEGER.

o TYPE my_table IS TABLE OF some_table.some_column%type NOT NULL INDEX BY BINARY_INTEGER.

o TYPE my_table IS TABLE OF varchar2(50) INDEX BY BINARY_INTEGER.

• The INDEX BY phrase is mandatory and a BINARY_INTEGER index is the fastest for retrieval.

• Use table index to reference values. Examples:

o IF my_table(12) = 99.99 THEN … o my_table(some_variable + 5) ;

Cursors

Implicit Cursors:

• An implicit cursor is automatically defined when any SQL statement is issued. It results in 2 fetches:

o Fetch1 - ID’s if more than one row will be returned

o Fetch2 - Gets the row

• An implicit cursor can only be used to process one row at a time. If more than one row is returned an implicit exception is raised.

Page 34: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

33

Implicit Cursor Variables:

• %FOUND: Before the first fetch on an opened cursor equals NULL. If the latest fetch is successful then it equals TRUE. Check only after a fetch command.

• %NOTFOUND: If the latest fetch is unsuccessful it equals TRUE. If the latest fetch is successful it equals FALSE.

• %ISOPEN: Before a cursor is opened it equals FALSE. If the cursor has been opened and is still open it equals TRUE.

• %ROWCOUNT: Before a cursor is open it equals NULL and raises an INVALID_CURSOR exception. Before first fetch after cursor is open it equals 0 (zero). After a fetch while a cursor is open it equals the last valid count of rows fetched.

• Explicit cursor definition is done in the declaration section. Remember, no SELECT INTO statement in a cursor!

Syntax:

DECLARE

CURSOR cursor_name(parm1 parm1-data-type, parm2 parm2-data-type, …) IS

SELECT * FROM EMPLOYEE;

END;

BEGIN ---

• Cursor For Loop: implicitly handles opening, parsing, executing, fetching, check for more rows, loop exit. A cursor for loop implicitly declares the record variable.

Example:

DECLARE

CURSOR employee_crsr(low_end VARCHAR2, high_end VARCHAR2) IS

SELECT empid, salary

FROM employee

WHERE substr(lastname,1,1) BETWEEN UPPER(low_end) AND UPPER(high_end);

Page 35: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

34

...

BEGIN

FOR my_emprec IN employee_crsr(‘A’,’M’) LOOP

<statements>

END LOOP;

Exceptions

• There are 3 types of PL/SQL exceptions 1) user defined 2) system or pre-defined 3) pragma

• A user defined exception that is associated with an Oracle error (PRAGMA EXCEPTION_INIT) is raised implicitly when the condition occurs.

Exception block Syntax:

EXCEPTION

WHEN error-condition THEN <statements> ;

WHEN OTHERS THEN <statements> ;

END;

• Exception declaration syntax:

o exception_name EXCEPTION; - declare exception phrase

PRAGMA EXCEPTION_INIT (exception_name , error_code ); - This statement is only used to associate a user-defined exception with an existing Oracle error-code (e.g. ORA-14104).

Page 36: < a«T¾ð£[× íöPJÓ·]/ $êTR*2î Kþl[ »È¸ñ ¬x½a yÅø - [ðQ´ Êç ... · Cramsession for Oracle 8.0 SQL-PL/SQL. This study guide will help you to prepare for the Oracle

Cramsession: Oracle 8.0 SQL-PL/SQL

TM

© 2000 All Rights Reserved – BrainBuzz.com

35

• SQLCODE() and SQLERRM() functions can be used to capture the error-code and the associated error messages in the WHEN OTHERS exception handler.

NEW TO PL/SQL 8.0

External Procedures - The ability to call external procedures from within PL/SQL.

Object Types - The incorporation of object oriented programming within PL/SQL.

Collections - New types of object collections that can be used like arrays or be made part of an object.

LOB Types - New package DBMS_LOB allows PL/SQL to operate on large objects.

Special thanks to

Rick Sands

and Joe Seeley

for contributing this Cramsession.