0% found this document useful (0 votes)
15 views

Unit 9 PL & SQL Language

Uploaded by

Rudram Kshatri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Unit 9 PL & SQL Language

Uploaded by

Rudram Kshatri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

PARUL INSTITUTE OF ENGINEERING & TECHNOLOGY

FACULTY OF ENGINEERING & TECHNOLOGY


PARUL
UNIVERSITY

Database Management System


PL/SQL
Block Views
Cursors
Triggers
Stored Procedures
Store Functions
PL/SQL
Procedural Language/Structured Query Language PL/SQL
An extension to SQL with design features of
programming languages (procedural and object oriented).

 Provides Portability of code from one environment to another.

 Improves performance of multi-query transactions.

 Provides error handling.

 Acts as host language for stored procedures and triggers.


Features of PL/SQL
 PL/SQL is tightly integrated with SQL.
 It offers extensive error checking.
 It offers numerous data types.
 It offers a variety of programming structures.
 It supports structured programming through functions
and procedures.
 It supports object oriented programming.
 It supports developing web applications and server pages.
Advantages of PL/SQL
 Block structures: PL/SQL consists of blocks of codes
that can be stored in the database and reused.
 Procedural language capability: PL/SQL consists of
procedural language such as conditional
statements(IF, ELSE statement) and loops (FOR
loop).
 Better performance: PL/SQL executes multiple
SQL statements simultaneously as a single block.
 Error handling: PL/SQL handles error or
exception effectively while execution.
PL/SQL Block-
Structure
PL/SQL is a block-structured language. The structure of
a PL/SQL block consists of four parts:
PL/SQL Block-
Structure
PL/SQL programs are divided and written in logical blocks
of code.
1. Declarations : This section starts with the keyword
DECLARE to declare variables, allocate memory for cursors,
and define data types.
2. Executable section: An executable section starts with the
keyword BEGIN and ends with the keyword END.
3. Exception-handling section : A PL/SQL block has an
exception-handling section that starts with the keyword
EXCEPTION. The exception-handling section is where you
catch and handle exceptions raised by the code in the
execution section.
PL/SQL Block-
Structure
Syntax The 'Hello World' Example
DECLARE DECLARE
<declarations section> message varchar2(20):= 'Hello, World!';
BEGIN BEGIN
<executable command(s)> dbms_output.put_line(message);
EXCEPTION END;
<exception handling>
END;
It produces the following
result −
Hello
World
PL/SQL procedure successfully
completed.
PL/SQL
 Conditional Statements

1. IF …THEN…ELSE 2. CASE…

IF <condition> THEN CASE


<Code> WHEN VARIABLE = VALUE THEN
ELSEIF <condition> THEN <Code>
<Code> WHEN VARIABLE = VALUE THEN
ELSE <Code>
<Code> ELSE
ENDIF; <Code>
END CASE;
PL/SQL
 Types of Loops
1. Simple Loop 3. For Loop
Loop FOR <Variable> IN <Min> .. <Max>
<Code> Loop
Exit when <Cond> <Code>
End Loop; End Loop;
2. While Loop While 4. For
<Condition> Loop Loop
<Code> FOR
End Loop; <Variable
> IN
REVERSE
<Min> .. <Max>
PL/SQL
Examples
Write a PL/SQL block to add 2 numbers
declare
x number(5);
y
number(5);
z number(7);
begin
x:=10;
y:=20;
z:=x+y;
DBMS_OUTPUT.PUT_LINE('Sum is '||z);
end;
PL/SQL
Examples
Write a PL/SQL block to find maximum of 2 numbers
declare
x number(5);
y
number(5);
begin
x:=10;
y:=20;
if x > y then
DBMS_OUT
PUT.PUT_L
INE(‘x is
greater
than y');
else
PL/SQL
Examples
Write a PL/SQL block to print the sum of Numbers from
1 to 100
declare

a number;

sum1 number :=0;

begin

a:=1;

loop

sum1:=sum1+a;

a:=a+1;

exit when (a>100);

end loop;
DBMS_OUTPUT.PU
T_LINE('sum of 1
to 100 is '||sum1);

end;
View
s A PL/SQL view is a virtual table that contains data from one or
more tables.

Views are used to provide security or simplify complex queries.


Creating a View:
To create a view, you use the CREATE VIEW statement as
follows:
CREATE VIEW view_name
AS SELECT column1,
column2,...
FROM table_name
View
sFor example, to create a view that displays all employees in the
sales
department.
CREATE VIEW sales_employees
AS SELECT first_name, last_name
FROM employees
WHERE department = 'Sales';

To display the view, you use the SELECT statement as follows:


SELECT * FROM view_name;

For example, to display all employees in the sales


department: SELECT * FROM
sales_employees;
View
s
Updating a View

To update data in a view, you use the UPDATE View statement.

For example, to increase the salary of all employees in the


sales department by 10%.

UPDATE sales_employees SET salary = salary * 1.1;


View
s Modifying a View
You can modify an existing view by using the CREATE OR REPLACE
VIEW statement.

This statement first drops the existing view and then creates it again.

For example, to modify the sales_employees view so that it displays


all employees in the sales or marketing departments

CREATE OR REPLACE VIEW sales_employees


AS
SELECT first_name, last_name
FROM employees
WHERE department IN
View
s Drop VIEW
Once VIEW has been created, you can drop it with the DROP
VIEW
Statement.

Syntax: DROP VIEW view_name;

Example: DROP VIEW

sales_employees;
Cursor
s  Cursor is a temporary working area created in
the system memory when your SQL statement is
executed.

 The Data that is stored in the Cursor is called the Active


Data Set.
Cursor
s 1. Implicit Cursors
The implicit cursors are automatically generated while an SQL
statement is executed, if you don't use an explicit cursor for the
statement.

These are created by default to process the statements when DML


statements like INSERT, UPDATE, DELETE etc. are executed.
Cursor
s Attribute &
Description Its return value is TRUE if DML statements or SELECT INTO
%FOUND statement return one or more rows. Otherwise it returns FALSE.
Its return value is TRUE if DML statements or a SELECT INTO
%NOTFOUND statement return no rows. Otherwise it returns FALSE.

It always returns FALSE for implicit cursors, because the SQL


%ISOPEN cursor is automatically closed after executing its associated SQL
statements.

It returns the number of rows affected by DML statements or


%ROWCOUNT returned by a SELECT INTO statement.

* DML statements like INSERT, DELETE and UPDATE


Cursor
s
ID
Implicit Cursor Example
NAME AGE ADDRESS SALARY
1 Ramesh 23 Allahabad 20000
2 Suresh 22 Kanpur 22000
3 Mahesh 24 Ghaziabad 24000
4 Chandan 25 Noida 26000
5 Alex 21 Paris 28000
6 Sunita 20 Delhi 30000

Let's increase salary of each customer by 5000.


Here, SQL%ROWCOUNT attribute is used to
determine the number of rows affected.
Cursor
s Now, if you check the records in customer table, you will find that
the rows are updated.
select * from customers;
ID NAME AGE ADDRESS SALARY
1 Ramesh 23 Allahabad 25000
2 Suresh 22 Kanpur 27000
3 Mahesh 24 Ghaziabad 29000
4 Chandan 25 Noida 31000
5 Alex 21 Paris 33000
6 Sunita 20 Delhi 35000
Cursor
s 1. Explicit Cursors
The Explicit cursors are defined by the programmers to gain
more control over the context area. These cursors should be
defined in the declaration section of the PL/SQL block.

Syntax of explicit cursor:


CURSOR cursor_name IS select_statement;
Cursor
s
Steps while working with an explicit cursor:

1. Declare the cursor to initialize in the memory.


2.Open the cursor to allocate memory.
3.Fetch the cursor to retrieve data.
4.Close the cursor to release allocated
memory.
Cursor
sExecute the program to retrieve the customer name and address.
1. DECLARE Output
2. c_id customers.id%type; 1 Ramesh Allahabad
3. c_name customers.name%type;
4. c_addr customers.address%type; 2 Suresh Kanpur
5. CURSOR c_customers is 3 Mahesh Ghaziabad
6. SELECT id, name, address FROM customers;
4 Chandan Noida
7. BEGIN
8. OPEN c_customers; 5 Alex Paris
9. LOOP 6 Sunita Delhi
10. FETCH c_customers into c_id, c_name, c_addr; PL/SQL procedure successfully
11. EXIT WHEN c_customers%notfound; completed.

12. dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);


13. END LOOP;
14. CLOSE c_customers;
15. END;
Trigge
r
PL/SQL triggers are block structures and predefined programs
invoked automatically when some event occurs.

They are stored in the database and invoked repeatedly in a particular

scenario. Triggers occurs with response-based events:

1. Database Definition Language statements such as CREATE, DROP or


ALTER.
2. Database Manipulation Language statements such as UPDATE, INSERT or
DELETE.
3. Database operations such as LOGON, LOGOFF, STARTUP, and
SHUTDOWN.
Trigge
r
Importance of Trigger Usages Of Triggers
 Automated Action
 Prevents improper transactions.
 Data integrity
 Accumulates information on
 Consistency
table usage.
 Error handling  Monitor critical information
Types of
Trigger
• ROW Level trigger: Event is triggered for each
row updated/inserted/deleted.

• STATEMENT Level trigger: Event is triggered for


each SQL statement is executed.
Trigge
r Syntax of Triggers
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER}
{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;
Compound
Trigger
A compound trigger is used to define the operations for all
the timing points within the trigger body.

The various timing points are listed below:


o AFTER STATEMENT level
o BEFORE STATEMENT level
o BEFORE ROW level
o AFTER ROW level
Trigge
r
The syntax for a dropping a Trigger is:

DROP TRIGGER trigger_name ON tbl_name;

The syntax for a disabling a Trigger is:

ALTER TRIGGER trigger_name DISABLE;

The syntax for a enabling a Trigger is:

ALTER TRIGGER trigger_name ENABLE;


Stored
Procedure
A stored procedure, on the other hand, is a reusable block of code
that performs a specific task but doesn't necessarily return a
value. Stored procedures are primarily used to process,
manipulate, and modify data in the database.
CREATE [OR REPLACE] PROCEDURE procedure_name [
(parameter mod datatype [parameter]) ]
IS
[local variable declaration_section]
BEGIN
executable_section
[EXCEPTION
exception
_section]
END
Stored
Procedure
EXAMPLE:
Create or replace procedure account_update The Following Stored
( Procedure updates
curr_acc_no IN varchar2, the balance of the
curr_name IN varchar2, account for a given
curr_balance IN number account number and
) name of the account.
IS
BEGIN
u
p
d Command to
a Execute the Store
t Procedure
e

a
c Execute account_update(‘A001’,’Patel’,125000);
c
o
Store
Function
A function is similar to a procedure, except that it returns a
single value.

 Functions is a reusable block of code that performs a specific


task and returns a single value.

Example:
CREATE FUNCTION GetTotalRevenue()
RETURNS DECIMAL(10,2)
BEGIN
RETURN (SELECT SUM(TotalAmount) FROM Orders);
END
Stored Procedure & Store
FunctionFunction Stored Procedure
Returns a single value, either as a table Can return zero, a single value, or
or as a scalar, always. several values.
Run-time compilation and execution The database contains stored
occur for functions. procedures that have been parsed and
compiled.
Only input parameters are permitted. Both input and output parameters are
supported.
Transactions are not permitted within A stored procedure can
a function. contain transactions.
A function cannot call a stored A stored procedure can be called a
procedure. function.
THANK
YOU!!
www.paruluniversi

You might also like