22
Introduction PL/SQL PL/SQL Advantages PL/SQL Block Structure PL/SQL Data Types PL/SQL Variables PL/SQL Constants PL/SQL Server Output PL/SQL Comments Basic PL/SQL PL/SQL Condition Control PL/SQL Looping Control PL/SQL Sequnce Control PL/SQL Case Statements PL/SQL Cursors Implicit Cursors Explicit Cursors For Loop Cursors Parameterized Cursors PL/SQL Transaction PL/SQL Exception Built-in Exception User-Defined Exception User-Named Exceptions Advance PL/SQL PL/SQL Functions Functions Syntax Functions Drop Functions Examples PL/SQL Procedures

Pl./sql

Embed Size (px)

DESCRIPTION

N/A

Citation preview

Page 1: Pl./sql

Introduction PL/SQL PL/SQL Advantages PL/SQL Block Structure PL/SQL Data Types PL/SQL Variables PL/SQL Constants PL/SQL Server Output PL/SQL Comments

Basic PL/SQL PL/SQL Condition Control PL/SQL Looping Control PL/SQL Sequnce Control PL/SQL Case Statements PL/SQL Cursors

Implicit CursorsExplicit CursorsFor Loop Cursors Parameterized Cursors

PL/SQL Transaction PL/SQL Exception

Built-in ExceptionUser-Defined ExceptionUser-Named Exceptions

Advance PL/SQL PL/SQL Functions

Functions SyntaxFunctions DropFunctions Examples

PL/SQL Procedures

Procedures SyntaxProcedures DropProcedures Examples

Page 2: Pl./sql

PL/SQL Packages

Packages AdvantagesPackages SyntaxPackages ExamplesPackages Alter

PL/SQL Triggers

Triggers How to WorkTriggers TypeTriggers SyntaxTriggers Examples

Page 3: Pl./sql

Introduction PL/SQL

What is PL/SQL?PL/SQL is a product of the Oracle.PL/SQL stands by "Programming Language" extension of SQL.PL/SQL is Specially Designed for Database Oriented Activities.

PL/SQL is Very Usefully Language and Tools of Oracle to Manipulate, Control, Validate, and Restricted the Unauthorized Access of Data From the Database.PL/SQL can improve the Performance of an Application and It is dealing with Error and return User Friendly Error Message.We can easily show Multiple Records of the Multiple Table on s the Same Time.PL/SQL Sends an entire Block of Statements execute to the oracle engine at One Time.

Advantages PL/SQL

Procedural Language Supported: PL/SQL is a development tools that not only supported data Manipulation but also Provide the Condition, Checking, Looping or Branching Operation.

Reduces Network Traffic: PL/SQL is same entire block of SQL statement execute to the oracle engine at all at once so it's benefit to reduce the Network Traffic.

Error Handling: PL/SQL also permit during with Error Handling as required facility to Display User Friendly Error Message where error are encounter.

Declare Variable: PL/SQL allow to declaration and use of variable in a block of code which variable will use to store intermediate result of query for later processing.

Intermediate Calculation: PL/SQL calculations done quickly and efficient without the use of oracle engines and improve the transaction.

Portable Application: Application are written in PL/SQL is portable in any computer or hardware for any system means Application independence to run any computer.

Page 4: Pl./sql

PL/SQL Block Structure

PL/SQL Block Structure divide by four parts but two parts BEGIN and END part are compulsory, other two part DECLARE and EXCEPTION is optional part.

Figure - Structure of PL/SQL block

DECLARE: Variable and constants are declared within this section and we may initialize them with value.

BEGIN: It contains the PL/SQL statements which implement the actual programming logic. This section contains conditional statements (IF..ELSE), looping statements (FOR, WHILE) and Branching Statements (GOTO) etc.

EXCEPTION: Exception block handling the error and show the user friendly message. Error can arise due to syntax, logical or validation rules.

Note:

1. BEGIN and END; are compulsory sections of any PL/SQL program.2. DECLARE and EXCEPTION are optional sections.

Page 5: Pl./sql

PL/SQL Data Types

PL/SQL support following SQL basic data type like CHAR, VARCHAR2, LONG, NUMBER, NUMBER(p,s), and DATE.

PL/SQL support Basic Data Types:

Data Type Description Storage(Maximum)

CHAR(size)

This data type is use to store character strings value of fixed length.It can contain letters, numbers, and special characters.

255 Character

VARCHAR(size)/ VARCHAR2(size)

This data type is use to store variable length alphanumeric data.It is more flexible form if the CHAR data type. It can contain letters, numbers, and special characters.

4000 Character

Date()This data type is use to represent data and time.Standard format is DD-MON-YY.

-

Number(P,S)

This data type is use to store number (fixed or floating point).P means Precision, Maximum length of digit.S means Scale, number of decimal places by default 0.

38 Digit Precision

LONGThis data type is use to store variable length character string contain up to 2GB.

2GB

RAWThis data type is use to store Binary data such as Digitized, Picture or Image.

255 Bytes

LONG RAWThis data type is use to store Binary data such as Digitized, Picture or Image.

2GB

PL/SQL can support the special Data Types like CLOB, BLOB, BFile, %Type, %RowType and RowID all are describe here.

Page 6: Pl./sql

PL/SQL support Advance Data Types:

Data Type Description Storage(Maximum)

BLOBThis data type is use to store Binary character like songs, video, image, constructured data type and hold the upto 4 GB.

4 GB

CLOBThis data type is use to store Character variable and hold the up to 4 GB.

4 GB

BFileThis data type is use to store value in Pointer variable. type of pointer, reference of external file.

4 GB

%Type

This data type is use to store value unknown data type column in a table. column is identified by %type data type.Eg. emp.eno%typeemp name is table,eno is a unknown data type column and%Type is data type to hold the value.

%RowType

This data type is use to store value unknown data type all column in a table. All column is identified by %RowType datatype.Eg. emp%rowtypeemp name is table,all column type is %rowtype.

%RowID RowID is Data Type. RowID is Two Type Extended or Restricted.Extended return 0 and Restricted return 1 otherwise return the row number.Function of Row ID:

Function RowID Description

ROWID_Verify Verify if the rowid can be extended.

ROWID_Type 0 = rowid, 1 = extended.

Page 7: Pl./sql

ROWID_Block_NumberBlock number that contain the record return 1 extended.

ROWID_ObjectObject Number of the object that contain record.

ROWID_Relative_FNumberRelative File Number that contain record.

ROWID_Row_Number Row Number of the Record.

ROWID_To_Absolute_FNumber Return the Absolute file number.

ROWID_To_Extended Convert the Extended format.

ROWID_To_Restricted Convert the Restricted format.

PL/SQL Variables Declaration and Variables Scope

PL/SQL Variable Declaration is use to store value into declared value.

Declare Variable Syntax

The General Syntax to declare a variable is:

Variable_Name DataType[Size] [NOT NULL] := [ Value ];

Variable_Name is the predefined name of the variable. DataType is a valid PL/SQL datatype. Size is an optional specification of datatype size to hold maximum size value. NOT NULL is an optional specification on the variable. Value is also an Optional Specification, where you can Initialize or later initialize a

variable. Each variable declaration is terminated by a semicolon.

Page 8: Pl./sql

PL/SQL Placeholders

Placeholders means value store temporary in storage area. Placeholders can be any of Variables, Constants. Oracle defines placeholders to store data temporarily, which are used to manipulate data during the execution of a PL SQL block.

Number(p,s), Number(n), Char, Varchar2, Date, Long, Raw, Blob, Clob, Bfile datatypes used to define placeholders.

Variable Declaration Example

1. Store the employee No is NOT NULL(compulsory) and employee Name using the Variable.

Exmple Code:

DECLAREeno number(5) NOT NULL := 2// NOT NULL means value initialize as same time declaration.ename varchar2(15) := Jay Patel;// value is initialize as now and later initialize

BEGINdbms_output.put_line('Declared Value:');dbms_output.put_line(' Eno: ' || eno || ' EName: ' || ename);

END;/

Backward slash '/' is indicates to execute the above PL/SQL Block Program.

Example Result:

Declared Value:Eno: 2 Ename: Jay Patel

Variables Scope

Local variables - Declared in a Inner block and cannot be referenced by outside Blocks. Global variables - Declared in a outer block and can be referenced by itself and by its

inner blocks.

Variable Scope Example

First we declare the two variable ('num1' and 'num2') in Global variable and third variable declare (num_addition) in local variable. variable 'num_addition' is declared in the inner block,

Page 9: Pl./sql

so cannot be accessed in the outer block i.e. it cannot be accessed after inner end block. and 'num1' and 'num2' can be accessed anywhere in the block.

Example Code:

DECLAREnum1 number := 10;num2 number := 20;

BEGINDECLARE

num_addition number; BEGIN

num_addition := num1 + num2; dbms_output.put_line('Addition is: ' ||

num_addition);END;

END;/

Example Result:

Addition is: 30

PL/SQL Constants Declaration

PL/SQL Constants Declaration is use to constant value can not be change in PL/SQL Block.

PL/SQL Constants Declaration Syntax

The General Syntax to declare a variable is:

Constant_Name CONSTANT DataType[Size] := Value;

Constant_Name is the predefined name of the constant (similar to a variable name). CONSTANT is a reserved word and the value does not change. DataType is a valid PL/SQL datatype. Size is an optional specification of datatype size to hold maximum size value. Value must be assigned to a constant when it is declared. not assign the later. Each constant declaration is terminated by a semicolon.

Page 10: Pl./sql

PL/SQL Constant Declaration Example

1. Store the employee No is NOT NULL(compulsory), employee Name and constant the employee Department fixed on Web Developer using the Variable.

Example Code:

DECLAREeno number(5) NOT NULL := 2ename varchar2(15) := Jay Patel;edept CONSTANT varchar2(15) := Web Developer;

BEGINdbms_output.put_line('Declared Value:');dbms_output.put_line(' Eno: ' || eno || ' EName: ' || ename);dbms_output.put_line('Constant Declared:');dbms_output.put_line(' EDept: ' || edept);

END;/

Backward slash '/' is indicates to execute the above PL/SQL Block Program.

Example Result:

Declared Value:Eno: 2 Ename: Jay PatelEDept: Web Developer

Constant benefit is to not all time assign the same value in the same variable its fixed and not change during the program block.

PL/SQL Server Output

PL/SQL is a work on the server result so we always required to server output result is show in the screen otherwise result can not be display.

Whenever start the Oracle at that time required to write the input command "set serveroutput on".

How to on the PL/SQL Server ResultSQL> set serveroutput on

Page 11: Pl./sql

Set serveroutput on Example

Store the employee No is NOT NULL(compulsory), employee Name and constant the employee Department fixed on Web Developer using the Variable.

Exmple Code:

SQL> set serveroutput onSQL> DECLARE

eno number(5) NOT NULL := 2ename varchar2(15) := Jay Patel;edept CONSTANT varchar2(15) := Web Developer;

BEGINdbms_output.put_line('Declared Value:');dbms_output.put_line(' Eno: ' || eno || ' EName: ' ||

ename);dbms_output.put_line('Constant Declared:');dbms_output.put_line(' EDept: ' || edept);

END;/

Result show only on when execute the first "set serveroutput on" command.

Example Result:

Declared Value:Eno: 2 Ename: Jay PatelEDept: Web Developer

PL/SQL Comments

Comments in PL/SQL can take one of two forms:

Multi-line comments and Single line comments.

Multi-line comments are delimited with /*....*/ andsingle line comments starts with two dashes --.

Comments can begin in any column on any line. If you are embedding comments in SQL that will be embedded in PL/SQL you need to be careful but just about any other use is easy understand.

PL/SQL Multi line and Single line Comments

Page 12: Pl./sql

SQL>-- Single Line CommentSQL>/* Multiline Comment line 1

Multiline Comment line2 */

Comment Example

Store the employee No is NOT NULL(compulsory), employee Name and constant the employee Department fixed on Web Developer using the Variable.

Exmple Code:

SQL> set serveroutput onSQL> DECLARE

--assign value into eno variableeno number(5) NOT NULL := 2;

ename varchar2(15) := Jay Patel;

/* Constant value is fixed for edept value is "Web Deloper" is fixed all program not required declare all times. */edept CONSTANT varchar2(15) := Web Developer;

BEGINdbms_output.put_line('Declared Value:');dbms_output.put_line(' Eno: ' || eno || ' EName: ' || ename);dbms_output.put_line('Constant Declared:');dbms_output.put_line(' EDept: ' || edept);

END;/

Example Result:

Declared Value:Eno: 2 Ename: Jay PatelEDept: Web Developer

PL/SQL If Statements

PL/SQL IF statement is used to transfer the control of program depending on a specified condition. If we want to know greater of given 2 numbers then we can use the IF statement for comparing the 2 values.

Page 13: Pl./sql

Simple IF Statement Syntax

Simplest IF statement takes the following format:

IF <condition> THEN<statements>;

END IF;

IF..ELSE Statement Syntax

IF statement have a ELSE part:

IF <condition> THEN<statements>;

ELSE<statements>;

END IF;

Nested IF Statement Syntax

Nested IF statement have a IF..ELSE part:

IF <condition-1> THEN<statements>;

ELSEIF <condition-2> THEN

<statements>;ELSE

<statements>;END IF;

END IF;

Alternative Nested IF Syntax

Alternative Nested IF have a IF..ELSE part:

IF <condition-1> THEN<statements>;

ELSIF <condition-2> THEN<statements>;

ELSIF <condition-3> THEN

Page 14: Pl./sql

<statements>;............................................................ELSE

<statements>;END IF;

PL/SQL Loops/Iterative

When we need to execute the block of statements we required to repeatedly for a certain number of times then we haveto use loops.

PL/SQL support three looping control: SIMPLE Loop, WHILE Loop, FOR Loop.

Simple Loop

Syntax:LOOP <Sequence of statements> EXIT; {or EXIT WHEN condition;}END LOOP; Example Code:SQL>DECLARE

i number;BEGINLOOP

dbms_output.put_line('Hello');i:=i+1;EXIT WHEN i>5;

END LOOP; END;/

Example Result:

HelloHelloHelloHello

Page 15: Pl./sql

While Loop

Syntax:

WHILE <condition>LOOP

<action>END LOOP;

Example Code:

SQL>DECLAREi number;

BEGINWHILE i<5LOOP

dbms_output.put_line('Hello');i:=i+1;

END LOOP; END;/

Example Result:

HelloHelloHelloHello

FOR Loop

Syntax:

FOR variable IN [REVERSE] start..endLOOP <action>END LOOP;

Example Code:

SQL>DECLAREBEGIN

Page 16: Pl./sql

FOR i IN 1..5LOOP

dbms_output.put_line('Hello');END LOOP; END;/

Example Result:

HelloHelloHelloHello

PL/SQL GOTO Statement

GOTO statement transfers the control of program unconditionally. GOTO statement is transfers the control of program to any position in the PL/SQL block.

GOTO Syntax

GOTO <<Code_Block_Name>>----------------------<<Code_Block_Name>>----------------------

Example Code:

SQL>DECLAREBEGINFOR i IN 1..5LOOP

dbms_output.put_line(i);IF i=4 THEN

GOTO label1;END IF;

Page 17: Pl./sql

END LOOP; <<label1>>dbms_output.put_line(Row Filled);END;/

Example Result:

1234

PL/SQL Switch Case Statements

PL/SQL SWITCH case statement is important control to use the selected case statement will be execute.

SWITCH Statement Syntax

CASEWHEN <condition>

THEN <statement>WHEN <condition>

THEN <statement>ELSE <statement>END CASE

Example Code:

SQL>DECLAREa number := 5;BEGINCASEWHEN a = 5 THEN

dbms_output.put_line('Execute Me');WHEN a = 4 THEN

dbms_output.put_line('Not Execute Me');ELSE

Page 18: Pl./sql

dbms_output.put_line('Else Statements');END CASE;END;/

Example Result:

Execute Me