SlideShare a Scribd company logo
1
PL/SQL programming
Procedures and Cursors
Lecture 1
Akhtar Ali
2
SQL refresher
 Basic commands
 SELECT, INSERT, DELETE, UPDATE
 Always remember to state the table(s) you
are selecting data from
 Join tables using keys (Primary / Foreign)
 Filter data wherever possible
 Procedures are different from scripts
3
SQL scripts
 Set of commands to run in sequence.
 Stored as a text file (e.g. using Notepad) on a disk
and not in the data dictionary. It is accessed by
file name
 Executed using @ or Start.
Script called:
Create_User.sql
Executed by:
SQL> @Create_User.sql
4
Procedures in SQL
 Block of SQL statements stored in the Data dictionary
and called by applications or from SQL* plus prompt.
 Usually used to implement application/business logic.
 When called all code within a procedure is executed
(unlike packages).
 Action takes place on server side not client.
 Do not return value to calling program.
 Not available in Oracle 6 or older.
 Aid security as DBA will grant access to procedures not
tables, therefore users can not access tables unless via a
procedure.
5
Building a procedure
1. Create or replace command
2. Type of object to be created
3. Name of object
4. Any variables accessed or imported
5. Declare local variables
6. Write body of the object (code)
7. End procedure declaration
6
1. Create or replace
command
2. Object to be
created
3. Name of object
4. Any variables
accessed or
imported
5. Declare local
variables
6. Body
7. End procedure
declaration
Create or replace procedure inflation_rise (inf_rate in
number)
Begin
update employee
set salary = salary + (salary * inf_rate / 100);
commit;
End;
This procedure is called inflation_rise and used a
variable accessed as inf_rate which is a number,
this is passed in when the procedure is used. It
simply updates the salary by the rate of inflation.
7
Compiling and executing
procedures
 Like any program the code needs to be compiled.
 @inflation_rise will compile the procedure and make it
available in the database
 Execute inflation_rise(2) will cause the procedure to
execute, with 2 as an inflation rate.
 Remember to compile a procedure once it has been
amended.
 For ease of use, it is easiest to write procedures in
notepad, store as script files, and then run them, this
means that they can be easily edited – also you will have
a copy if required
8
Example
CREATE OR REPLACE PROCEDURE validate_customer ( v_cust IN VARCHAR ) AS
v_count NUMBER;
BEGIN
SELECT COUNT(*) INTO V_COUNT
FROM customer
WHERE c_id = v_cust;
IF v_count > 0 THEN
DBMS_OUTPUT.PUT_LINE( 'customer valid');
ELSE
DBMS_OUTPUT.PUT_LINE('customer not recognised');
END IF;
END;
Any variables
passed into
procedure
Local variables used
by procedure
SQL
9
Cursors in SQL
 Enables users to loop around a selection of
data.
 Stores data selected from a query in a temp
area for use when opened.
 Use complex actions which would not be
feasible in standard SQL selection queries
10
Syntax for Cursors
 Declared as a variable in the same way as
standard variables
 Identified as cursor type
 SQL included
 E.g. Cursor cur_emp is
Select emp_id, surname name, grade, salary
From employee
Where salary>30000;
11
Cursors
 A cursor is a temp store of data.
 The data is populated when the cursor is opened.
 Once opened the data must be moved from the
temp area to a local variable to be used by the
program. These variables must be populated in
the same order that the data is held in the cursor.
 The data is looped round till an exit clause is
reached.
12
Active set
Active set
Current row
Current row
Cursor
7369 SMITH CLERK
7566 JONES MANAGER
7788 SCOTT ANALYST
7876 ADAMS CLERK
7902 FORD ANALYST
Cursor Functions
Cursor Functions
13
Controlling Cursor
Controlling Cursor
• Create a
Create a
named
named
SQL area
SQL area
DECLARE
DECLARE
• Identify
Identify
the active
the active
set
set
OPEN
OPEN
• Load the
Load the
current
current
row into
row into
variables
variables
FETCH
FETCH
• Test for
Test for
existing
existing
rows
rows
EMPTY?
• Return to
Return to
FETCH if
FETCH if
rows
rows
found
found
No
No
• Release
Release
the active
the active
set
set
CLOSE
CLOSE
Yes
Yes
14
Controlling Cursor…
Controlling Cursor…
Open the cursor.
Open the cursor.
Cursor
Cursor
Pointer
Pointer
Fetch a row from the cursor.
Fetch a row from the cursor.
Cursor
Cursor
Pointer
Pointer
Continue until empty.
Continue until empty.
Cursor
Cursor
Pointer
Pointer
Close the cursor.
Close the cursor.
Cursor
Cursor
15
Cursor Attributes
Cursor Attributes
Attribute Type Description
%ISOPEN Boolean Evaluates to TRUE if the cursor
is open
%NOTFOUND Boolean Evaluates to TRUE if the most
recent fetch does not return a row
%FOUND Boolean Evaluates to TRUE if the most
recent fetch returns a row;
complement of %NOTFOUND
%ROWCOUNT Number Evaluates to the total number of
rows returned so far
Obtain status information about a cursor.
16
Create or replace procedure proc_test as
v_empid number;
Cursor cur_sample is
Select empid from employee
where grade > 4;
Begin
open cur_sample;
loop
fetch cur_sample into v_empid;
exit when cur_sample%notfound;
update employee
set salary = salary + 500
where empid = v_empid;
end loop;
End;
Open cursor for use.
Loops round each value
returned by the cursor
Place the value from the
cursor into the variable
v_empid
Stop
when not
more
records
are found
25463
12245
55983
12524
98543
Data
returned
by
cursor
Declare
Cursor
17
Use of conditions
 If statements can be used
If <condition> Then
…..
End if;
 Example
 Remember to end the if statement and use of indented code
will make it easier to debug!
. . .
IF v_ename = 'MILLER' THEN
v_job := 'SALESMAN';
v_deptno := 35;
v_new_comm := sal * 0.20;
END IF;
. . .
18
The %ISOPEN Attribute
 Fetch rows only when the cursor is open.
 Use the %ISOPEN cursor attribute before
performing a fetch to test whether the cursor is
open.
 Example
IF NOT cur_sample%ISOPEN THEN
OPEN cur_sample;
END IF;
LOOP
FETCH cur_sample...
19
DECLARE
CURSOR emp_cursor IS
SELECT empno, ename
FROM emp;
emp_record emp_cursor%ROWTYPE;
BEGIN
OPEN emp_cursor;
LOOP
FETCH emp_cursor INTO emp_record;
...
Cursors and Records
Cursors and Records
 Process the rows of the active set
conveniently by fetching values into a
PL/SQL RECORD.
 Example
20
Cursor FOR Loops
Cursor FOR Loops
FOR record_name IN cursor_name LOOP
statement1;
statement2;
. . .
END LOOP;
Syntax
The cursor FOR loop is a shortcut to process
cursors.
Implicitly opens, fetches, and closes cursor.
The record is implicitly declared.
21
Cursor FOR Loops: An Example
Cursor FOR Loops: An Example
 Retrieve employees one by one until no more are
Retrieve employees one by one until no more are
left.
left.
 Example
Example
DECLARE
CURSOR emp_cursor IS
SELECT ename, deptno
FROM emp;
BEGIN
FOR emp_record IN emp_cursor LOOP
-- implicit open and implicit fetch occur
IF emp_record.deptno = 30 THEN
...
END LOOP; -- implicit close occurs
END;

More Related Content

PPT
Procedures andcursors
PPT
PPTX
PL/SQL___________________________________
PPTX
PL_SQL - II.pptx
PPTX
PPT
DOCX
Cursor
DOCX
Cursor
Procedures andcursors
PL/SQL___________________________________
PL_SQL - II.pptx
Cursor
Cursor

Similar to PL/SQL Stored Procedures And Cursors.ppt (20)

PPTX
Unit 3(rdbms)
PPTX
Unit 3(rdbms)
PDF
Cursors
PPTX
Stored procedures by thanveer danish melayi
PPTX
PL_SQL_1.pptx fvbxcfbhxdfgh .
PDF
Lecture Notes Unit5 chapter19 Cursor in Pl/SQL
PPT
Intro to tsql unit 13
PPTX
plsql tutorialhub....
PPT
PLplsql study aboutmsnsjskakajsjslajwvsbsns
PPTX
BBarters_PL_SQL gives cdemo details.pptx
PPTX
Day 6.pptx
DOCX
Conditional Control
PPT
PPTX
PPT
PPT
SQL- Introduction to PL/SQL
PPTX
PPT Lecture 2.3.4 Cursortttttttttttttttttttttttttttttttts.pptx
PPT
Cursors in oracle
PPT
Pl sql guide
PPT
Unit 3(rdbms)
Unit 3(rdbms)
Cursors
Stored procedures by thanveer danish melayi
PL_SQL_1.pptx fvbxcfbhxdfgh .
Lecture Notes Unit5 chapter19 Cursor in Pl/SQL
Intro to tsql unit 13
plsql tutorialhub....
PLplsql study aboutmsnsjskakajsjslajwvsbsns
BBarters_PL_SQL gives cdemo details.pptx
Day 6.pptx
Conditional Control
SQL- Introduction to PL/SQL
PPT Lecture 2.3.4 Cursortttttttttttttttttttttttttttttttts.pptx
Cursors in oracle
Pl sql guide
Ad

Recently uploaded (20)

PPTX
bas. eng. economics group 4 presentation 1.pptx
PPTX
Geodesy 1.pptx...............................................
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PPTX
Construction Project Organization Group 2.pptx
PPTX
UNIT 4 Total Quality Management .pptx
PPTX
Welding lecture in detail for understanding
PDF
Digital Logic Computer Design lecture notes
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
Sustainable Sites - Green Building Construction
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PDF
PPT on Performance Review to get promotions
PPTX
Internet of Things (IOT) - A guide to understanding
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PDF
Well-logging-methods_new................
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PDF
composite construction of structures.pdf
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
bas. eng. economics group 4 presentation 1.pptx
Geodesy 1.pptx...............................................
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
Construction Project Organization Group 2.pptx
UNIT 4 Total Quality Management .pptx
Welding lecture in detail for understanding
Digital Logic Computer Design lecture notes
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Sustainable Sites - Green Building Construction
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
Model Code of Practice - Construction Work - 21102022 .pdf
PPT on Performance Review to get promotions
Internet of Things (IOT) - A guide to understanding
Automation-in-Manufacturing-Chapter-Introduction.pdf
Well-logging-methods_new................
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Foundation to blockchain - A guide to Blockchain Tech
composite construction of structures.pdf
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
Ad

PL/SQL Stored Procedures And Cursors.ppt

  • 1. 1 PL/SQL programming Procedures and Cursors Lecture 1 Akhtar Ali
  • 2. 2 SQL refresher  Basic commands  SELECT, INSERT, DELETE, UPDATE  Always remember to state the table(s) you are selecting data from  Join tables using keys (Primary / Foreign)  Filter data wherever possible  Procedures are different from scripts
  • 3. 3 SQL scripts  Set of commands to run in sequence.  Stored as a text file (e.g. using Notepad) on a disk and not in the data dictionary. It is accessed by file name  Executed using @ or Start. Script called: Create_User.sql Executed by: SQL> @Create_User.sql
  • 4. 4 Procedures in SQL  Block of SQL statements stored in the Data dictionary and called by applications or from SQL* plus prompt.  Usually used to implement application/business logic.  When called all code within a procedure is executed (unlike packages).  Action takes place on server side not client.  Do not return value to calling program.  Not available in Oracle 6 or older.  Aid security as DBA will grant access to procedures not tables, therefore users can not access tables unless via a procedure.
  • 5. 5 Building a procedure 1. Create or replace command 2. Type of object to be created 3. Name of object 4. Any variables accessed or imported 5. Declare local variables 6. Write body of the object (code) 7. End procedure declaration
  • 6. 6 1. Create or replace command 2. Object to be created 3. Name of object 4. Any variables accessed or imported 5. Declare local variables 6. Body 7. End procedure declaration Create or replace procedure inflation_rise (inf_rate in number) Begin update employee set salary = salary + (salary * inf_rate / 100); commit; End; This procedure is called inflation_rise and used a variable accessed as inf_rate which is a number, this is passed in when the procedure is used. It simply updates the salary by the rate of inflation.
  • 7. 7 Compiling and executing procedures  Like any program the code needs to be compiled.  @inflation_rise will compile the procedure and make it available in the database  Execute inflation_rise(2) will cause the procedure to execute, with 2 as an inflation rate.  Remember to compile a procedure once it has been amended.  For ease of use, it is easiest to write procedures in notepad, store as script files, and then run them, this means that they can be easily edited – also you will have a copy if required
  • 8. 8 Example CREATE OR REPLACE PROCEDURE validate_customer ( v_cust IN VARCHAR ) AS v_count NUMBER; BEGIN SELECT COUNT(*) INTO V_COUNT FROM customer WHERE c_id = v_cust; IF v_count > 0 THEN DBMS_OUTPUT.PUT_LINE( 'customer valid'); ELSE DBMS_OUTPUT.PUT_LINE('customer not recognised'); END IF; END; Any variables passed into procedure Local variables used by procedure SQL
  • 9. 9 Cursors in SQL  Enables users to loop around a selection of data.  Stores data selected from a query in a temp area for use when opened.  Use complex actions which would not be feasible in standard SQL selection queries
  • 10. 10 Syntax for Cursors  Declared as a variable in the same way as standard variables  Identified as cursor type  SQL included  E.g. Cursor cur_emp is Select emp_id, surname name, grade, salary From employee Where salary>30000;
  • 11. 11 Cursors  A cursor is a temp store of data.  The data is populated when the cursor is opened.  Once opened the data must be moved from the temp area to a local variable to be used by the program. These variables must be populated in the same order that the data is held in the cursor.  The data is looped round till an exit clause is reached.
  • 12. 12 Active set Active set Current row Current row Cursor 7369 SMITH CLERK 7566 JONES MANAGER 7788 SCOTT ANALYST 7876 ADAMS CLERK 7902 FORD ANALYST Cursor Functions Cursor Functions
  • 13. 13 Controlling Cursor Controlling Cursor • Create a Create a named named SQL area SQL area DECLARE DECLARE • Identify Identify the active the active set set OPEN OPEN • Load the Load the current current row into row into variables variables FETCH FETCH • Test for Test for existing existing rows rows EMPTY? • Return to Return to FETCH if FETCH if rows rows found found No No • Release Release the active the active set set CLOSE CLOSE Yes Yes
  • 14. 14 Controlling Cursor… Controlling Cursor… Open the cursor. Open the cursor. Cursor Cursor Pointer Pointer Fetch a row from the cursor. Fetch a row from the cursor. Cursor Cursor Pointer Pointer Continue until empty. Continue until empty. Cursor Cursor Pointer Pointer Close the cursor. Close the cursor. Cursor Cursor
  • 15. 15 Cursor Attributes Cursor Attributes Attribute Type Description %ISOPEN Boolean Evaluates to TRUE if the cursor is open %NOTFOUND Boolean Evaluates to TRUE if the most recent fetch does not return a row %FOUND Boolean Evaluates to TRUE if the most recent fetch returns a row; complement of %NOTFOUND %ROWCOUNT Number Evaluates to the total number of rows returned so far Obtain status information about a cursor.
  • 16. 16 Create or replace procedure proc_test as v_empid number; Cursor cur_sample is Select empid from employee where grade > 4; Begin open cur_sample; loop fetch cur_sample into v_empid; exit when cur_sample%notfound; update employee set salary = salary + 500 where empid = v_empid; end loop; End; Open cursor for use. Loops round each value returned by the cursor Place the value from the cursor into the variable v_empid Stop when not more records are found 25463 12245 55983 12524 98543 Data returned by cursor Declare Cursor
  • 17. 17 Use of conditions  If statements can be used If <condition> Then ….. End if;  Example  Remember to end the if statement and use of indented code will make it easier to debug! . . . IF v_ename = 'MILLER' THEN v_job := 'SALESMAN'; v_deptno := 35; v_new_comm := sal * 0.20; END IF; . . .
  • 18. 18 The %ISOPEN Attribute  Fetch rows only when the cursor is open.  Use the %ISOPEN cursor attribute before performing a fetch to test whether the cursor is open.  Example IF NOT cur_sample%ISOPEN THEN OPEN cur_sample; END IF; LOOP FETCH cur_sample...
  • 19. 19 DECLARE CURSOR emp_cursor IS SELECT empno, ename FROM emp; emp_record emp_cursor%ROWTYPE; BEGIN OPEN emp_cursor; LOOP FETCH emp_cursor INTO emp_record; ... Cursors and Records Cursors and Records  Process the rows of the active set conveniently by fetching values into a PL/SQL RECORD.  Example
  • 20. 20 Cursor FOR Loops Cursor FOR Loops FOR record_name IN cursor_name LOOP statement1; statement2; . . . END LOOP; Syntax The cursor FOR loop is a shortcut to process cursors. Implicitly opens, fetches, and closes cursor. The record is implicitly declared.
  • 21. 21 Cursor FOR Loops: An Example Cursor FOR Loops: An Example  Retrieve employees one by one until no more are Retrieve employees one by one until no more are left. left.  Example Example DECLARE CURSOR emp_cursor IS SELECT ename, deptno FROM emp; BEGIN FOR emp_record IN emp_cursor LOOP -- implicit open and implicit fetch occur IF emp_record.deptno = 30 THEN ... END LOOP; -- implicit close occurs END;