Sunteți pe pagina 1din 52

PL/SQL

1.Basic structure of sql


2.Introduction to pl/sql
3.Sql vs pl/sql
4.Advantages of pl/sql
5.Architecture of pl/sql
6.PL/SQL language elements
7.PL/SQL control statements
BASIC STRUCTURE OF SQL
s the language used to manipulate relational database. SQL is
very closely with the relational model

imple and powerful language used to create ,manipulate and


ve data and structure in the database..

s a non-procedural language i.e. it describe what is required


out how result should be computed..

ndustry standard language for relational database management


m such as oracle, Microsoft SQL Servers, MS Access

nd ANSI has published standards for SQL implementation Join


by ISO and ANSI has lead to standard version of SQL is called
86(SQL1), SQL/92(SQL2)
INTRODUCTION TO PL/SQL
/SQL stands for Procedural Language/Structured Query Language, and it
extension of the SQL Language

s superset of the Structured Query Language specialized for use in the


acle database.

cause it is procedural language, it eliminates many restriction of the SQL


nguage

th the use of SQL user can only perform basic operations such as selecti
e information from some prefabricated tables, inserting information into
ose tables, updating the information stored into tables and also used to
lete information from these tables

/SQL extends SQL by adding control structure found in the other procedu
nguages

/SQL is the combination of SQLs languages ease of data manipulation a


e procedural languages ease of programming.
7. With PL/SQL, we can use SQL statements to manipulate ORACL
data and
the flow of control statements to process the data. Moreover, we ca
declare
constants and variables, define subprograms (procedures an
functions).
Thus, PL/SQL combines the data manipulating power of SQL with th
data
processing power of procedural languages

8. While PL/SQL is just like any other programming language, it ha


syntax and
rules that determine how programming statements work together.
It is important for you to realize that PL/SQL is not a stand-alon
programming
language

9. PL/SQL is a part of the Oracle RDBMS, and it can reside in tw


environments,
the client and the server
www.starthack.com
When the PL/SQL engine is located on the
client, as it
is in the Oracle Developer Tools, the PL/SQL
processing is done on the client side.

All SQL statements that are embedded within


the
PL/SQL block are sent to the Oracle server for
further
processing. When PL/SQL block contains no SQL
statement, the entire block is executed on the
client
side.
SQL VS PL/SQL
SQL PL/SQL
SQL does not have any procedural ORACLE has provides all procedural
capabilities capabilities in PL/SQL to support data
filtration
SQL statements are passed to oracle In PL/SQL it sends the bundle of SQL
engine(server) one at a statements to the oracle server in the
time..Therefore each time for each form of BLOCK and hence calling the
statement a call is made to the server server resources only once for that
resources and these resources are block even if that block is having
opened and closed every time more than one SQL statements

Due to this, Generating network After processing all the statements in


traffic resulting in slow processing. a block ORACLE server closer the
resources results in faster execution
of SQL statements in a PL/SQL
block.
In SQL, there is no provision for In PL/SQL, we can program the block
handling errors and exception, which of statements to handle the errors in
means that if any SQL statements such a way that if any of the
fails to execute, then oracle gives its statement fails to execute then we
own error message and error code can display user friendly appropriate
SQL does not support PL/SQL PL/SQL supports SQL statements
statements in its block
We cannot store the intermediate PL/SQL supports declaring the
results of a query in variable variables so as to store
intermediate results for later
use
ADVANTAGES OF PL/SQL
Supports the declaration and manipulation of object types and collectio
Allowing the calling of external function and procedure
Contains new libraries of built-in packages.A package is a file that gro
functions, cursors, stored procedures and variables in one place

TRIGGERS: Trigger is a PL/SQL program that is stored in the database


executed immediately before or after the INSERT, UPD
and DELETE command

CURSORS: Oracle uses workspaces to executes the SQL commands.


Through PL/SQL it is possible to name the workspace and
access its information

PL/SQL allow us to use all the SQL data manipulation commands, tran-
section control commands, SQL functionsand operators, thus allowing u
manipulates data values in a table more flexibly and effectively
PL/SQL BLOCK STRUCTURE

PL/SQL blocks contain three sections

1. Declare section
2. Executable section
3. Exception-handling section.

The executable section is the only mandatory


section
of the block.

Both the declaration and exception-handling


sections
are optional.
PL/SQL block has the following structure:

DECLARE - Declaration statements

BEGIN - Executable statements

EXCEPTION - Exception-handling
statements

END ;
DECLARATION SECTION

The declaration section is the first section of the


PL/SQL block..

It contains definitions of PL/SQL identifiers such


as
variables, constants, cursors and so on..

Example

DECLARE
v_first_name VARCHAR2(35) ;
v_last_name VARCHAR2(35) ;
v_counter NUMBER := 0 ;
EXECUTABLE SECTION

The executable section is the next section of the PL/SQL


block.

This section contains executable statements that allow


you to manipulate the variables that have been declared in
the declaration section.

BEGIN
SELECT first_name, last_name
INTO v_first_name, v_last_name
FROM student
WHERE student_id = 123 ;
DBMS_OUTPUT.PUT_LINE
(Student name : || v_first_name || ||
v_last_name);
END;
EXCEPTION-HANDLING SECTION
The exception-handling section is the last section of
the
PL/SQL block.

This section contains statements that are executed


when a
runtime error occurs within a block.

Runtime errors occur while the program is running


and cannot
be detected by the PL/SQL compiler.

EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE
( There is no student with student id 123 );
END;
EXAMPLE
DECLARE
v_first_name VARCHAR2(35);
v_last_name VARCHAR2(35);
BEGIN
SELECT first_name, last_name
INTO v_first_name, v_last_name
FROM student
WHERE student_id = 123;
DBMS_OUTPUT.PUT_LINE
('Student name: '||v_first_name||' '||v_last_name);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE
('There is no student with student id 123');
END ;
PL/SQL LANGUAGE ELEMENTS

Operators and Indicators

Identifiers

Literals

Comments

Expression and Comparisons

Data Types and Declarations


Operator and Indicators

ARITHMETIC OPERATOR :: Used to perform arithmetic operations


Example :- +, -, *, /

XPRESSION OPERATORS :: Used to create assignment, range and


string catenation expression.

ample :-
Assignment Operator :: A:=2
Range Operator :: 1..4
Concatenate :: || ( dav||college)

Used for variable, constants and oracle objects like


Identifiers
tables, procedure, function, package, trigger, cursor etc.
Literals
It specifies and exact value in a programIt is and explicit
Numeric, character, string and Boolean value not represen
by an identifierLiterals are used to initialize constants,
variables and other data values.

Example: 10, -19, 9.99 (Numeric Literals)


a, A, ?, ,, ) etc..are character
literals
starthack, tajinder, 1234 (String
Literals)
TRUE & FALSE (Boolean Literals)

Comments
Begin with /* and end with an asterisk-slash */

Example: /* Statements to select rate and quantity into variables and


caluclate value */
Data Types and Declaration
Some commonly used data types for PL/SQL are :-

NUMBER(store numeric data)


CHAR
VARCHAR(store variable length character data)
DATE
BOOLEAN
LONG
PL/SQL CONTROL STATEMENTS
We can change the logical flow of statements within the PL/SQL block wit
a number of control structure.

Control Structure Can Be ::


Conditional Control
Iterative Control
Sequential Control

Conditional Control :- It allows testing the truth of a condition and


executing section of program depending upon
the condition that may be true or false..

terative Control :- It allows executing a section of program repeatedly


long as a specified condition remain true..

Sequential Control :- It allows ordering the sequence of processing se


of program..
CONDITIONAL CONTROL
IF THEN Statement

IF THEN ELSE Statement

IF THEN ELSIF Statement

IF THEN Statement ::

Syntax
IF condition THEN
Sequence_of_statements;
END IF;

Example :-
IF a>b THEN
dbms_output.put_lines( a is greater);
END IF;
IF THEN ELSE ::

Syntax
IF condition THEN
Sequence_of_statements1;
ELSE;
Sequence_of_statements2;
END IF;

TRUE IF Condition FALSE

THEN action ELSE action

EXAMPLE
To illustrate of IF-ELSE construct PL/SQL block to find greate of two numb
User will enter any two numbers and IF statement will check for the grea
among the entered number.
SOLUTION :-

DECLARE
A NUMBER := &ENTER_A;
B NUMBER := &ENTER_B;

BEGIN
IF A > B THEN
DBMS_OUTPUT.PUT_LINE(A IS GREATER);
ELSE
DBMS_OUTPUT.PUT_LINE(B IS GREATER);
END IF;
END;
IF THEN ELSEIF
The::third form of IF statement uses the keyword
ELSIF (not ELSEIF) to introduce additional
Condition, as follows

SYNTAX
IF condition1 THEN
Sequence_of_statements1;
ELSIF condition2 THEN
Sequence_of_statements2;
ELSE
Sequence_of_statements3;
END IF;
Control structures(LOOP)
LOOP: loop repeats a statement. Loops are used to execute statements
until an exit condition is achieved.
There are three types of loops
1. basic loop
2. for loop: is used to perfrom iterative actions based on a count.
3. while loop: perform iterative actions based on condition.
An exit statement is used to terminate loop.
1. for loop: The initial step is executed first, and only once. This step
allows you to declare and initialize any loop control variables.
Next, the condition, i.e.,initial_value .. final_valueis evaluated. If it is
TRUE, the body of the loop is executed. If it is FALSE, the body of the loop
does not execute and flow of control jumps to the next statement just
after the for loop.
After the body of the for loop executes, the value of thecountervariable
is increased or decreased.
The condition is now evaluated again. If it is TRUE, the loop executes and
the process repeats itself (body of loop, then increment step, and then
again condition). After the condition becomes FALSE, the FOR-LOOP
terminates.
For loop
Syntax: FOR variable IN initial_value .. final_value
LOOP sequence_of_statements;
END LOOP;
WAP to print a number by using for loop.
DECLARE
a number(2);
BEGIN
FOR a in 10 .. 20 LOOP
dbms_output.put_line('value of a: ' || a);
END LOOP;
END;
To find factorial of number
declare
i number(4):=1;
n number(4):=&n;
f number(4):=1;
begin
for i in 1..n
loop
f:=f*i;
end loop;
Dbms_output.put_line('the factorial of '||n||' is:'||f);
end;
/
While loop
Sometimes, you dont know in advance how many times a
sequence of statements needs to execute because it
depends on a condition which is not fixed at compile time.
In such cases, you should use PL/SQLWHILE
LOOPstatement.
Syntax:
WHILE condition
LOOP
sequence_of_statements;
END LOOP;
DECLARE
a number(2) := 10;
BEGIN
WHILE a < 20
LOOP dbms_output.put_line('value of a: ' || a);
a := a + 1; END LOOP; END;
/
%type:
%type and % row type
ID Name

1 A

2 B

3 C

4 D
Declare
A number(10);
B number(10);
Begin
Select id, name into a,b where id=3;
Dbms_output.put_line(a|| b);
End;
Declare
a T1.id%type;
B T1.name% type;
Begin
Select id, name into a,b where id=3;
Dbms_output.put_line(a|| b);
End;
Declare
A T1%rowtype;
Select * into a from T1 where id=3;
Dbms_output.put_line(a.id ||
a.name);
End;
Triggers
Atriggeris a special kind of stored procedure
that automatically executes when an event
occurs in thedatabaseserver.
DMLtriggersexecute when a user tries to
modify data through a data manipulation
language (DML) event. DML events are INSERT,
UPDATE, or DELETE statements on a table or view.
syntax
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
BEGIN
--- sql statements
END;
options
CREATE [OR REPLACE ] TRIGGER trigger_name- This clause creates a trigger
with the given name or overwrites an existing trigger with the same name.
{BEFORE | AFTER | INSTEAD OF }- This clause indicates at what time should
the trigger get fired. i.e for example: before or after updating a table. INSTEAD
OF is used to create a trigger on a view. before and after cannot be used to
create a trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE}- This clause determines the triggering
event. More than one triggering events can be used together separated by OR
keyword. The trigger gets fired at all the specified triggering event.
[OF col_name]- This clause is used with update triggers. This clause is used
when you want to trigger an event only when a specific column is updated.
[ON table_name]- This clause identifies the name of the table or view to which
the trigger is associated.
[REFERENCING OLD AS o NEW AS n]- This clause is used to reference the old
and new values of the data being changed. By default, you reference the values
as :old.column_name or :new.column_name.
[FOR EACH ROW]- This clause is used to determine whether a trigger must fire
when each row gets affected ( i.e. a Row Level Trigger) or just once when the
entire sql statement is executed(i.e.statement level Trigger).
WHEN (condition)- This clause is valid only for row level triggers. The trigger is
fired only for rows that satisfy the condition specified.
Updating a trigger
For Example:The price of a product changes constantly. It
is important to maintain the history of the prices of the
products.
We can create a trigger to update the
'product_price_history' table when the price of the product
is updated in the 'product' table.
1)Create the 'product' table and 'product_price_history' table

CREATE TABLE product_price_history (product_id number(5),


product_name varchar2(32), supplier_name varchar2(32),
unit_price number(7 );
2) CREATE TABLE product (product_id number(5),
product_name varchar2(32), supplier_name varchar2(32),
unit_price number(7,2) );
CREATE or REPLACE TRIGGER price_history_trigger
BEFORE UPDATE OF unit_price
ON product
FOR EACH ROW
BEGIN
INSERT INTO product_price_history VALUES
(:old.product_id, :old.product_name,
:old.supplier_name, :old.unit_price);
END;
3)Lets update the price of a product.
UPDATE PRODUCT SET unit_price = 800 WHERE
product_id = 100.
Procedures
A procedure is a group of PL/sql statements that is
used to perform a specific task.A procedure is a
stored program that you can pass parameters into.
It does not return a value like a function does.
It allows a programmer to divide a program into
more than one well-defined unit called as modules.
Resuability.
It has following parts:
Declare section
Executable section
Exception handling section
Syntax to create a
procedure
CREATE [OR REPLACE] PROCEDURE
procedure_name
[(parameter_name [IN | OUT | IN OUT]
datatype [, ...])]
{IS | AS}
BEGIN
Pl/sql statements
END <optional procedure_name>;
procedure-namespecifies the name of the procedure.
[OR REPLACE] option allows modifying an existing
procedure.
The optional parameter list contains name, mode and
types of the parameters. IN represents that value will
be passed from outside and OUT represents that this
parameter will be used to return a value outside of
the procedure.
procedure-bodycontains the executable part.
IS/AS -marks the beginning of the body of the procedure.
Inside a PL/SQL block
It is created with the CREATE PROCEDURE or CREATE
FUNCTION statement. It is stored in the database and
can be deleted with the DROP PROCEDURE or DROP
FUNCTION statement.
programs
CREATE OR REPLACE PROCEDURE
greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;
/
Write a pl/sql block to multiply two numbers
using procedure inside the block
Set serveroutput on
Declare
Num1 number(5);
Num2 number(5);
Mul number(20);
Procedure multiplication( num1 in number, num2 in number, mul out number)
Is
Begin
Mul:=num1*num2;
End multoplication;
Begin
Num1:=&num1;
Num2:=&num2;
Multiplication(num1,num2,mul);..procedure calling
Dbms_output.put_line(mul);
End;
/
Write a stored procedure to add two
numbers
Create or replace procedure
addition(num1 in number, num2 in
number, sum out number)
Is
Begin
Sum:=num1+num2;
End;
/
To display the sum of two numbers by
calling the addition stored procedure
Declare
Num1 number(5);
Num2 number(5);
sum number(20);
Begin
Num1:=&num1;
Num2:=&num2;
Addition(num1,num2,sum);
Dbms_output.put_line(addition is || sum);
End;
Methods to call a procedure

1. execute procedure name;


declare
{ variable declaration}
Begin
Procedure name;
End;
Create or replace procedure p1
Is
a number(10):=&a;
b number(10):=&b;
C number (10);
Begin
C:=a+b;
Dbms_output.put_line(C);
End;
/
We can call this procedure
declare
Begin
P1;
End;
/
Create or replace procedure p1(a in
number, b in number, c out number)
Is
Begin
C:=a+b;
Dbms_output.put_line(c);
End;
Declare
a number(10):=&a;
b number(10):=&b;
C number(10);
Begin
P1(a,b,c);
End;
Execute(a,b,c);

S-ar putea să vă placă și