SlideShare a Scribd company logo
Database Management System
UNIT-9 PL/SQL Concepts
Computer Science & Engineering
Dr. Vishwanath
PARUL INSTITUTE OF ENGINEERING & TECHNOLOGY
FACULTY OF ENGINEERING & TECHNOLOGY
PARUL UNIVERSITY
Views
PL/SQL Block
Cursors
Triggers
Stored Procedures
Store Functions
DBMS UNIT 9.pptx..................................
Views
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
WHERE condition;
Views
For 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;
Views
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;
Views
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 ('Sales', 'Marketing');
Views
Views
Views
 The view is a virtual table. It does not physically exist. Rather, it is created by a
query joining one or more tables.
 A view contains rows and columns, just like a real table
 The fields in a view are fields from one or more real tables in the database
Creating an SQL VIEW
Syntax:
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition;
Views
View Creation – Example
1. CREATE VIEW transaction_view
AS SELECT acc_no, tr_date,amt from transaction;
2. Create view account_view
AS SELECT a.acc_no,a.balance,l.loan_amt,l.interest_rate from account a, loan l where
a.acc_no=l.acc_no and a.city=‘Ahmedabad’;
The above views would create a virtual table based on the
result set of the select statement. To show created views:
1. SELECT * FROM transaction_view;
2. SELECT * FROM account_view;
Views
1. Create or Replace view account_view
AS SELECT a.acc_no,a.balance,l.loan_amt,l.interest_rate,
l.remaining_loan from account a, loan l where a.acc_no=l.acc_no and
a.city=‘Vadodara’;
Updating View
You can modify the definition of a VIEW without dropping it by using the
following syntax:
CREATE OR REPLACE VIEW view_name
AS SELECT columns
FROM table
WHERE predicates;
Views
Deleting View
The syntax for dropping a VIEW :
DROP VIEW view_name;
View Drop - Example
DROP VIEW transaction_view;
Views
Question: Can you update the data in an view?
Answer : A view is created by joining one or more tables. When you update
record(s) in a view, it updates the records in the underlying tables that make up the
View. So, yes, you can update the data in View providing you have the proper
privileges to the underlying tables.
Question: Does the SQL View exist if the table is dropped from the database?
Answer: Yes, View continues to exist even after one of the tables (that the SQL View
is based on) is dropped from the database. However, if you try to query the View
after the table has been dropped, you will receive a message indicating that the
View has errors.
Views
Trigger
 A trigger is a block structure which is fired when a DML statements
like Insert, Delete, Update is executed on a database table. A trigger
is triggered automatically when an associated DML statement is
executed.
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) ;
Trigger
Creating Trigger
1. CREATE TRIGGER deleted_details
BEFORE
DELETE on loan
FOR EACH ROW
2. CREATE TRIGGER inserted_details
after
insert on transaction
FOR EACH ROW
Trigger
Creating Trigger
3. CREATE TRIGGER updated_details
BEFORE
UPDATE on account
FOR EACH ROW when name=‘Patel Hiren’;
Deleting Trigger
Drop trigger inserted_details on transaction;
Trigger
 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;
PL/SQL
Procedural Language – SQL: An extension to SQL with design
features of programming languages (procedural and object
oriented)
PL/SQL
PL/SQL BLOCK STRUCTURE
DECLARE (optional)
- variable declarations
BEGIN (required)
- SQL statements
- PL/SQL statements or sub-blocks
EXCEPTION (optional)
- actions to perform when errors occur
END; (required)
PL/SQL
 There are 2 types of Datatypes:
1. Scalar (Char, Varchar2, Date and Number)
2. Composite (%rowtype)
 All Variables required to be used in the program must be declared before
their use. Variable names cannot be table, column and keyword names.
 Assignment Operator is denoted as “:=” and each statement of PL/SQL ends
with “;”.
 Dbms_Output.Put_Line() is used for printing Output.
 &Variable_Name :Variable Name is use to take input from the user.
PL/SQL
1. IF …THEN…ELSE
IF <condition> THEN
<Code>
ELSEIF <condition> THEN
<Code>
ELSE
<Code>
ENDIF;
2. CASE…
CASE
WHEN VARIABLE = VALUE THEN
<Code>
WHEN VARIABLE = VALUE THEN
<Code>
ELSE
<Code>
END CASE;
 Conditional Statements
PL/SQL
1. Simple Loop
Loop
<Code>
Exit when <Cond>
End Loop;
2. While Loop
While <Condition>
Loop
<Code>
End Loop;
 Types of Loops
3. For Loop
FOR <Variable> IN <Min> .. <Max>
Loop
<Code>
End Loop;
4. For Loop
FOR <Variable> IN REVERSE <Min> ..
<Max>
Loop
<Code>
End Loop;
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_OUTPUT.PUT_LINE(‘x is greater than y');
else
DBMS_OUTPUT.PUT_LINE(‘ y is greater than x');
end if;
end;
PL/SQL Examples
Write a PL/SQL
block to find area of
rectangle, square
and circle
declare
area_c number(6, 2) ;
radius number(1) := 3 ;
area_r number(6) ;
area_s number(6) ;
length number(2) := 5 ;
width number(2) := 4 ;
pi constant number(3, 2) := 3.14;
begin
area_c := pi * radius * radius;
DBMS_OUTPUT.PUT_LINE('Circle area = ' || area_c);
area_r := length * width;
DBMS_OUTPUT.PUT_LINE('Rectangle area = ' || area_r);
area_s := length * length;
DBMS_OUTPUT.PUT_LINE('Square area = ' || area_s);
end;
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.PUT_LINE('sum of 1 to 100 is '||sum1);
end;
PL/SQL Examples
Write a PL/SQL program for inserting even numbers in EVEN table and odd number in ODD table from
number 1 to 50.
begin
for i in 1..50
loop
if mod(i,2) = 0 then
insert into EVEN values (i);
end if;
end loop;
for i in 1..50
loop
if mod(i,2)!= 0 then
insert into ODD values (i);
end if;
end loop;
end;
PL/SQL Examples
Write a PL/SQL block to print the given number is prime or not
declare
num number;
i number:=1;
c number:=0;
begin
num:=#
for i in 1..num
loop
if((mod(num,i))=0)
then
c:=c+1;
end if;
end loop;
if(c>2)
then
DBMS_OUTPUT.PUT_LINE(num||' not a prime');
else
DBMS_OUTPUT.PUT_LINE(num||' is prime');
end if;
end;
PL/SQL
%RowType
Variable Name TableName%RowType
acc account%RowType;
- This “acc” variable will have complete structure of the table account. Any column
of account table can be referred using “acc” variable
DECLARE
acc account%RowType;
BEGIN
select * into acc from account where acc_no=‘A001’;
DBMS_OUTPUT.PUT_LINE (acc.name); = “Patel Hiren”
DBMS_OUTPUT.PUT_LINE (acc.city); = “Mehsana”
DBMS_OUTPUT.PUT_LINE (acc.balance); = 50000
DBMS_OUTPUT.PUT_LINE (acc.loan_taken); = “YES”
END;
Cursor
 A cursor is a private set of records.
 A cursor is a temporary work area created in the system memory when a SQL
statement is executed. A cursor contains information on a select statement and
the rows of data accessed by it.
 This temporary work area is used to store the data retrieved from the database,
and manipulate this data. A cursor can hold more than one row, but can process
only one row at a time. The set of rows the cursor holds is called the active set.
 There are 2 types of Cursors:
1. Implicit Cursor: Created automatically for every query in SQL.
2. Explicit Cursor: Created manually by the programmer.
Cursor
Cursor Attributes
cursorname%ROWCOUNT Rows returned so far
cursorname%FOUND One or more rows retrieved
cursorname%NOTFOUND No rows found
cursorname%ISOPEN Is the cursor open
Cursor
Explicit Cursor
• Declare the cursor
• Open the cursor
• Fetch a row
• Test for end of cursor
• Close the cursor
Cursor
Explicit Cursor Example
DECLARE
CURSOR account_cursor IS SELECT * from account;
acc account%rowtype
BEGIN
DBMS_OUTPUT.PUT_LINE ('******************');
OPEN account_cursor;
FETCH account_cursor into acc;
WHILE account_cursor % Found
LOOP
DBMS_OUTPUT.PUT_LINE (acc.name);
DBMS_OUTPUT.PUT_LINE (acc.city);
DBMS_OUTPUT.PUT_LINE (acc.balance);
DBMS_OUTPUT.PUT_LINE (acc.loan_taken)
DBMS_OUTPUT.PUT_LINE ('******************');
FETCH account_cursor into acc;
END LOOP;
CLOSE account_cursor;
END;
Stored Procedure
 A program unit is a self-contained group of program statements that can be used within a
large program
 Stored PL/SQL program units are program units that other PL/SQL program can reference
and that other database users can use and execute.
 Can receive multiple input parameters and return multiple output values (or no output
values) and perform DML Commands
CREATE [OR REPLACE] PROCEDURE procedure_name [ (parameter
mod datatype [,parameter]) ]
IS
[local variable declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [procedure_name];
Stored Procedure
 The header section defines:
1. The procedure name (name should be unique )
2. The parameters that the procedure receives or delivers
(IN, OUT, IN OUT)
3. IS keyword: follows the parameters list
4. The local procedure variables
 Create or replace: instructs the DBMS to create the procedure if it does it exists, otherwise; it replaces the
existing one
 OR REPLACE clause is optional. But if omitted and a procedure exists with the same name, an error occurs
 Parameter name, mod and data type are enclosed in parentheses, each is separated by a comma.
 Parameter mod: describes how the procedure change the value. It can be:
1. IN: passed parameter is a Read only value. Cannot be changed by the procedure
2. OUT: write-only value. Always comes on the left side of an assignment statement
3. IN OUT: its value can be changed
Stored Procedure
EXAMPLE:
Create or replace procedure account_update
(
curr_acc_no IN varchar2,
curr_name IN varchar2,
curr_balance IN number
)
IS
BEGIN
update account
set balance = curr_balance
where
acc_no = curr_acc_no and
name = curr_name;
COMMIT;
END;
The Following Stored
Procedure updates the
balance of the account
for a given account
number and name of
the account.
Execute account_update(‘A001’,’Patel’,125000);
Command to
Execute the Store
Procedure
Function
 A function is similar to a procedure, except that it returns a single value.
 Functions can accept one, many, or no parameters, but a function must have a
return clause in the executable section of the function.
 The datatype of the return value must be declared in the header of the function.
 The syntax for creating a function is as follows:
CREATE [OR REPLACE] FUNCTION function_name
(parameter list)
RETURN datatype
IS
BEGIN
<body>
RETURN (return_value);
END;
Function
EXAMPLE:
Create or replace function account_det
(account_num varchar2)
RETURN varchar2
AS
acc_name varchar2(30);
BEGIN
select name into acc_name from
account where acc_no=account_num;
RETURN acc_name;
END;
The Following
Function will
fetch the name of
the account for a
given account
number.
DECLARE
acc_name VARCHAR2(30);
BEGIN
acc_name := account_det(&account_num);
DBMS_OUTPUT.PUT_LINE(acc_name);
END;
2 Ways to Execute the Function:
Select
account_det(‘A001’)
from account;
THANK YOU!!
www.paruluniversi
ty.ac.in

More Related Content

PPTX
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
KathanPatel49
 
PPT
chap 9 dbms.ppt
arjun431527
 
PPTX
BBarters_PL_SQL gives cdemo details.pptx
shailesh patil
 
PPTX
Cursors, triggers, procedures
Vaibhav Kathuria
 
PPT
lecture13.ppt
IrfanAkbar35
 
PDF
Sql tutorial
amitabros
 
PDF
sql notes Provideby AGN HUB Tech & It Solutions
mohanagn2244
 
PPT
Chapter09
sasa_eldoby
 
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
KathanPatel49
 
chap 9 dbms.ppt
arjun431527
 
BBarters_PL_SQL gives cdemo details.pptx
shailesh patil
 
Cursors, triggers, procedures
Vaibhav Kathuria
 
lecture13.ppt
IrfanAkbar35
 
Sql tutorial
amitabros
 
sql notes Provideby AGN HUB Tech & It Solutions
mohanagn2244
 
Chapter09
sasa_eldoby
 

Similar to DBMS UNIT 9.pptx.................................. (20)

PPTX
PL_SQL_1.pptx fvbxcfbhxdfgh .
RAMIROENRIQUERAMALLO
 
PPTX
PL_SQL - II.pptx
priyaprakash11
 
PDF
Dynamic websites lec3
Belal Arfa
 
PPTX
Oracle:Cursors
oracle content
 
PPTX
Oracle: Cursors
DataminingTools Inc
 
PPT
Triggers n Cursors.ppt
VADAPALLYPRAVEENKUMA1
 
PPT
10gplsqlslide-120704232925-phJKKJJKKJpapp01.ppt
Noorien3
 
PPTX
Cursors
Priyanka Yadav
 
PPT
Plsql
Mandeep Singh
 
PPTX
View
Pooja Dixit
 
PPTX
PostgreSQL Database Slides
metsarin
 
PPTX
Relational Database Language.pptx
Sheethal Aji Mani
 
PPT
Plsql
fika sweety
 
PPT
PL/SQL Stored Procedures And Cursors.ppt
sonaligaikwad281110
 
PPT
PLSQL (1).ppt
MadhuriAnaparthy
 
PPT
Chap 7
Karan Patil
 
PDF
Assignment#08
Sunita Milind Dol
 
PPT
PPT for Advanced Relational Database Management System
switipatel4
 
PL_SQL_1.pptx fvbxcfbhxdfgh .
RAMIROENRIQUERAMALLO
 
PL_SQL - II.pptx
priyaprakash11
 
Dynamic websites lec3
Belal Arfa
 
Oracle:Cursors
oracle content
 
Oracle: Cursors
DataminingTools Inc
 
Triggers n Cursors.ppt
VADAPALLYPRAVEENKUMA1
 
10gplsqlslide-120704232925-phJKKJJKKJpapp01.ppt
Noorien3
 
PostgreSQL Database Slides
metsarin
 
Relational Database Language.pptx
Sheethal Aji Mani
 
PL/SQL Stored Procedures And Cursors.ppt
sonaligaikwad281110
 
PLSQL (1).ppt
MadhuriAnaparthy
 
Chap 7
Karan Patil
 
Assignment#08
Sunita Milind Dol
 
PPT for Advanced Relational Database Management System
switipatel4
 
Ad

Recently uploaded (20)

PDF
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 
PPTX
IoT_Smart_Agriculture_Presentations.pptx
poojakumari696707
 
PDF
LEAP-1B presedntation xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
hatem173148
 
PPTX
MT Chapter 1.pptx- Magnetic particle testing
ABCAnyBodyCanRelax
 
PPTX
Civil Engineering Practices_BY Sh.JP Mishra 23.09.pptx
bineetmishra1990
 
PPTX
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
PDF
The Effect of Artifact Removal from EEG Signals on the Detection of Epileptic...
Partho Prosad
 
PPTX
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 
PDF
July 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
PDF
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
PPTX
Module2 Data Base Design- ER and NF.pptx
gomathisankariv2
 
PDF
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
PDF
Traditional Exams vs Continuous Assessment in Boarding Schools.pdf
The Asian School
 
PDF
Top 10 read articles In Managing Information Technology.pdf
IJMIT JOURNAL
 
PDF
Software Testing Tools - names and explanation
shruti533256
 
PDF
2025 Laurence Sigler - Advancing Decision Support. Content Management Ecommer...
Francisco Javier Mora Serrano
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PPTX
FUNDAMENTALS OF ELECTRIC VEHICLES UNIT-1
MikkiliSuresh
 
PPTX
Tunnel Ventilation System in Kanpur Metro
220105053
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 
IoT_Smart_Agriculture_Presentations.pptx
poojakumari696707
 
LEAP-1B presedntation xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
hatem173148
 
MT Chapter 1.pptx- Magnetic particle testing
ABCAnyBodyCanRelax
 
Civil Engineering Practices_BY Sh.JP Mishra 23.09.pptx
bineetmishra1990
 
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
The Effect of Artifact Removal from EEG Signals on the Detection of Epileptic...
Partho Prosad
 
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 
July 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
Module2 Data Base Design- ER and NF.pptx
gomathisankariv2
 
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
Traditional Exams vs Continuous Assessment in Boarding Schools.pdf
The Asian School
 
Top 10 read articles In Managing Information Technology.pdf
IJMIT JOURNAL
 
Software Testing Tools - names and explanation
shruti533256
 
2025 Laurence Sigler - Advancing Decision Support. Content Management Ecommer...
Francisco Javier Mora Serrano
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
FUNDAMENTALS OF ELECTRIC VEHICLES UNIT-1
MikkiliSuresh
 
Tunnel Ventilation System in Kanpur Metro
220105053
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
Ad

DBMS UNIT 9.pptx..................................

  • 1. Database Management System UNIT-9 PL/SQL Concepts Computer Science & Engineering Dr. Vishwanath PARUL INSTITUTE OF ENGINEERING & TECHNOLOGY FACULTY OF ENGINEERING & TECHNOLOGY PARUL UNIVERSITY
  • 4. Views 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 WHERE condition;
  • 5. Views For 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;
  • 6. Views 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;
  • 7. Views 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 ('Sales', 'Marketing');
  • 10. Views  The view is a virtual table. It does not physically exist. Rather, it is created by a query joining one or more tables.  A view contains rows and columns, just like a real table  The fields in a view are fields from one or more real tables in the database Creating an SQL VIEW Syntax: CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition;
  • 11. Views View Creation – Example 1. CREATE VIEW transaction_view AS SELECT acc_no, tr_date,amt from transaction; 2. Create view account_view AS SELECT a.acc_no,a.balance,l.loan_amt,l.interest_rate from account a, loan l where a.acc_no=l.acc_no and a.city=‘Ahmedabad’; The above views would create a virtual table based on the result set of the select statement. To show created views: 1. SELECT * FROM transaction_view; 2. SELECT * FROM account_view;
  • 12. Views 1. Create or Replace view account_view AS SELECT a.acc_no,a.balance,l.loan_amt,l.interest_rate, l.remaining_loan from account a, loan l where a.acc_no=l.acc_no and a.city=‘Vadodara’; Updating View You can modify the definition of a VIEW without dropping it by using the following syntax: CREATE OR REPLACE VIEW view_name AS SELECT columns FROM table WHERE predicates;
  • 13. Views Deleting View The syntax for dropping a VIEW : DROP VIEW view_name; View Drop - Example DROP VIEW transaction_view;
  • 14. Views Question: Can you update the data in an view? Answer : A view is created by joining one or more tables. When you update record(s) in a view, it updates the records in the underlying tables that make up the View. So, yes, you can update the data in View providing you have the proper privileges to the underlying tables. Question: Does the SQL View exist if the table is dropped from the database? Answer: Yes, View continues to exist even after one of the tables (that the SQL View is based on) is dropped from the database. However, if you try to query the View after the table has been dropped, you will receive a message indicating that the View has errors.
  • 15. Views
  • 16. Trigger  A trigger is a block structure which is fired when a DML statements like Insert, Delete, Update is executed on a database table. A trigger is triggered automatically when an associated DML statement is executed. 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) ;
  • 17. Trigger Creating Trigger 1. CREATE TRIGGER deleted_details BEFORE DELETE on loan FOR EACH ROW 2. CREATE TRIGGER inserted_details after insert on transaction FOR EACH ROW
  • 18. Trigger Creating Trigger 3. CREATE TRIGGER updated_details BEFORE UPDATE on account FOR EACH ROW when name=‘Patel Hiren’; Deleting Trigger Drop trigger inserted_details on transaction;
  • 19. Trigger  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;
  • 20. PL/SQL Procedural Language – SQL: An extension to SQL with design features of programming languages (procedural and object oriented)
  • 21. PL/SQL PL/SQL BLOCK STRUCTURE DECLARE (optional) - variable declarations BEGIN (required) - SQL statements - PL/SQL statements or sub-blocks EXCEPTION (optional) - actions to perform when errors occur END; (required)
  • 22. PL/SQL  There are 2 types of Datatypes: 1. Scalar (Char, Varchar2, Date and Number) 2. Composite (%rowtype)  All Variables required to be used in the program must be declared before their use. Variable names cannot be table, column and keyword names.  Assignment Operator is denoted as “:=” and each statement of PL/SQL ends with “;”.  Dbms_Output.Put_Line() is used for printing Output.  &Variable_Name :Variable Name is use to take input from the user.
  • 23. PL/SQL 1. IF …THEN…ELSE IF <condition> THEN <Code> ELSEIF <condition> THEN <Code> ELSE <Code> ENDIF; 2. CASE… CASE WHEN VARIABLE = VALUE THEN <Code> WHEN VARIABLE = VALUE THEN <Code> ELSE <Code> END CASE;  Conditional Statements
  • 24. PL/SQL 1. Simple Loop Loop <Code> Exit when <Cond> End Loop; 2. While Loop While <Condition> Loop <Code> End Loop;  Types of Loops 3. For Loop FOR <Variable> IN <Min> .. <Max> Loop <Code> End Loop; 4. For Loop FOR <Variable> IN REVERSE <Min> .. <Max> Loop <Code> End Loop;
  • 25. 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;
  • 26. 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_OUTPUT.PUT_LINE(‘x is greater than y'); else DBMS_OUTPUT.PUT_LINE(‘ y is greater than x'); end if; end;
  • 27. PL/SQL Examples Write a PL/SQL block to find area of rectangle, square and circle declare area_c number(6, 2) ; radius number(1) := 3 ; area_r number(6) ; area_s number(6) ; length number(2) := 5 ; width number(2) := 4 ; pi constant number(3, 2) := 3.14; begin area_c := pi * radius * radius; DBMS_OUTPUT.PUT_LINE('Circle area = ' || area_c); area_r := length * width; DBMS_OUTPUT.PUT_LINE('Rectangle area = ' || area_r); area_s := length * length; DBMS_OUTPUT.PUT_LINE('Square area = ' || area_s); end;
  • 28. 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.PUT_LINE('sum of 1 to 100 is '||sum1); end;
  • 29. PL/SQL Examples Write a PL/SQL program for inserting even numbers in EVEN table and odd number in ODD table from number 1 to 50. begin for i in 1..50 loop if mod(i,2) = 0 then insert into EVEN values (i); end if; end loop; for i in 1..50 loop if mod(i,2)!= 0 then insert into ODD values (i); end if; end loop; end;
  • 30. PL/SQL Examples Write a PL/SQL block to print the given number is prime or not declare num number; i number:=1; c number:=0; begin num:=# for i in 1..num loop if((mod(num,i))=0) then c:=c+1; end if; end loop; if(c>2) then DBMS_OUTPUT.PUT_LINE(num||' not a prime'); else DBMS_OUTPUT.PUT_LINE(num||' is prime'); end if; end;
  • 31. PL/SQL %RowType Variable Name TableName%RowType acc account%RowType; - This “acc” variable will have complete structure of the table account. Any column of account table can be referred using “acc” variable DECLARE acc account%RowType; BEGIN select * into acc from account where acc_no=‘A001’; DBMS_OUTPUT.PUT_LINE (acc.name); = “Patel Hiren” DBMS_OUTPUT.PUT_LINE (acc.city); = “Mehsana” DBMS_OUTPUT.PUT_LINE (acc.balance); = 50000 DBMS_OUTPUT.PUT_LINE (acc.loan_taken); = “YES” END;
  • 32. Cursor  A cursor is a private set of records.  A cursor is a temporary work area created in the system memory when a SQL statement is executed. A cursor contains information on a select statement and the rows of data accessed by it.  This temporary work area is used to store the data retrieved from the database, and manipulate this data. A cursor can hold more than one row, but can process only one row at a time. The set of rows the cursor holds is called the active set.  There are 2 types of Cursors: 1. Implicit Cursor: Created automatically for every query in SQL. 2. Explicit Cursor: Created manually by the programmer.
  • 33. Cursor Cursor Attributes cursorname%ROWCOUNT Rows returned so far cursorname%FOUND One or more rows retrieved cursorname%NOTFOUND No rows found cursorname%ISOPEN Is the cursor open
  • 34. Cursor Explicit Cursor • Declare the cursor • Open the cursor • Fetch a row • Test for end of cursor • Close the cursor
  • 35. Cursor Explicit Cursor Example DECLARE CURSOR account_cursor IS SELECT * from account; acc account%rowtype BEGIN DBMS_OUTPUT.PUT_LINE ('******************'); OPEN account_cursor; FETCH account_cursor into acc; WHILE account_cursor % Found LOOP DBMS_OUTPUT.PUT_LINE (acc.name); DBMS_OUTPUT.PUT_LINE (acc.city); DBMS_OUTPUT.PUT_LINE (acc.balance); DBMS_OUTPUT.PUT_LINE (acc.loan_taken) DBMS_OUTPUT.PUT_LINE ('******************'); FETCH account_cursor into acc; END LOOP; CLOSE account_cursor; END;
  • 36. Stored Procedure  A program unit is a self-contained group of program statements that can be used within a large program  Stored PL/SQL program units are program units that other PL/SQL program can reference and that other database users can use and execute.  Can receive multiple input parameters and return multiple output values (or no output values) and perform DML Commands CREATE [OR REPLACE] PROCEDURE procedure_name [ (parameter mod datatype [,parameter]) ] IS [local variable declaration_section] BEGIN executable_section [EXCEPTION exception_section] END [procedure_name];
  • 37. Stored Procedure  The header section defines: 1. The procedure name (name should be unique ) 2. The parameters that the procedure receives or delivers (IN, OUT, IN OUT) 3. IS keyword: follows the parameters list 4. The local procedure variables  Create or replace: instructs the DBMS to create the procedure if it does it exists, otherwise; it replaces the existing one  OR REPLACE clause is optional. But if omitted and a procedure exists with the same name, an error occurs  Parameter name, mod and data type are enclosed in parentheses, each is separated by a comma.  Parameter mod: describes how the procedure change the value. It can be: 1. IN: passed parameter is a Read only value. Cannot be changed by the procedure 2. OUT: write-only value. Always comes on the left side of an assignment statement 3. IN OUT: its value can be changed
  • 38. Stored Procedure EXAMPLE: Create or replace procedure account_update ( curr_acc_no IN varchar2, curr_name IN varchar2, curr_balance IN number ) IS BEGIN update account set balance = curr_balance where acc_no = curr_acc_no and name = curr_name; COMMIT; END; The Following Stored Procedure updates the balance of the account for a given account number and name of the account. Execute account_update(‘A001’,’Patel’,125000); Command to Execute the Store Procedure
  • 39. Function  A function is similar to a procedure, except that it returns a single value.  Functions can accept one, many, or no parameters, but a function must have a return clause in the executable section of the function.  The datatype of the return value must be declared in the header of the function.  The syntax for creating a function is as follows: CREATE [OR REPLACE] FUNCTION function_name (parameter list) RETURN datatype IS BEGIN <body> RETURN (return_value); END;
  • 40. Function EXAMPLE: Create or replace function account_det (account_num varchar2) RETURN varchar2 AS acc_name varchar2(30); BEGIN select name into acc_name from account where acc_no=account_num; RETURN acc_name; END; The Following Function will fetch the name of the account for a given account number. DECLARE acc_name VARCHAR2(30); BEGIN acc_name := account_det(&account_num); DBMS_OUTPUT.PUT_LINE(acc_name); END; 2 Ways to Execute the Function: Select account_det(‘A001’) from account;