SlideShare a Scribd company logo
1 of 23
1
PL/SQL programming
Procedures and Cursors
By,
Lakshmi.S,
Assistant Professor in Dept. of Computer Science,
Sri Adi Chunchanagiri Women’s College, Cumbum.
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 regrade is true;
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
Current rowCursor
7369 SMITH CLERK
7566 JONES MANAGER
7788 SCOTT ANALYST
7876 ADAMS CLERK
7902 FORD ANALYST
Cursor Functions
13
Controlling Cursor
• Create a
named
SQL area
DECLARE
• Identify
the active
set
OPEN
• Load the
current
row into
variables
FETCH
• Test for
existing
rows
EMPTY?
• Return to
FETCH if
rows
found
No
• Release
the active
set
CLOSE
Yes
14
Controlling Cursor…
Open the cursor.
Cursor
Pointer
Fetch a row from the cursor.
Cursor
Pointer
Continue until empty.
Cursor
Pointer
Close the cursor.
Cursor
15
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
Notepad file called:
Create_procedure.sql
1) Open SQL*Plus and logon
2) At the prompt enter:
@create_procedure
You will get a prompt which should say ‘procedure created’
3) To run the procedure enter:
Execute proc_test
4) If you check your data you should now find that the procedure has run successfully
18
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;
. . .
19
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...
20
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
 Process the rows of the active set
conveniently by fetching values into a
PL/SQL RECORD.
 Example
21
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.
22
Cursor FOR Loops: An Example
 Retrieve employees one by one until no more are
left.
 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;
23
Seminar exercise
 The purpose of this exercise is to create a procedure which, when
evoked, will increase the salary of a grade by £500 or £1000
depending on the level of the grade. You will need to populate the
table first with a minimum of 10 entries, the empgrade value should
be between 1 and 5, and the idea is the higher the grade the higher the
manager. There is a script for this on the BlackBoard/homepage.
 Once you have done this you should compile the code this will then
indicate if the procedure has compiled or not. If compilation is
unsuccessful entering the command show errors will list any
problems with the code. To run the procedure you type execute
<procedure name> at the SQL prompt.

More Related Content

What's hot

Exception handling in plsql
Exception handling in plsqlException handling in plsql
Exception handling in plsqlArun Sial
 
Programming in Oracle with PL/SQL
Programming in Oracle with PL/SQLProgramming in Oracle with PL/SQL
Programming in Oracle with PL/SQLlubna19
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sqlÑirmal Tatiwal
 
Oracle PL/SQL Bulk binds
Oracle PL/SQL Bulk bindsOracle PL/SQL Bulk binds
Oracle PL/SQL Bulk bindsScott Wesley
 
Oracle - Program with PL/SQL - Lession 06
Oracle - Program with PL/SQL - Lession 06Oracle - Program with PL/SQL - Lession 06
Oracle - Program with PL/SQL - Lession 06Thuan Nguyen
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts Bharat Kalia
 
Procedures/functions of rdbms
Procedures/functions of rdbmsProcedures/functions of rdbms
Procedures/functions of rdbmsjain.pralabh
 
Oracle - Program with PL/SQL - Lession 18
Oracle - Program with PL/SQL - Lession 18Oracle - Program with PL/SQL - Lession 18
Oracle - Program with PL/SQL - Lession 18Thuan Nguyen
 
Oracle PL/SQL exception handling
Oracle PL/SQL exception handlingOracle PL/SQL exception handling
Oracle PL/SQL exception handlingSmitha Padmanabhan
 
Oracle - Program with PL/SQL - Lession 16
Oracle - Program with PL/SQL - Lession 16Oracle - Program with PL/SQL - Lession 16
Oracle - Program with PL/SQL - Lession 16Thuan Nguyen
 

What's hot (19)

Exception handling in plsql
Exception handling in plsqlException handling in plsql
Exception handling in plsql
 
Cursors
CursorsCursors
Cursors
 
Programming in Oracle with PL/SQL
Programming in Oracle with PL/SQLProgramming in Oracle with PL/SQL
Programming in Oracle with PL/SQL
 
Oracle: Procedures
Oracle: ProceduresOracle: Procedures
Oracle: Procedures
 
Oracle: Control Structures
Oracle: Control StructuresOracle: Control Structures
Oracle: Control Structures
 
My sql cursors
My sql cursorsMy sql cursors
My sql cursors
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sql
 
PLSQL Advanced
PLSQL AdvancedPLSQL Advanced
PLSQL Advanced
 
Plsql
PlsqlPlsql
Plsql
 
Pl sql
Pl sqlPl sql
Pl sql
 
Oracle: Cursors
Oracle: CursorsOracle: Cursors
Oracle: Cursors
 
Oracle PL/SQL Bulk binds
Oracle PL/SQL Bulk bindsOracle PL/SQL Bulk binds
Oracle PL/SQL Bulk binds
 
Oracle - Program with PL/SQL - Lession 06
Oracle - Program with PL/SQL - Lession 06Oracle - Program with PL/SQL - Lession 06
Oracle - Program with PL/SQL - Lession 06
 
Pl sql guide
Pl sql guidePl sql guide
Pl sql guide
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
 
Procedures/functions of rdbms
Procedures/functions of rdbmsProcedures/functions of rdbms
Procedures/functions of rdbms
 
Oracle - Program with PL/SQL - Lession 18
Oracle - Program with PL/SQL - Lession 18Oracle - Program with PL/SQL - Lession 18
Oracle - Program with PL/SQL - Lession 18
 
Oracle PL/SQL exception handling
Oracle PL/SQL exception handlingOracle PL/SQL exception handling
Oracle PL/SQL exception handling
 
Oracle - Program with PL/SQL - Lession 16
Oracle - Program with PL/SQL - Lession 16Oracle - Program with PL/SQL - Lession 16
Oracle - Program with PL/SQL - Lession 16
 

Similar to Procedures andcursors

Similar to Procedures andcursors (20)

Day 6.pptx
Day 6.pptxDay 6.pptx
Day 6.pptx
 
PL_SQL - II.pptx
PL_SQL - II.pptxPL_SQL - II.pptx
PL_SQL - II.pptx
 
plsql tutorialhub....
plsql tutorialhub....plsql tutorialhub....
plsql tutorialhub....
 
Oracle:Cursors
Oracle:CursorsOracle:Cursors
Oracle:Cursors
 
3963066 pl-sql-notes-only
3963066 pl-sql-notes-only3963066 pl-sql-notes-only
3963066 pl-sql-notes-only
 
PLSQLmy Updated (1).pptx
PLSQLmy Updated (1).pptxPLSQLmy Updated (1).pptx
PLSQLmy Updated (1).pptx
 
Relational Database Management System
Relational Database Management SystemRelational Database Management System
Relational Database Management System
 
Cursors.ppt
Cursors.pptCursors.ppt
Cursors.ppt
 
Oracle: Procedures
Oracle: ProceduresOracle: Procedures
Oracle: Procedures
 
PLSQL Tutorial
PLSQL TutorialPLSQL Tutorial
PLSQL Tutorial
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standards
 
L9 l10 server side programming
L9 l10  server side programmingL9 l10  server side programming
L9 l10 server side programming
 
Sql Functions And Procedures
Sql Functions And ProceduresSql Functions And Procedures
Sql Functions And Procedures
 
MS SQLSERVER:Sql Functions And Procedures
MS SQLSERVER:Sql Functions And ProceduresMS SQLSERVER:Sql Functions And Procedures
MS SQLSERVER:Sql Functions And Procedures
 
MS SQL SERVER: Sql Functions And Procedures
MS SQL SERVER: Sql Functions And ProceduresMS SQL SERVER: Sql Functions And Procedures
MS SQL SERVER: Sql Functions And Procedures
 
SQL / PL
SQL / PLSQL / PL
SQL / PL
 
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals I
 
Module04
Module04Module04
Module04
 
Performance tuning
Performance tuningPerformance tuning
Performance tuning
 
4 cursors
4 cursors4 cursors
4 cursors
 

More from LakshmiSamivel

Greedy Algorithm for Computer Science.ppt
Greedy Algorithm for Computer Science.pptGreedy Algorithm for Computer Science.ppt
Greedy Algorithm for Computer Science.pptLakshmiSamivel
 
General methodin Data Structure for UG.pptx
General methodin Data Structure for UG.pptxGeneral methodin Data Structure for UG.pptx
General methodin Data Structure for UG.pptxLakshmiSamivel
 
DIVIDE AND CONQUERMETHOD IN DATASTRUCTURE.pptx
DIVIDE AND CONQUERMETHOD IN DATASTRUCTURE.pptxDIVIDE AND CONQUERMETHOD IN DATASTRUCTURE.pptx
DIVIDE AND CONQUERMETHOD IN DATASTRUCTURE.pptxLakshmiSamivel
 
DataSructure-Time and Space Complexity.pptx
DataSructure-Time and Space Complexity.pptxDataSructure-Time and Space Complexity.pptx
DataSructure-Time and Space Complexity.pptxLakshmiSamivel
 
Basic Queue Operation in DataStructure.pptx
Basic Queue Operation in DataStructure.pptxBasic Queue Operation in DataStructure.pptx
Basic Queue Operation in DataStructure.pptxLakshmiSamivel
 
Classification of datastructure.ppt
Classification of datastructure.pptClassification of datastructure.ppt
Classification of datastructure.pptLakshmiSamivel
 
Computer network notes
Computer network notesComputer network notes
Computer network notesLakshmiSamivel
 

More from LakshmiSamivel (15)

Greedy Algorithm for Computer Science.ppt
Greedy Algorithm for Computer Science.pptGreedy Algorithm for Computer Science.ppt
Greedy Algorithm for Computer Science.ppt
 
General methodin Data Structure for UG.pptx
General methodin Data Structure for UG.pptxGeneral methodin Data Structure for UG.pptx
General methodin Data Structure for UG.pptx
 
DIVIDE AND CONQUERMETHOD IN DATASTRUCTURE.pptx
DIVIDE AND CONQUERMETHOD IN DATASTRUCTURE.pptxDIVIDE AND CONQUERMETHOD IN DATASTRUCTURE.pptx
DIVIDE AND CONQUERMETHOD IN DATASTRUCTURE.pptx
 
DataSructure-Time and Space Complexity.pptx
DataSructure-Time and Space Complexity.pptxDataSructure-Time and Space Complexity.pptx
DataSructure-Time and Space Complexity.pptx
 
Basic Queue Operation in DataStructure.pptx
Basic Queue Operation in DataStructure.pptxBasic Queue Operation in DataStructure.pptx
Basic Queue Operation in DataStructure.pptx
 
Presentation DM.pptx
Presentation DM.pptxPresentation DM.pptx
Presentation DM.pptx
 
Dos.pptx
Dos.pptxDos.pptx
Dos.pptx
 
Formatting tags
Formatting tagsFormatting tags
Formatting tags
 
Classification of datastructure.ppt
Classification of datastructure.pptClassification of datastructure.ppt
Classification of datastructure.ppt
 
Top down parsing
Top down parsingTop down parsing
Top down parsing
 
Semaphore
Semaphore Semaphore
Semaphore
 
Firewall ppt
Firewall pptFirewall ppt
Firewall ppt
 
View
ViewView
View
 
Computer network notes
Computer network notesComputer network notes
Computer network notes
 
OsI reference model
OsI reference modelOsI reference model
OsI reference model
 

Recently uploaded

Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxsqpmdrvczh
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayMakMakNepo
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........LeaCamillePacle
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxLigayaBacuel1
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 

Recently uploaded (20)

Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up Friday
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptx
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 

Procedures andcursors

  • 1. 1 PL/SQL programming Procedures and Cursors By, Lakshmi.S, Assistant Professor in Dept. of Computer Science, Sri Adi Chunchanagiri Women’s College, Cumbum.
  • 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 regrade is true;
  • 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 Current rowCursor 7369 SMITH CLERK 7566 JONES MANAGER 7788 SCOTT ANALYST 7876 ADAMS CLERK 7902 FORD ANALYST Cursor Functions
  • 13. 13 Controlling Cursor • Create a named SQL area DECLARE • Identify the active set OPEN • Load the current row into variables FETCH • Test for existing rows EMPTY? • Return to FETCH if rows found No • Release the active set CLOSE Yes
  • 14. 14 Controlling Cursor… Open the cursor. Cursor Pointer Fetch a row from the cursor. Cursor Pointer Continue until empty. Cursor Pointer Close the cursor. Cursor
  • 15. 15 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 Notepad file called: Create_procedure.sql 1) Open SQL*Plus and logon 2) At the prompt enter: @create_procedure You will get a prompt which should say ‘procedure created’ 3) To run the procedure enter: Execute proc_test 4) If you check your data you should now find that the procedure has run successfully
  • 18. 18 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; . . .
  • 19. 19 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...
  • 20. 20 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  Process the rows of the active set conveniently by fetching values into a PL/SQL RECORD.  Example
  • 21. 21 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.
  • 22. 22 Cursor FOR Loops: An Example  Retrieve employees one by one until no more are left.  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;
  • 23. 23 Seminar exercise  The purpose of this exercise is to create a procedure which, when evoked, will increase the salary of a grade by £500 or £1000 depending on the level of the grade. You will need to populate the table first with a minimum of 10 entries, the empgrade value should be between 1 and 5, and the idea is the higher the grade the higher the manager. There is a script for this on the BlackBoard/homepage.  Once you have done this you should compile the code this will then indicate if the procedure has compiled or not. If compilation is unsuccessful entering the command show errors will list any problems with the code. To run the procedure you type execute <procedure name> at the SQL prompt.