0% found this document useful (0 votes)
22 views39 pages

PL SQL

Uploaded by

liyava6499
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)
22 views39 pages

PL SQL

Uploaded by

liyava6499
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/ 39

PL / SQL

PL/SQL
 PL/SQL is a procedural language extension to Structured Query
Language (SQL).

 The purpose of PL/SQL is to combine database language and procedural


programming language.

 The basic unit in PL/SQL is called a block and is made up of three parts:
a declarative part, an executable part and an exception-building part.

 A PL/SQL program that is stored in a database in compiled form and can


be called by name is referred to as a stored procedure
Differences between SQL and PL/SQL

SQL PL/SQL

SQL is a single query that is used to PL/SQL is a block of codes that used to write
perform DML and DDL operations. the entire program blocks/ procedure/
function, etc.

Execute as a single statement. Execute as a whole block.


Mainly used to manipulate data. Mainly used to create an application.
Cannot contain PL/SQL code in it. It is an extension of SQL, so it can contain
SQL inside it.
Structure of PL/SQL Block

 The basic unit in PL/SQL is a block. All


PL/SQL programs are made up of
blocks, which can be nested within each
other. PL/SQL contains 4 main blocks
 Declare
 Begin
 Exception DECLARE
Declaration statement;
 End BEGIN
Executable statements;

 EXCEPTIONS
Typically, each block performs a logical Exception handling statements;
action in the program. A block has the
following structure: END;
PL/SQL Identifiers

 There are several PL/SQL identifiers such as procedures, cursors, triggers


etc.

Variables:
 Like several other programming languages, variables in PL/SQL must be
declared prior to its use. They should have a valid name and data type as well.
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
var1 INTEGER;
var2 REAL;
var3 varchar2(20) ;
BEGIN
null;
END;
/

Output:
PL/SQL procedure successfully completed
INITIALISING VARIABLES

 Example for initializing variable

SQL> SET SERVEROUTPUT ON;


SQL> DECLARE
var1 INTEGER := 2 ;
var3 varchar2(20) := ‘Hi Everyone!!!!';

BEGIN
null;
END;
/

Output:
PL/SQL procedure successfully completed
DISPLAYING OUTPUT

 The outputs are displayed by using DBMS_OUTPUT which is a built-in


package that enables the user to display output.

SQL> SET SERVEROUTPUT ON;


SQL> DECLARE
var varchar2(40) := ‘Hi Everyone';

BEGIN
dbms_output.put_line(var);
END;
/
Output:

Hi Everyone
PL/SQL procedure successfully completed
TAKING INPUT FROM USER
 Just like in other programming languages, in PL/SQL also, we can take
input from the user and store it in a variable

SQL> SET SERVEROUTPUT ON;


SQL> DECLARE
-- taking input forvariable a
a number := &a;
-- taking input forvariable b
b varchar(30) := &b;
BEGIN
null;
END;
/

Output:
PL/SQL procedure successfully completed
Example 1:
--PL/SQL code to print sum of two numbers taken from the user.
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
-- taking input forvariable a
a integer := &a ;
-- taking input forvariable b
b integer := &b ;
c integer ;
BEGIN
c := a + b ;
dbms_output.put_line('Sum of '||a||' and '||b||' is = '||c);
END;
/

Output:
2
3
Sum of 2 and 3 is =5
PL/SQL procedure successfully completed
Example 2:
--PL/SQL code to print natural numbers from 1 to 5

SQL> SET SERVEROUTPUT ON;


SQL> DECLARE
i number;
BEGIN
i:=1;
loop
dbms_output.put_line(i);
i:= i+1;
exit when i>5;
end loop;
END;
/
Example 3:
PL/SQL Program to Find Factorial of a Number
declare
n number;
fact number:=1;
i number;

begin
n:=&n;

for i in 1..n
loop
fact:=fact*i;
end loop;

dbms_output.put_line('factorial='||fact);
end;
/
Example 4: Pl/SQL Program for Palindrome Number
declare
n number;
m number;
rev number:=0;
r number;
begin
n:=12321;
m:=n;
while n>0
loop
r:=mod(n,10);
rev:=(rev*10)+r;
n:=trunc(n/10);
end loop;

if m=rev
then
dbms_output.put_line('number is palindrome');
else
dbms_output.put_line('number is not palindrome');
end if;
end;
/
Procedure (stored procedure)
 A stored procedure is a prepared SQL code that you can save, so the code can
be reused over and over again.
 You can also pass parameters to a stored procedure. They are:

IN:
This is the Default Parameter for the procedure. It always receives the values
from calling program.
OUT:
This parameter always sends the values to the calling program.
IN OUT:
This parameter performs both the operations. It Receives value from as well as
sends the values to the calling program.
Syntax : Creating a Procedure

CREATE or REPLACE PROCEDURE name(parameters)


IS
variables;
BEGIN
//statements;
END;
Example
Create or replace procedure inc_salary(E IN number, amt IN number, S
OUT number)
IS
BEGIN
UPDATE emp set sal = sal + amt where empno = E;
commit;
select sal into S from emp where empno = E;
END;
/
Steps to execute the procedure:
 Declare a Variable to Store the value comming out from
Procedure :
Variable v NUMBER;

 Execution of the Procedure:


EXECUTE inc_salary(1002,1000, :v);

 To check the updated salary use SELECT statement:


SELECT * FROM emp_table WHERE emp_no = 1002;
Example 2:
Create or replace procedure insertuser(id IN number ,
name IN varchar)
IS
BEGIN
insert into user values(id, name);
End;
/

Output:
insertuser(101,’raju’);
Dbms_output.put_line(“inserted successfully”);
/
TRIGGERS
A trigger is a procedure that is automatically invoked by the DBMS in
response to specified changes to the database, and is typically specified
by the DBA.

A database that has a set of associated triggers is called an active


database.

A trigger description contains three parts:


Event: A change to the database that activates the trigger.
Condition: A query or test that is run when the trigger is activated.
Action: A procedure that is executed when the trigger is activated
and its condition is true.
TRIGGERS
An insert, delete or update statement could activate a trigger, regardless
of which user or application invoked the activating statement.

A condition in a trigger can be a true/false statement or a query.

If the condition part evaluates to true, the action associated with the
trigger is executed.
TRIGGERS

In fact, an action can even execute a series of data-definition commands


(e.g., create new tables, change authorizations) and transaction-oriented
commands (e.g., commit), or call host language procedures.

The execution of the action part of a trigger could again activate the
same trigger such triggers are called recursive triggers.
Contd..

The following are the key differences between triggers and stored
procedures:

1. Triggers cannot be manually invoked or executed.


2. There is no chance that triggers will receive parameters.
3. A transaction cannot be committed or rolled back inside a trigger.
TRIGGERS
Trigger Declaration 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)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
Contd..
BEFORE and AFTER Trigger
 The main purpose of a BEFORE trigger is to perform any checks,
validations, or calculations before the data is actually written to the
database. Since it executes before the data is inserted or updated, it
allows you to modify the incoming data (:NEW values) before they are
saved.
 AFTER triggers are used when you need to perform operations that rely
on the data being already inserted, updated, or deleted. Since the
operation has already occurred, you cannot modify the :NEW values
directly. Instead, you can use AFTER triggers to update related tables,
enforce referential integrity.
Example 1: before insert
create table student( create or replace trigger student_marks
sid int primary key, before insert on student
name varchar(20), for each row
sub1 int, begin
sub2 int,
:new.total:=:new.sub1+:new.sub2+:new.sub3;
sub3 int,
:new.percentage:=((:new.sub1+:new.sub2+:new.sub3)/300)*100;
total int,
end;
percentage int);
/
Output: Trigger created
// table created
Contd..

Execution

SQL> insert into student(sid,name,sub1,sub2,sub3)


values(101,’ram’,67,78,86);
1 row inserted

SQL> select * from student;


Contd..

 Given Student Report Database, in which student marks assessment is


recorded. In such a schema, create a trigger so that the total and
percentage of specified marks are automatically inserted whenever a
record is inserted.
 Here, a trigger will invoke before the record is inserted so BEFORE
Tag is used.
Example 2: After Insert
create table student( create or replace trigger insert_operation
id int primary key, after insert on student

name varchar(35)); begin


insert into log values(sysdate, '1 row
successfully inserted’, 'student’);
create table log( end;
access_date date, /
operation varchar2(40),
table_name varchar(10)); Output:
Trigger created
Contd..
Execution

SQL> insert into student values(1002,'Raman’);


1 row created.

SQL> select * from student;


ID NAME
---------- -----------------------------------
1002 Raman

SQL> select * from log;


ACCESS_DATE OPERATION TABLE_NAME
---------------- ---------------------------------------- -------------
10-SEP-24 1 row successfully inserted student
Example 3: Before Update
create table employee( create or replace trigger update_demo
eid int primary key, before update of salary on employee
name varchar(30), for each row
age int, begin
salary int, if
dept varchar(20)); :new.salary < 100000 then
:new.salary := :new.salary*1.10;
end if;
end;
/
Output: Trigger created
Contd..
Execution
SQL> update employee set salary=50000 where eid=102;
1 row updated

SQL> select * from employee;


EID NAME AGE SALARY DEPT
---------- -------------------- ---------- ---------- ----------
101 Ram 27 112400
Sales
102 Ramya 24 55000
Accounts
103 Ramesh 34 114000
Accounts
Example 4: After Update

create table student( create or replace trigger update_operation


id int primary key, after update on student
name varchar(35)); Begin
insert into log values(sysdate, '1 row
successfully updated’, 'student’);
create table log(
end;
access_date date,
/
operation varchar2(40),
table_name varchar(10)); Output:
Trigger created
Contd..
Execution
SQL> update student set name='S Raman' where id=1002;
1 row updated

SQL> select * from student;


ID NAME
---------- -----------------------------------
1002 S Raman

SQL> select * from log;


ACCESS_DATE OPERATION TABLE_NAME
--------- ---------------------------------------- ----------
10-SEP-24 1 row successfully inserted student
10-SEP-24 1 row successfully updated student
Example 5: After Update
create table student( create or replace trigger update_operation2
id int primary key, after update on student
name varchar(35)); begin
insert into log values(systimestamp, '1 row successfully
create table log( updated’, 'student');

access_date timestamp, end;

operation varchar(25), /

table_name varchar(20));
Output: Trigger created.

Output: Table created


Contd..
Execution
SQL> update student set name='Sai R Raman' where id=1002;
1 row updated.
SQL> select * from student;
ID NAME
---------- -----------------------------------
1002 Sai R Raman
SQL> select * from log;
ACCESS_DATE OPERATION TABLE_NAME
---------------------------------- ------------------------------ --------------------
10-SEP-24 12.20.05.039000 PM 1 row successfully updated student
10-SEP-24 12.20.05.039000 PM 1 row successfully updated student
10-SEP-24 12.20.05.000000 PM 1 row successfully updated student
TRIGGERS
Constraints versus Triggers
Triggers are active, while constraints are passive. While constraints prevent
updates that violate referential integrity, triggers perform explicit actions in addition
to the update operation.

Triggers can do much more than enforce referential integrity. Because they are
passive, constraints are limited to preventing updates in a narrow set of conditions.

A common use of triggers is to maintain database consistency.

The meaning of a constraint is not defined operationally, unlike the effect of a


trigger.

This property makes a constraint easier to understand, and also gives the DBMS
more opportunities to optimize execution.
TRIGGERS
Constraints versus Triggers

A constraint also prevents the data from being made inconsistent by


any kind of statement, whereas a trigger is activated by a specific kind
of statement (e.g., an insert or delete statement). Again, this restriction
makes a constraint easier to understand.

On the other hand, triggers allow us to maintain database integrity in


more flexible ways.
Assertions
 An assertion is a predicate expressing a condition we wish the database to always satisfy.
 Domain constraints, functional dependency and referential integrity are special forms of assertion.
 Syntax:
CREATE ASSERTION assertion_name CHECK (condition);
 Example 1:
 Suppose we have a table "Orders" and we want to ensure that the total amount of all orders is always
less than 10000.
Query: CREATE ASSERTION orders_total CHECK ((SELECT SUM(amount) FROM Orders) < 10000);
 Example 2:
 To create an assertion called “salary_assertion” that checks that no employee in the
“employees” table has a salary greater than $100,000, you could use the following statement:
Query: CREATE ASSERTION salary_assertion CHECK (salary <= 100000);
Assertions (contd..)
 To drop an assertion, you can use the following statement:
Syntax:
DROP ASSERTION assertion_name;
Example:
drop assertion orders_total;

Assertions are useful for enforcing data integrity and ensuring that the data in the
database meets certain conditions. They can be used to enforce business rules or
to ensure the consistency of the data. However, they can also be time-consuming
to create and maintain, so they are not always used in practice.
Thank you

You might also like