PL/SQL Introduction

Source: Internet
Author: User

What is a PL/SQL program?

The standard SQL language learned in the previous chapter 4th performs various operations on the database. Only one statement can be executed at a time. The statement uses the semicolon (;) as the end mark, which is inconvenient to use, at the same time, the efficiency is low, because the Oracle database system is not similar to programming languages such as VB and Vc, it focuses on the management of background databases, so it provides weak programming capabilities, structured Programming Languages have weak support for databases. If some management tasks with a little complexity need to be implemented using programming languages, this is a great burden for administrators.
Driven by this demand, Oracle 6 has developed its own PL/SQL (Procedural Language/SQL, procedural SQL language) language based on the standard SQL language, introduce the elements of variable, control structure, process, and function into the SQL language, so that you can compile complicated SQL programs, programs Written in PL/SQL are also called PL/SQL blocks.
The main features of PL/SQL block are as follows.
It has a modular structure.
Use a procedural language control structure.
Can handle errors.

1. What is PL/SQL?

PL/SQL (Procedural Language/SQL) is an extension of SQL, which absorbs many of the highest design features of programming languages in recent years: such as data encapsulation, information concealment, heavy load, and exception handling. It allows SQL data manipulation language and query statement to be included in Block Structure (block_structured) and Code process language, making PL/SQL a powerful transaction processing language.

PL/SQL has the following advantages:

1. Block Structure)

PL/SQL is a block structure language, which means that a program can be divided into several logical blocks, each containing the required logical language resources in that unit. You can declare local variables to the block and use these variables in the block to specially handle error conditions (called exceptions) in the block where they are applied)

2. Process Control

Conditional statements, loops, and branches can be used to control the process flow of a program to Determine whether or when to execute SQL statements or other actions. These features allow oracle tools (such as SQL * forms) to group together command groups and control their execution through PL/SQL. This avoids the need to set many commands as separate trigger steps or nested SQL statements in external programming languages.

3. Portability

Since PL/SQL is the main language of Oracle, the program can be transplanted to any operating system platform that supports Oracle and PL/SQL.

4. Integration

PL/SQL plays an increasing central role in RDBMS (stored procedures, triggers, packages) and oracle tools. PL/SQL variables and types are compatible with SQL variables and types (compatible with those used in database columns ). Therefore, PL/SQL is a convenient bridge between database technology and process programming capabilities.

5. Improved performance

PL/SQL can help improve application performance. In the absence of PL/SQL, Oracle only processes one SQL statement at a time, while in the absence of PL/SQL, a complete statement block is sent to Oracle at a time, communication and calling with Oracle can be significantly reduced. Benefits are improved. The difference in benefits depends on the environment in which PL/SQL is used. These benefits will be discussed later

Ii. PL/SQL Structure

Each PL/SQL unit consists of one or more blocks. These blocks can be completely independent, or one block is nested in another block. In this way, a block can represent a small part of other blocks. In turn, it is just a part of the whole program code unit.

Generally, a block can be an unknown block or a sub-program.

1. Anonymous block (anonymous)

An unnamed block is a block without a name. These blocks are described in the application that runs them, and are passed by the PL/SQL engine during execution. Untitled blocks can be embedded into pre-compiled programs (or OCI programs) and SQL * Plus or SQL * DBA. The triggers in SQL * forms are also composed of these blocks, which are used more.

The definition of an unknown block is as follows:

Declare

-- Description

Begin

-- Statement Sequence

[Exception

-- Exception handler]

End;

A pl/SQL block consists of three parts: Description, executable, and Exception Processing.

PL/SQL objects such as variables and constants can be referenced in blocks or nested sub-blocks in the description section. The description section is optional. In the execution part, you can use SQL DML statements, transaction control statements, and control structures such as condition control, iteration control, and sequence control, this is the most important extension of PL/SQL for SQL. In PL/SQL programs, you can easily find and process predefined or user-defined error conditions (warning or error conditions) that are called exceptions. When an error occurs, it will cause (RAISE) with one exception, normal execution is stopped and control is transferred to the exception handling program. The exception handler is optional.

Example 2.47: PL/SQL untitled Block Structure

Declare

Qty_on_hand number (5 );

Begin

Select Quantity into qty_on_hand from inventory

Where product = 'tennis racket ';

If qty_on_hand> 0 then

Update inventory set quantity = quantity-l

Where product = 'tennis racket ';

Insert into purchase_record

Values ('out of tennis rackets ', sysdate );

Endif;

Commit;

Exception

When no_data_found then

Insert tnto error_table

Values ('product tennis racket not found ')

End;

Note that keys declare, begin, and exception are not followed by semicolons, but end and all other PL/SQL statements require semicolons.

The preceding example illustrates a PL/SQL variable 'qtyon _ Hand' and then uses a SELECT statement. If the value of this variable is positive, modify the 'inventory 'table. If the SELECT statement fails to be searched, the exception "no-Data found" is triggered. The control is immediately transferred to the exception section and the problem is recorded in a table.

2. Subprogram)

A subroutine is a named PL/SQL block. It can be divided into two types: Process (procedures) and function (functions. When the latter is called, return returns a value. Therefore, you can use a process to execute an action and use a function to calculate a value.

SQL * FORMS allows the process and function to be described as part of form and can be called from other vertices of forms.

(1) Process

A process is a subroutine that executes a specific action. It is a named PL/SQL block. The process consists of two parts: process description and process body. The process structure is as follows:

Procedure process name (parameter)

-- Description

Begin

-- Statement Sequence

[Exception

-- Exception handler]

End [process name];

The parameter format is:

Parameter Name in type name

Out: = value.

In out

Process description specifies the process name or parameter table. parameter description is the option. A process consists of three parts: declarative, executable, and optional exception handling. Declarations include descriptions of types, cursors, constants, variables, exceptions, and subprograms. These objects are local and no longer exist when exiting the process. The executable part consists of a value assignment statement, a control statement, and an ORACLE data manipulation statement. The exception handling part includes the exception handling program.

The parameter method (In, out, inout) defines the behavior of the formal parameter. The in parameter can transmit the value to the called subroutine. The out parameter returns the value to the caller of the subroutine. The inout parameter can transmit the initial value to the called subroutine and return the modified value to the caller. In a process, the in parameter acts as a constant and cannot be assigned a value. The in out parameter acts as an initialized variable and can be assigned a value, its value can be assigned to other variables. The out parameter acts as an uninitialized variable. Its value cannot be assigned to other variables or re-assigned to itself. Before exiting the process, you must explicitly assign the value to all out parameters. The in parameter can be initialized as the default value.

Example of the 2.48: Out parameter:

Procedure reconcile (acctno out integer) is

Begin

...

End reconcile;

Example 2.49: process of increasing employees' salaries:

Procedure raise_salary (emp_id integer, increase real) is

Current_salary real;

Salary_missing exception;

Begin

Select Sal into current_salary from EMP

Where epno = emp_id;

If schement_salary is null then

Raise salary_missing;

Else

Update EMP set sal = Sal + increase

Where empno = emp_id;

Endif;

Exception

When no_data_found then

Insert into emp_audit values (emp_id, 'no such number ');

When salary_missing then

Insert into emp_audit values (emp_id, 'salary is null ');

End raise_salary;

When this process is called, an employee number and a salary increase are received in this process. Use this employee number to select the current salary in the EMP table. If the EMP does not have this employee ID or the current salary is null, an exception occurs. Otherwise, change the salary.

The procedure call is a-PL/SQL statement. For the above example, the form of the call statement is:

Raise_salary (1002,600)

It can also be:

Raise_salary (increase => 600, emp_id => 1002)

(2) Functions

A function is a named Program unit. It can contain parameters and return a calculated value. The structure of a function and a process is the same, except that a function has a return clause. The function structure is as follows:

Function Name (variable)

Return type name is

-- Description

Begin

-- Statement Sequence

[Exception

-- Exception handler]

End [function name];

The variable format is:

Variable name in type name

Out: = value.

In out

Description: keywords and parameters in a function have the same meaning. The return clause is used to specify the Data Type of the result value.

Example 2.50: function used to determine whether a worker's salary is out of the range:

Function sal_ OK (salary real, title char)

Return booean is

Max_sal real;

Min_sal real;

Begin

Select losal, hisal into min_sal, amx_sal

From SALS where job = title;

Return (salary> = min_sal) and (salary <= max_sal );

End sal_ OK;

When this function is called, it receives the salary and name of a worker. It uses the work name to find the range restriction in the sals table. The sal_ OK Function Identifier is set to a Boolean value by the Return Statement, if the salary is out of the range of false, otherwise it is true.

A function call can be an expression component.

Example 2.51:

If sal_ OK (new_sal, new_title) then

...

End if;

...

Promotable: = sal_ OK (new_sal, new_title) and (rating> 3 );

Note: Calling user-defined functions can be used in procedural statements, so they cannot be used in SQL statements.

Use the return statement in a function. The function is to immediately execute the subprogram and return the control to the caller. Then it is executed immediately from the caller Program Calling the subroutine. A sub-program can contain multiple return clauses. For a process, a return statement cannot contain an expression. For a function, a return statement must contain an expression that is any complex expression and is calculated when a return statement is executed, this value is assigned to the Function Identifier.

3. Package)

(1) Significance of packages

In order to meet the modular needs of the program, PL/SQL introduces the construction of packages in addition to the block and subroutine structures.

A package is a database object that combines logical PL/SQL types, objects, and subprograms into a larger unit. The package consists of the specification and body ). Description is an application interface that declares the type, constant, exception, cursor, and available subroutines. Body defines the cursor and subroutine, implementation instructions. The application is visible and accessible only to the declarations in the package description. If Oracle has the procedure option, packages can be compiled and stored in Oracle databases, and the content can be shared by many applications. When a user calls a packaged subroutine for the first time, the entire package is packaged into the memory. Therefore, I/O operations are no longer required for future calls to the package neutron program, so the package can improve efficiency and performance.

PL/SQL packages have information hiding, which is only visible at the relevant layers of algorithm and data structure design. In the process described above, you can combine the process description and the process body into a program unit. You can also separate the process description from its process body. In this case, you can place the process in a package to conceal the implementation details. You can also define the process in the package. The process does not define the process description in the package description. This process is only used in the package.

(2) package Definition

The package is defined as follows:

Package Description:

Package package name is

-- Variable description;

-- Cursor description;

-- Exception description;

-- Record description;

-- PLSQL table description;

-- Process description;

-- Function description;

End [package name];

Package body:

Package body package name is

-- Variable name description;

-- Cursor description;

-- Cursor Declaration;

-- Exception description;

-- Record description;

-- PLSQL description;

-- Process body;

-- Function body;

Begin

-- Statement Sequence

End [package name];

The package name is the identifier of the named package.

Packages cannot be embedded in PL/SQL blocks or subprograms, but can be defined using any tool that supports PL/SQL. To use the package for all purposes, you must use the CREATE command to create and store the package in an Oracle database. You can use the create package and create package body statements in SQL * Plus, SQL * dBA, or the Oracle pre-compiled Host Program.

Example 2.52: Create a package:

. Package Description Creation

Create package emp_actions

Type emprectyp is record (emp_id integer, salary real );

Cursor desc_salary (emp_id number) return emprectyp;

Procedure hire_employee

(Ename char,

Job char,

Sal number,

Mgr number,

Comm number,

Deptno number;

Procedure fire_employee (emp_id number );

End emp_actions;

(A): The statement type emprectyp is record (emp_id. integer, salary real) indicates that the user-defined emprectyp is a record object. User-Defined records

The general format is:

Typy type name is record

(Field name 1 {field type | variable name % type | table name. Column name % type | table name % rowtype} [not null],

Field name 2 {field type | variable name % type | table name. column name % type | table name % rowtype} [not null],...); the type name is a type description, which can be used in the record description. Field

Any data types allowed by PL/SQL, including record and table. The % type or % rowtype attribute can be used to specify the Data Type of a field.

The % Type attribute can be used to provide the data types of variables, constants, or database columns. For example, if the variable my_dname is of the same type as the dname column in Scott's dept table, you can define it as follows:

The my_dname Scott. Dept. danme % type, % rowtype attribute provides a record type, which indicates a row in a table (or view. Records can store a whole row selected by the table or

The entire row obtained by a cursor. For example:

Declare

Emp_rec EMP % rowtype;

Cursor C1 is select deptno, dname, LOC from Dept;

Dept_rec C1 % rowtype;

The emp_rec record can store the rows selected from the table EMP, And the dept_rec record can store the rows obtained by the C1 cursor. Fields defined in this way have the same name and data type as columns in the row. Fields in the record can be referenced in the following format:

Record Name. Field name

Emp_rec.ename: = 'johnson ';

Original article: http://edu.yesky.com/edupxpt/114/2176614.shtml

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.