Source: Wikipedia: PL/SQL


From Wikipedia, the free encyclopedia
Jump to: navigation, search

PL/SQL (Procedural Language/Structured Query Language) is Oracle Corporation's procedural extension language for SQL and the Oracle relational database. PL/SQL's general syntax resembles that of Ada.

PL/SQL is one of three key programming languages embedded in the Oracle Database, along with SQL itself and Java.

PL/SQL is available in Oracle Database (since version 7), TimesTen in-memory database (since version 11.2.1), IBM DB2 (since version 9.7)[1].

* 1 Introduction
* 2 PL/SQL program units
o 2.1 Anonymous Blocks
o 2.2 Functions
o 2.3 Procedures
o 2.4 Packages
* 3 Variables
o 3.1 Numeric variables
o 3.2 Character variables
o 3.3 Date variables
o 3.4 Datatypes for specific columns
* 4 Conditional Statements
* 5 Array handling
* 6 Looping
o 6.1 LOOP statements
o 6.2 FOR loops
o 6.3 Cursor FOR loops
o 6.4 Example
* 7 Similar languages
* 8 See also
* 9 References
* 10 External links

[edit] Introduction

PL/SQL supports variables, conditions, loops and exceptions. Arrays are also supported, though in a somewhat unusual way, involving the use of PL/SQL collections. PL/SQL collections are a slightly advanced topic.

Implementations from version 8 of Oracle Database onwards have included features associated with object-orientation.

PL/SQL program units (essentially code containers) can be compiled into the Oracle database. Programmers can thus embed PL/SQL units of functionality into the database directly. They also can write scripts containing PL/SQL program units that can be read into the database using the Oracle SQL*Plus tool.

Once the program units have been stored into the database, they become available for execution at a later time.

While programmers can readily embed Data Manipulation Language (DML) statements directly into their PL/SQL code using straight forward SQL statements, Data Definition Language (DDL) requires more complex "Dynamic SQL" statements to be written in the PL/SQL code. However, DML statements underpin the majority of PL/SQL code in typical software applications.

In the case of PL/SQL dynamic SQL, early versions of the Oracle Database required the use of a complicated Oracle DBMS_SQL package library. More recent versions have however introduced a simpler "Native Dynamic SQL", along with an associated EXECUTE IMMEDIATE syntax.

Oracle Corporation customarily extends package functionality with each successive release of the Oracle Database.
[edit] PL/SQL program units
[edit] Anonymous Blocks

Anonymous blocks form the basis of the simplest PL/SQL code, and have the following structure:

TYPE / item / FUNCTION / PROCEDURE declarations
EXCEPTION handlers
END label;

The «label» and the DECLARE and EXCEPTION sections are optional.

Exceptions, errors which arise during the execution of the code, have one of two types:

1. Predefined exceptions
2. User-defined exceptions.

User-defined exceptions are always raised explicitly by the programmers, using the RAISE or RAISE_APPLICATION_ERROR commands, in any situation where they have determined that it is impossible for normal execution to continue. RAISE command has the syntax:

RAISE <exception name>;

Oracle Corporation has pre-defined several exceptions like NO_DATA_FOUND, TOO_MANY_ROWS, etc. Each exception has a SQL Error Number and SQL Error Message associated with it. Programmers can access these by using the SQLCODE and SQLERRM functions.

The DECLARE section defines and (optionally) initialises variables. If not initialised specifically, they default to NULL.

For example:

number1 NUMBER(2);
number2 NUMBER(2) := 17; — value default
text1 VARCHAR2(12) := 'Hello world';
text2 DATE := SYSDATE; — current date and time
SELECT street_number
INTO number1
FROM address
WHERE name = 'INU';

The symbol := functions as an assignment operator to store a value in a variable.

The major datatypes in PL/SQL include NUMBER, INTEGER, CHAR, VARCHAR2, DATE, TIMESTAMP, TEXT etc.
[edit] Functions

Functions in PL/SQL are a collection of SQL and PL/SQL statements that perform a task and should return a value to the calling environment. User defined functions are used to supplement the many hundreds of functions built in by Oracle.

There are two different types of functions in PL/SQL. The traditional function is written in the form:

CREATE OR REPLACE FUNCTION <function_name> [(input/output variable declarations)] RETURN return_type
[declaration block]
<PL/SQL block WITH RETURN statement>
RETURN <return_value>;
RETURN <return_value>;

Pipelined Table Functions are written in the form:

CREATE OR REPLACE FUNCTION <function_name> [(input/output variable declarations)] RETURN return_type
[declaration block]
<PL/SQL block WITH RETURN statement>
PIPE ROW <return type>;
PIPE ROW <return type>;

There are three types of parameter: IN, OUT and IN OUT. An IN parameter is used as input only. An IN parameter is passed by reference and thus cannot be changed by the called program. An OUT parameter is initially NULL. The program assigns the parameter a value and that value is returned to the calling program. An IN OUT parameter may or may not have an initial value. That initial value may or may not be modified by the called program. Any changes made to the parameter are returned to the calling program by default by copying but, with the NOCOPY hint may be passed by reference.
[edit] Procedures

Procedures are similar to Functions, in that they can be executed to perform work. The primary difference is that procedures cannot be used in a SQL statement and although they can have multiple out parameters they do not "RETURN" a value.

Procedures are traditionally the workhorse of the coding world and functions are traditionally the smaller, more specific pieces of code. PL/SQL maintains many of the distinctions between functions and procedures found in many general-purpose programming languages, but in addition, functions can be called from SQL, while procedures cannot.
[edit] Packages

Packages are groups of conceptually linked Functions, Procedures,Variable,PL/SQL table and record TYPE statements,Constants & Cursors etc. The use of packages promotes re-use of code. Packages usually have two parts, a specification and a body, although sometimes the body is unnecessary. The specification (spec for short) is the interface to your applications; it declares the types, variables, constants, exceptions, cursors, and subprograms available for use. The body fully defines cursors and subprograms, and so implements the spec. They are stored permanently in USER_SOURCE system table. Two advantages of packages include:

1. Modular approach, Encapsulation/hiding of business logic, security, performance improvement, re-usability.They support OOPS features like function over loading,encapsulation.
2. Using package variables we can declare session level (scoped) variables, since variables declared in the package specification have session scope.

[edit] Variables
[edit] Numeric variables

variable_name NUMBER(P[,S]) := VALUE;

To define a numeric variable, the programmer appends the variable type NUMBER to the name definition. To specify the (optional) precision(P) and the (optional) scale (S), one can further append these in round brackets, separated by a comma. ("Precision" in this context refers to the number of digits which the variable can hold, "scale" refers to the number of digits which can follow the decimal point.)

A selection of other datatypes for numeric variables would include: binary_float, binary_double, dec, decimal, double precision, float, integer, int, numeric, real, smallint, binary_integer
[edit] Character variables

variable_name VARCHAR2(L) := 'Text';

To define a character variable, the programmer normally appends the variable type VARCHAR2 to the name definition. There follows in brackets the maximum number of characters which the variable can store.

Other datatypes for character variables include: varchar, char, long, raw, long raw, nchar, nchar2, clob, blob, bfile
[edit] Date variables

variable_name DATE := '01-Jan-2005';

Oracle provides a number of data types that can store dates (DATE, DATETIME, TIMESTAMP etc.), however DATE is most commonly used.

Programmers define date variables by appending the datatype code "DATE" to a variable name. The TO_DATE function can be used to convert strings to date values. The function converts the first quoted string into a date, using as a definition the second quoted string, for example:



TO_DATE ('31-Dec-2004','dd-mon-yyyy', 'NLS_DATE_LANGUAGE = American')

To convert the dates to strings one uses the function TO_CHAR (date_string, format_string).

PL/SQL also supports the use of ANSI date and interval literals.[2] The following clause gives an 18-month range:

WHERE dateField BETWEEN DATE '2004-12-31' - INTERVAL '1-6' YEAR TO MONTH
AND DATE '2004-12-31'

[edit] Datatypes for specific columns

Variable_name Table_name.Column_name%type;

This syntax defines a variable of the type of the referenced column on the referenced tables.

Programmers specify user-defined datatypes with the syntax:

type data_type is record (field_1 type_1 :=xyz, field_2 type_2 :=xyz, …, field_n type_n :=xyz);

For example:

TYPE t_address IS RECORD (
street address.street%TYPE,
street_number address.street_number%TYPE,
postcode address.postcode%TYPE);
v_address t_address;
SELECT name, street, street_number, postcode INTO v_address FROM address WHERE ROWNUM = 1;

This sample program defines its own datatype, called t_address, which contains the fields name, street, street_number and postcode.

So according to the example, we are able to copy the data from the database to the fields in the program.

Using this datatype the programmer has defined a variable called v_address and loaded it with data from the ADDRESS table.

Programmers can address individual attributes in such a structure by means of the dot-notation, thus: "v_address.street := 'High Street';"
[edit] Conditional Statements

The following code segment shows the IF-THEN-ELSIF construct. The ELSIF and ELSE parts are optional so it is possible to create simpler IF-THEN or, IF-THEN-ELSE constructs.

IF x = 1 THEN

The CASE statement simplifies some large IF-THEN-ELSE structures.

WHEN x = 1 THEN sequence_of_statements_1;
WHEN x = 2 THEN sequence_of_statements_2;
WHEN x = 3 THEN sequence_of_statements_3;
WHEN x = 4 THEN sequence_of_statements_4;
WHEN x = 5 THEN sequence_of_statements_5;
ELSE sequence_of_statements_N;

CASE statement can be used with predefined selector:

WHEN 1 THEN sequence_of_statements_1;
WHEN 2 THEN sequence_of_statements_2;
WHEN 3 THEN sequence_of_statements_3;
WHEN 4 THEN sequence_of_statements_4;
WHEN 5 THEN sequence_of_statements_5;
ELSE sequence_of_statements_N;

[edit] Array handling

PL/SQL refers to arrays as "collections". The language offers three types of collections:

1. Index-by tables (associative arrays)
2. Nested tables
3. Varrays (variable-size arrays)

Programmers must specify an upper limit for varrays, but need not for index-by tables or for nested tables. The language includes several collection methods used to manipulate collection elements: for example FIRST, LAST, NEXT, PRIOR, EXTEND, TRIM, DELETE, etc. Index-by tables can be used to simulate associative arrays, as in this example of a memo function for Ackermann's function in PL/SQL.
[edit] Looping

As a procedural language by definition, PL/SQL provides several iteration constructs, including basic LOOP statements, WHILE loops, FOR loops, and Cursor FOR loops.
[edit] LOOP statements



EXIT parent_loop WHEN <condition>; — Terminates both loops
EXIT WHEN <condition>; — Returns control to parent_loop

EXIT WHEN <condition>;
END LOOP parent_loop;

Loops can be terminated by using the EXIT keyword, or by raising an exception.
[edit] FOR loops
[edit] Cursor FOR loops

FOR RecordIndex IN (SELECT person_code FROM people_table)

Cursor-for loops automatically open a cursor, read in their data and close the cursor again

As an alternative, the PL/SQL programmer can pre-define the cursor's SELECT-statement in advance in order (for example) to allow re-use or to make the code more understandable (especially useful in the case of long or complex queries).

CURSOR cursor_person IS
SELECT person_code FROM people_table;
FOR RecordIndex IN cursor_person

The concept of the person_code within the FOR-loop gets expressed with dot-notation ("."):


[edit] Example

/*N.B. for loop variables in pl/sql are new declarations, with scope only inside the loop */
FOR var IN 0 .. 10 LOOP

DBMS_OUTPUT.put_line('var is null');
DBMS_OUTPUT.put_line('var is not null');


var is null

[edit] Similar languages

PL/SQL functions analogously to the embedded procedural languages associated with other relational databases. Sybase ASE and Microsoft SQL Server have Transact-SQL, PostgreSQL has PL/pgSQL (which tries to emulate PL/SQL to an extent), and IBM DB2 includes SQL Procedural Language,[3] which conforms to the ISO SQL’s SQL/PSM standard.

The designers of PL/SQL modelled its syntax on that of Ada. Both Ada and PL/SQL have Pascal as a common ancestor, and so PL/SQL also resembles Pascal in numerous aspects. The structure of a PL/SQL package closely resembles the basic Pascal program structure or a Borland Delphi unit. Programmers can define global data-types, constants and static variables, public and private, in a PL/SQL package.

PL/SQL also allows for the definition of classes and instantiating these as objects in PL/SQL code. This resembles usages in object-oriented programming languages like Object Pascal, C++ and Java. PL/SQL refers to a class as an "Abstract Data Type" (ADT) or "User Defined Type" (UDT), and defines it as an Oracle SQL data-type as opposed to a PL/SQL user-defined type, allowing its use in both the Oracle SQL Engine and the Oracle PL/SQL engine. The constructor and methods of an Abstract Data Type are written in PL/SQL. The resulting Abstract Data Type can operate as an object class in PL/SQL. Such objects can also persist as column values in Oracle database tables.

PL/SQL is fundamentally distinct from Transact-SQL, despite superficial similarities. Porting code from one to the other usually involves non-trivial work, not only due to the differences in the feature sets of the two languages, but also due to the very significant differences in the way Oracle and SQL Server deal with concurrency and locking.

The Fyracle project aims to enable the execution of PL/SQL code in the open-source Firebird database.

The StepSqlite product is a PL/SQL compiler for the popular small database SQLite.
[edit] See also

* Relational database management systems

[edit] References

1. ^
2. ^ "Literals". Oracle Database SQL Reference 10g Release 2 (10.2). Oracle. Retrieved 2009-03-20.
3. ^ SQL PL

Text document with red question mark.svg
This article includes a list of references, related reading or external links, but its sources remain unclear because it lacks inline citations. Please improve this article by introducing more precise citations where appropriate. (February 2008)
Question book-new.svg
This article needs additional citations for verification.
Please help improve this article by adding reliable references. Unsourced material may be challenged and removed. (January 2008)
The Wikibook Oracle_Programming has a page on the topic of

* Feuerstein, Steven; with Bill Pribyl (2005). Oracle PL/SQL Programming (4th ed. ed.). O'Reilly & Associates. ISBN 0-596-00977-1.
* Naudé, Frank (June 9, 2005). "Oracle PL/SQL FAQ rev 2.08".

[edit] External links

* Oracle FAQ: PL/SQL
* Oracle Technology Center
* Oracle Tahiti Search Engine
* Morgan's Library

Retrieved from ""
Categories: Oracle software | SQL | Ada programming language family | Data-centric programming languages
Hidden categories: Articles lacking in-text citations from February 2008 | All articles lacking in-text citations | Articles needing additional references from January 2008 | All articles needing additional references
Personal tools

* New features
* Log in / create account


* Article
* Discussion



* Read
* Edit
* View history



* Main page
* Contents
* Featured content
* Current events
* Random article


* About Wikipedia
* Community portal
* Recent changes
* Contact Wikipedia
* Donate to Wikipedia
* Help


* What links here
* Related changes
* Upload file
* Special pages
* Permanent link
* Cite this page


* Create a book
* Download as PDF
* Printable version


* Català
* Česky
* Deutsch
* Español
* Français
* 한국어
* Italiano
* עברית
* Magyar
* Nederlands
* 日本語
* Polski
* Português
* Română
* Русский
* Slovenčina
* Svenska
* ไทย
* Тоҷикӣ
* Türkçe
* Українська
* 中文

* This page was last modified on 9 September 2010 at 06:08.
* Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. See Terms of Use for details.
Wikipedia® is a registered trademark of the Wikimedia Foundation, Inc., a non-profit organization.
* Contact us

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License