SlideShare a Scribd company logo
Database Procedural Programming
PL/SQL and Embedded SQL
By,
B.Nivegeetha
I-Msc cs.
Nadar Saraswathi College of Arts and Science,
Theni.
PL/SQL
 PL/SQL is Oracle's procedural language exte
nsion to SQL.
 PL/SQL combines SQL with the procedural fu
nctionality of a structured programming langu
age, such as IF ... THEN, WHILE, and LOOP.
 The PL/SQL engine used to define, compile,
and execute PL/SQL program units.
 A component of many Oracle products, includ
ing Oracle Server.
Procedures and Functions
 A set of SQL and PL/SQL statements grouped together as a
unit (block) to solve a specific problem or perform a set of re
lated tasks.
 An anonymous block is a PL/SQL block that appears within
your application and it is not named or stored in the databas
e. In many applications, PL/SQL blocks can appear whereve
r SQL statements can appear.
 A stored procedure is a PL/SQL block that Oracle stores in t
he database and can be called by name from an application.
 Functions always return a single value to the caller; procedu
res do not return values to the caller.
 Packages are groups of procedures and functions.
Procedure PL/SQL Example
CREATE PROCEDURE credit_labmark (sno NUMBER, cno CHAR, cre
dit NUMBER) AS
old_mark NUMBER;
new_mark NUMBER;
BEGIN
SELECT labmark INTO old_mark FROM enrol
WHERE studno = sno and courseno = cno FOR UPDATE OF la
bmark;
new_ mark := old_ mark + credit;
UPDATE enrol SET labmark = new_mark
WHERE studno = sno and courseno = cno;
COMMIT;
EXCEPTION
WHEN NO_DATA_FOUND THEN
INSERT INTO enrol(studno, courseno, labmark, exammark)
VALUES(sno, cno, credit, null);
WHEN OTHERS THEN ROLLBACK;
END credit_labmark;
PL/SQL sta
tement.
SQL statement.
Locks enrol
EXECUTE credit_lab
mark
(99234,’CS2312’,20)
Function
create function get_lab_mark(sno number, cno char)
return number
as f_lab_mark number;
no_mark exception;
begin
select labmark
into f_lab_mark from enrol
where studno = sno and courseno = cno;
if f_lab_mark is null
then raise no_mark;
else return(f_lab_mark);
end if
exception
when no_mark then …..return(null);
end;
Stored Procedures
Created in a user's schema and s
tored, centrally, in compiled for
m in the database as a named
object that can be:
 interactively executed by a user
using a tool like SQL*Plus
 called explicitly in the code of a d
atabase application, such as an
Oracle Forms or a Pre compiler a
pplication, or in the code of anoth
er procedure or trigger
When PL/SQL is not stored in the
database, applications can sen
d blocks of PL/SQL to the data
base rather than individual SQ
L statements  reducing netw
ork traffic. .
Program code
.
.
Program code
.
HIRE_EMP(…);
.
Program code
Program code
.
.
Program code
.
HIRE_EMP(…);
.
Program code
Program code
.
.
Program code
.
HIRE_EMP(…);
.
Program code HIRE_EMP(…)
BEGIN
.
.
END;
Database Applications
Stored
Procedure
Database
Architecture
Procedure
Begin
Procedurecall
Procedurecall
SQL
Procedurecall
SQL
End;
Procedural
Statement
Executor
PL/SQL Engine
SQL Statement
Executor
SQL
Database
Program code
Program code
Procedure call
Program code
Program code
SGA
Oracle Server
Database
Application
Benefits of Stored Procedures I
 Security
 Control data access through procedures and functions.
 E.g. grant users access to a procedure that updates a ta
ble, but not grant them access to the table itself.
 Performance
The information is sent only once between database and
application and thereafter invoked when it is used.
 Network traffic is reduced compared with issuing individu
al SQL statements or sending the text of an entire PL/S
QL block
 A procedure's compiled form is readily available in the d
atabase, so no compilation is required at execution time.
 The procedure might be cached
Benefits of Procedures II
 Memory Allocation
 Stored procedures take advantage of the shared memory capabiliti
es of Oracle
 Only a single copy of the procedure needs to be loaded into memor
y for execution by multiple users.
 Productivity
 By designing applications around a common set of procedures, you
can avoid redundant coding and increase your productivity.
 Procedures can be written to insert, update, or delete rows from a t
able and then called by any application without rewriting the SQL st
atements necessary to accomplish these tasks.
 If the methods of data management change, only the procedures n
eed to be modified, not all of the applications that use the procedur
es.
Benefits of Procedures III
 Integrity
 Stored procedures improve the integrity and consistenc
y of your applications. By developing all of your applicati
ons around a common group of procedures, you can re
duce the likelihood of committing coding errors.
 You can test a procedure or function to guarantee that it
returns an accurate result and, once it is verified, reuse i
t in any number of applications without testing it again.
 If the data structures referenced by the procedure are al
tered in any way, only the procedure needs to be recom
piled; applications that call the procedure do not necess
arily require any modifications.
Packages
 A method of encapsulating and storing related proced
ures, functions, variables, cursors and other package
constructs together as a unit in the database for conti
nued use as a unit.
 Similar to standalone procedures and functions, pack
aged procedures and functions can be called explicitl
y by applications or users.
 Organize routines
 Increased functionality (e.g. global package variab
les can be declared and used by any procedure in
the package) and
 Increased performance (e.g. all objects of the pac
kage are parsed, compiled, and loaded into memo
ry once).
Package manage tasks in database
 Database applications expli
citly call packaged procedu
res as necessary.
 After being granted the priv
ileges for the package, a us
er can explicitly execute an
y of the procedures contain
ed in it.
 EXECUTE marks_mgmt. cr
edit_labmark(99234,’CS23
12’,20)
 Packages offer several dev
elopment and performance
advantages over standalon
e stored procedures;
Program code
.
EMP_MGMT.FIRE_EMP(…);
Program code
.
EMP_MGMT.HIRE_EMP(…);
.
Program code
Program code
.
EMP_MGMT.HIRE_EMP(…);
Program code
.
EMP_MGMT.SAL_RAISE(…);
.
Program code
FIRE_EMP(…)
BEGIN
.
.
END;
HIRE_EMP(…)
BEGIN
.
.
END;
SAL_RAISE(…)
BEGIN
.
.
END;
Database
Benefits of Packages
 Encapsulation of related procedures and variables providing:
 Better organization during the development process and for granti
ng privileges
 Declaration of public and private procedures, variables, constants, an
d cursors
 Better performance
 An entire package is loaded into memory when a procedure withi
n the package is called for the first time in one operation, as oppo
sed to the separate loads required for standalone procedures. W
hen calls to related packaged procedures occur, no disk I/O is ne
cessary to execute the compiled code already in memory.
 A package body can be replaced and recompiled without affectin
g the specification. Objects that reference a package's constructs
(always via the specification) need not be recompiled unless the
package specification is also replaced. Unnecessary recompilatio
ns can be minimized, so in less impact on overall database perfor
mance.
Triggers vs Procedures and Packages
 Triggers are similar to stored procedures. A trigger ca
n include SQL and PL/SQL statements to execute as
a unit and can invoke stored procedures. Triggers are
stored in the database separate from their associated
tables.
 Procedures and triggers differ in the way that they ar
e invoked.
 A procedure is explicitly executed by a user, applic
ation, or trigger.
 Triggers (one or more) are implicitly fired (execute
d) by Oracle when a triggering INSERT, UPDATE,
or DELETE statement is issued, no matter which u
ser is connected or which application is being use
d.
Retrieval: Impedance Mismatch
 What happens when the query returns several rows? T
he host variables can only hold one value.
 Oracle will only pass the first row returned by the query
to the PL/SQL block (or host language program).
 Re-executing the SELECT operation will only run the q
uery again and so the first row will be selected again.
 Different type systems
 Different execution models
Cursors
 When a query returns multiple rows a cursor
must be declared to process each row return
ed by the query and to keep track of which ro
w is currently being processed.
 The rows returned by a query are stored in an
area called the Active Set.
 A cursor can be thought of as pointing to a ro
w in the active set.
Cursors and RetrievalPROCEDURE apply_marks IS
CURSOR marks_cursor IS
SELECT sno, cno, kind, amount FROM marks
WHERE status = 'Pending' ORDER BY time_tag FOR UPDATE OF
marks;
BEGIN
FOR marks IN marks_cursor LOOP /* implicit open and f
etch */
new_status := ’Accepted';
IF marks.kind = ’L' THEN
credit_labmark(marks.sno, marks.cno, marks.amount);
ELSIF trans.kind = ’E' THEN
credit_exammark(marks.sno, marks.cno, marks.amoun
t);
ELSE new_status := 'Rejected';
END IF;
UPDATE marks SET status = new_status
WHERE CURRENT OF marks_cursor;
END LOOP; COMMIT;
END apply_marks;
Embedded SQL
 SQL statements placed within a program. The source
program is called the host program, and the language
in which it is written is called the host language
 You can execute any SQL statement using embedde
d SQL statements just as if you were in SQL*Plus.
 CREATE, ALTER and DROP database tables
 SELECT, INSERT, UPDATE and DELETE rows of
data
 COMMIT transactions (make any changes to the d
atabase permanent)
Embedded SQL Statements
 Embedded SQL statements incorporate DDL, DML, and tran
saction control statements within a procedural language pro
gram. They are used with the Oracle pre-compilers, e.g. Pro
*C.
 Embedded SQL statements enable you to
 define, allocate, and release cursors (DECLARE CURSO
R, OPEN, CLOSE)
 declare a database name and connect to Oracle (DECLA
RE DATABASE, CONNECT)
 assign variable names (DECLARE STATEMENT)
 initialize descriptors (DESCRIBE)
 specify how error and warning conditions are handled (W
HENEVER)
 parse and execute SQL statements (PREPARE, EXECU
TE, EXECUTE IMMEDIATE)
 retrieve data from the database (FETCH).
Executable and Declarative Statements
 Embedded SQL includes all the interactive SQL statements pl
us others that allow you to transfer data between Oracle and
a host program. There are two types of embedded SQL state
ments:
 Executable:
 used to connect to Oracle, to define, query and manipulate
Oracle data, to control access to Oracle data and to proces
s transactions. They can be placed wherever host-languag
e executable statements can be placed.
 Declarative:
 do not operate on SQL data. Use them to declare Oracle o
bjects, communication areas and SQL variables which will
be used by Oracle and your host program. They can be pla
ced wherever host-language declarations can be placed.
Binding Variables
 A host variable is prefixed with a colon (:) in SQL statements bu
t must not be prefixed with a colon in C statements.
EXEC SQL BEGIN DECLARE SECTION;
INT sno;
VARCHAR cno[5];
INT labmark;
EXEC SQL END DECLARE SECTION;
…
EXEC SQL SELECT labmark INTO :labmark F
ROM enrol
WHERE studno = :sno and courseno = :cno
 The case of the host variable is significant when referencing the
m.
database attribute
host variable
SELECT
EXEC SQL SELECT courseno, subject
INTO :courseno, :subject
FROM course
WHERE courseno = :menu_selection;
Attributes in the staff table.
INTO clause specifies the host variables
which will hold the values of the attribute
s returned.
Host variable used to supply the WHERE claus
e with a value to base the query on.
In SQL*Plus this would be done using a literal
value. Pro*C allows variables to be used to sp
ecify a value. Host variables used in this way
must contain a value before the SELECT state
ment is used.
Example
Declare any host variables
EXEC SQL BEGIN DECLARE SECTION;
VARCHAR studname[21];
VARCHAR cno[5];
INT labmark;
VARCHAR o_connect_uid[18];
EXEC SQL END DECLARE SECTION;
Include the error handlers
EXEC SQL INCLUDE sqlca;
EXEC SQL INCLUDE oraca;
Log on procedure
void Oracle_Connect(void) {
(void)strcpy(o_connect_uid.arr,"/@t:ora-srv:mucs7");
o_connect_uid.len = strlen(o_connect_uid.arr);
EXEC SQL CONNECT :o_connect_uid;
}
Connect to Oracle Server and Do the Query
main()
{ EXEC SQL WHENEVER SQLERROR DO sqlerror()
EXEC ORACLE OPTION (ORACA=YES);
oraca.orastxtf = 1; Oracle_Connect(); printf("Connected to O
raclen");
 Cursor for query
EXEC SQL DECLARE studcursor CURSOR FOR
SELECT s.name, e.courseno, e.labmark,
FROM student s, enrol e WHERE s.studno = e.studno;
 Do the query
EXEC SQL OPEN studcursor; printf(”Name/Course/LabMark
n");
 Loop to fetch rows
while (sqlca.sqlcode == 0) {
EXEC SQL FETCH studcursor
INTO :studname, :cno, :labmark
printf("%s,%s,%d", studname, cno, labmark);
}
printf("%ld rows selected.n",sqlca.sqlerrd[2]);
EXEC SQL CLOSE studcursor;
EXEC SQL COMMIT WORK RELEASE;
exit(1);}
Examples of Packages and Procedures
Create Package Specification
create package marks_mgmt (null) as
max_mark CONSTANT NUMBER := 100.00;
PROCEDURE apply_marks;
PROCEDURE enter_marks(sno number,cno char
, kind char, credit number);
end marks_mgmt;
Create Package Body
CREATE PACKAGE BODY marks_mgmt AS
new_status CHAR(20); /* Global variable to record status of tra
nsaction being applied. Used for update in enter_marks. */
PROCEDURE do_journal_entry (sno NUMBER, cno CHAR, kind CH
AR) IS
/* Records a journal entry for each marks credit applied by the enter_
marks procedure. */
BEGIN
INSERT INTO journal
VALUES (sno, cno, kind, sysdate);
IF kind = ’L' THEN new_status := ’Lab credit';
ELSIF kind = ’E' THEN new_status := ’Exam credit';
ELSE new_status := 'New enrolment';
END IF;
END do_journal_entry;
Create Package Body I
CREATE PROCEDURE credit_labmark (sno NUMBER, cno CHAR,
credit NUMBER) AS
old_mark NUMBER; new_mark NUMBER;
mark_overflow EXCEPTION;
BEGIN
SELECT labmark INTO old_mark FROM enrol
WHERE studno = sno and courseno = cno
FOR UPDATE OF labmark;
new_ mark := old_ mark + credit;
IF new_mark <= max_mark THEN
UPDATE enrol SET labmark = new_mark
WHERE studno = sno and courseno = cno ;
do_journal_entry(sno, cno, L);
ELSE RAISE mark_overflow
ENDIF;
Create Package Body II
EXCEPTION
WHEN NO_DATA_FOUND THEN
/* Create new enrolment if not found */
INSERT INTO enrol (studno, courseno, labmark, exammark)
VALUES(sno, cno, credit, null);
do_journal_entry(sno, cno, 'N');
WHEN mark_overflow THEN
new_status := ’Mark Overflow’;
WHEN OTHERS THEN
/* Return other errors to application */
new_status := 'Error: ' || SQLERRM(SQLCODE);
END credit_labmark;
CREATE PROCEDURE credit_exammark (sno NUMBER, cno CHAR, cr
edit NUMBER) AS…
END credit_exammark;
PROCEDURE apply_marks IS …. complete shortly...
END apply_marks;
PROCEDURE enter_marks(sno NUMBER, cno CHAR, kind CHAR
, credit NUMBER) IS
/* A new mark is always put into this 'queue' before b
eing applied to the specified enrolment instance by
the APPLY_MARKS procedure. */
BEGIN
INSERT INTO marks
VALUES (sno, cno, kind, amount, 'Pending', sysdate);
COMMIT;
END enter_marks;
END marks_mgmt ; /* end package */
Create Package Body
Additional material
An error handling procedure
void sqlerror(void)
{ int o_errl;
int len = 550;
char o_err[550];
EXEC SQL WHENEVER SQLERROR CONTINUE;
sqlca.sqlerrm.sqlerrmc[sqlca.sqlerrm.sqlerrml] = NULL;
printf("nOracle Error:n%s", sqlca.sqlerrm.sqlerrmc);
oraca.orastxt.orastxtc[oraca.orastxt.orastxtl] = NULL;
printf("ERROR statement:%sn", oraca.orastxt.orastxtc);
sqlglm(o_err, &len, &oerrl);
o_err[o_errl] = NULL;
printf("ERROR Details: %sn",o_err);
oraca.orasfnm.orasfnmc[oraca.orasfnm.orasfnml] = NULL;
printf("ERROR at line %ld in %sn", oraca.oraslnr,oraca
.orasfnm.orasfnmc);
EXEC SQL ROLLBACK WORK RELEASE;
Ad

More Related Content

What's hot (20)

PLSQL Tutorial
PLSQL TutorialPLSQL Tutorial
PLSQL Tutorial
Quang Minh Đoàn
 
SQL
SQLSQL
SQL
kaushal123
 
05 Creating Stored Procedures
05 Creating Stored Procedures05 Creating Stored Procedures
05 Creating Stored Procedures
rehaniltifat
 
pl/sql Procedure
pl/sql Procedurepl/sql Procedure
pl/sql Procedure
Pooja Dixit
 
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals I
Nick Buytaert
 
Pl sql-ch2
Pl sql-ch2Pl sql-ch2
Pl sql-ch2
Mukesh Tekwani
 
Pl sql-ch1
Pl sql-ch1Pl sql-ch1
Pl sql-ch1
Mukesh Tekwani
 
ORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERSORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERS
mohdoracle
 
Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
Tony Jambu   (obscure) tools of the trade for tuning oracle sq lsTony Jambu   (obscure) tools of the trade for tuning oracle sq ls
Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
InSync Conference
 
09 Managing Dependencies
09 Managing Dependencies09 Managing Dependencies
09 Managing Dependencies
rehaniltifat
 
Cursors, triggers, procedures
Cursors, triggers, proceduresCursors, triggers, procedures
Cursors, triggers, procedures
Vaibhav Kathuria
 
Chapter8 pl sql
Chapter8 pl sqlChapter8 pl sql
Chapter8 pl sql
Jafar Nesargi
 
11 Understanding and Influencing the PL/SQL Compilar
11 Understanding and Influencing the PL/SQL Compilar11 Understanding and Influencing the PL/SQL Compilar
11 Understanding and Influencing the PL/SQL Compilar
rehaniltifat
 
02 Writing Executable Statments
02 Writing Executable Statments02 Writing Executable Statments
02 Writing Executable Statments
rehaniltifat
 
ORACLE PL SQL
ORACLE PL SQLORACLE PL SQL
ORACLE PL SQL
Srinath Maharana
 
Advanced plsql mock_assessment
Advanced plsql mock_assessmentAdvanced plsql mock_assessment
Advanced plsql mock_assessment
Saurabh K. Gupta
 
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
rehaniltifat
 
06 Using More Package Concepts
06 Using More Package Concepts06 Using More Package Concepts
06 Using More Package Concepts
rehaniltifat
 
PL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics CoveredPL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics Covered
Danish Mehraj
 
Plsql les04
Plsql les04Plsql les04
Plsql les04
sasa_eldoby
 
05 Creating Stored Procedures
05 Creating Stored Procedures05 Creating Stored Procedures
05 Creating Stored Procedures
rehaniltifat
 
pl/sql Procedure
pl/sql Procedurepl/sql Procedure
pl/sql Procedure
Pooja Dixit
 
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals I
Nick Buytaert
 
ORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERSORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERS
mohdoracle
 
Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
Tony Jambu   (obscure) tools of the trade for tuning oracle sq lsTony Jambu   (obscure) tools of the trade for tuning oracle sq ls
Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
InSync Conference
 
09 Managing Dependencies
09 Managing Dependencies09 Managing Dependencies
09 Managing Dependencies
rehaniltifat
 
Cursors, triggers, procedures
Cursors, triggers, proceduresCursors, triggers, procedures
Cursors, triggers, procedures
Vaibhav Kathuria
 
11 Understanding and Influencing the PL/SQL Compilar
11 Understanding and Influencing the PL/SQL Compilar11 Understanding and Influencing the PL/SQL Compilar
11 Understanding and Influencing the PL/SQL Compilar
rehaniltifat
 
02 Writing Executable Statments
02 Writing Executable Statments02 Writing Executable Statments
02 Writing Executable Statments
rehaniltifat
 
Advanced plsql mock_assessment
Advanced plsql mock_assessmentAdvanced plsql mock_assessment
Advanced plsql mock_assessment
Saurabh K. Gupta
 
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
rehaniltifat
 
06 Using More Package Concepts
06 Using More Package Concepts06 Using More Package Concepts
06 Using More Package Concepts
rehaniltifat
 
PL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics CoveredPL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics Covered
Danish Mehraj
 

Similar to Relational Database Management System (20)

What does PL_SQL stand for and what is the functioning of PL_SQL.docx
What does PL_SQL stand for and what is the functioning of PL_SQL.docxWhat does PL_SQL stand for and what is the functioning of PL_SQL.docx
What does PL_SQL stand for and what is the functioning of PL_SQL.docx
shivanikaale214
 
Oracle DBA interview_questions
Oracle DBA interview_questionsOracle DBA interview_questions
Oracle DBA interview_questions
Naveen P
 
PROCEDURAL LANGUAGE/ STRUCTURED QUERY LANGUAGE.pdf
PROCEDURAL LANGUAGE/ STRUCTURED QUERY LANGUAGE.pdfPROCEDURAL LANGUAGE/ STRUCTURED QUERY LANGUAGE.pdf
PROCEDURAL LANGUAGE/ STRUCTURED QUERY LANGUAGE.pdf
rajeswaria21
 
Oracle db subprograms
Oracle db subprogramsOracle db subprograms
Oracle db subprograms
Simon Huang
 
Passing java arrays in oracle stored procedure from mule esb flow
Passing java arrays in oracle stored procedure from mule esb flowPassing java arrays in oracle stored procedure from mule esb flow
Passing java arrays in oracle stored procedure from mule esb flow
Priyobroto Ghosh (Mule ESB Certified)
 
Oracle RI ETL process overview.
Oracle RI ETL process overview.Oracle RI ETL process overview.
Oracle RI ETL process overview.
Puneet Kala
 
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
Alex Zaballa
 
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
Alex Zaballa
 
Using SQL Plan Management for Performance Testing
Using SQL Plan Management for Performance TestingUsing SQL Plan Management for Performance Testing
Using SQL Plan Management for Performance Testing
Maris Elsins
 
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrjPLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
KathanPatel49
 
Unit 3
Unit 3Unit 3
Unit 3
Abha Damani
 
Lecture 3.2_Subprogrammm - Function.pptx
Lecture 3.2_Subprogrammm - Function.pptxLecture 3.2_Subprogrammm - Function.pptx
Lecture 3.2_Subprogrammm - Function.pptx
pproychd
 
Lecture 3.2_Subprogrammm - Function.pptx
Lecture 3.2_Subprogrammm - Function.pptxLecture 3.2_Subprogrammm - Function.pptx
Lecture 3.2_Subprogrammm - Function.pptx
pproychd
 
Chapter09
Chapter09Chapter09
Chapter09
sasa_eldoby
 
Store procedures
Store proceduresStore procedures
Store procedures
Farzan Wadood
 
chapter 1.pdfbbbbbbbbbbbbbbbbbbbbbbbbbb
chapter  1.pdfbbbbbbbbbbbbbbbbbbbbbbbbbbchapter  1.pdfbbbbbbbbbbbbbbbbbbbbbbbbbb
chapter 1.pdfbbbbbbbbbbbbbbbbbbbbbbbbbb
hhhhhcccc25
 
Oracle: Procedures
Oracle: ProceduresOracle: Procedures
Oracle: Procedures
DataminingTools Inc
 
Oracle: Procedures
Oracle: ProceduresOracle: Procedures
Oracle: Procedures
oracle content
 
Overview of query evaluation
Overview of query evaluationOverview of query evaluation
Overview of query evaluation
avniS
 
Procedures andcursors
Procedures andcursorsProcedures andcursors
Procedures andcursors
LakshmiSamivel
 
What does PL_SQL stand for and what is the functioning of PL_SQL.docx
What does PL_SQL stand for and what is the functioning of PL_SQL.docxWhat does PL_SQL stand for and what is the functioning of PL_SQL.docx
What does PL_SQL stand for and what is the functioning of PL_SQL.docx
shivanikaale214
 
Oracle DBA interview_questions
Oracle DBA interview_questionsOracle DBA interview_questions
Oracle DBA interview_questions
Naveen P
 
PROCEDURAL LANGUAGE/ STRUCTURED QUERY LANGUAGE.pdf
PROCEDURAL LANGUAGE/ STRUCTURED QUERY LANGUAGE.pdfPROCEDURAL LANGUAGE/ STRUCTURED QUERY LANGUAGE.pdf
PROCEDURAL LANGUAGE/ STRUCTURED QUERY LANGUAGE.pdf
rajeswaria21
 
Oracle db subprograms
Oracle db subprogramsOracle db subprograms
Oracle db subprograms
Simon Huang
 
Oracle RI ETL process overview.
Oracle RI ETL process overview.Oracle RI ETL process overview.
Oracle RI ETL process overview.
Puneet Kala
 
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
Alex Zaballa
 
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
OOW16 - Oracle Database 12c - The Best Oracle Database 12c New Features for D...
Alex Zaballa
 
Using SQL Plan Management for Performance Testing
Using SQL Plan Management for Performance TestingUsing SQL Plan Management for Performance Testing
Using SQL Plan Management for Performance Testing
Maris Elsins
 
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrjPLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
KathanPatel49
 
Lecture 3.2_Subprogrammm - Function.pptx
Lecture 3.2_Subprogrammm - Function.pptxLecture 3.2_Subprogrammm - Function.pptx
Lecture 3.2_Subprogrammm - Function.pptx
pproychd
 
Lecture 3.2_Subprogrammm - Function.pptx
Lecture 3.2_Subprogrammm - Function.pptxLecture 3.2_Subprogrammm - Function.pptx
Lecture 3.2_Subprogrammm - Function.pptx
pproychd
 
chapter 1.pdfbbbbbbbbbbbbbbbbbbbbbbbbbb
chapter  1.pdfbbbbbbbbbbbbbbbbbbbbbbbbbbchapter  1.pdfbbbbbbbbbbbbbbbbbbbbbbbbbb
chapter 1.pdfbbbbbbbbbbbbbbbbbbbbbbbbbb
hhhhhcccc25
 
Overview of query evaluation
Overview of query evaluationOverview of query evaluation
Overview of query evaluation
avniS
 
Ad

More from sweetysweety8 (20)

Artificial neural network
Artificial neural networkArtificial neural network
Artificial neural network
sweetysweety8
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
sweetysweety8
 
Software engineering
Software engineeringSoftware engineering
Software engineering
sweetysweety8
 
Software engineering
Software engineeringSoftware engineering
Software engineering
sweetysweety8
 
WEB PROGRAMMING ANALYSIS
WEB PROGRAMMING ANALYSISWEB PROGRAMMING ANALYSIS
WEB PROGRAMMING ANALYSIS
sweetysweety8
 
Software engineering
Software engineeringSoftware engineering
Software engineering
sweetysweety8
 
Software engineering
Software engineeringSoftware engineering
Software engineering
sweetysweety8
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
sweetysweety8
 
WEB PROGRAMMING ANALYSIS
WEB PROGRAMMING ANALYSISWEB PROGRAMMING ANALYSIS
WEB PROGRAMMING ANALYSIS
sweetysweety8
 
WEB PROGRAMMING
WEB PROGRAMMINGWEB PROGRAMMING
WEB PROGRAMMING
sweetysweety8
 
Bigdata
BigdataBigdata
Bigdata
sweetysweety8
 
BIG DATA ANALYTICS
BIG DATA ANALYTICSBIG DATA ANALYTICS
BIG DATA ANALYTICS
sweetysweety8
 
BIG DATA ANALYTICS
BIG DATA ANALYTICSBIG DATA ANALYTICS
BIG DATA ANALYTICS
sweetysweety8
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
sweetysweety8
 
WEB PROGRAMMING
WEB PROGRAMMINGWEB PROGRAMMING
WEB PROGRAMMING
sweetysweety8
 
BIG DATA ANALYTICS
BIG DATA ANALYTICSBIG DATA ANALYTICS
BIG DATA ANALYTICS
sweetysweety8
 
Data mining
Data miningData mining
Data mining
sweetysweety8
 
Operating System
Operating SystemOperating System
Operating System
sweetysweety8
 
Relational Database Management System
Relational Database Management SystemRelational Database Management System
Relational Database Management System
sweetysweety8
 
Relational Database Management System
Relational Database Management SystemRelational Database Management System
Relational Database Management System
sweetysweety8
 
Ad

Recently uploaded (20)

Effects of physical activity, exercise and sedentary behaviors to
Effects of physical activity, exercise and sedentary behaviors toEffects of physical activity, exercise and sedentary behaviors to
Effects of physical activity, exercise and sedentary behaviors to
DancanNyabuto
 
Reflections on an ngo peace conference in zimbabwe
Reflections on an ngo peace conference in zimbabweReflections on an ngo peace conference in zimbabwe
Reflections on an ngo peace conference in zimbabwe
jujuaw05
 
A Bot Identification Model and Tool Based on GitHub Activity Sequences
A Bot Identification Model and Tool Based on GitHub Activity SequencesA Bot Identification Model and Tool Based on GitHub Activity Sequences
A Bot Identification Model and Tool Based on GitHub Activity Sequences
natarajan8993
 
ICSE 2025 Keynote: Software Sustainability and its Engineering: How far have ...
ICSE 2025 Keynote: Software Sustainability and its Engineering: How far have ...ICSE 2025 Keynote: Software Sustainability and its Engineering: How far have ...
ICSE 2025 Keynote: Software Sustainability and its Engineering: How far have ...
patricialago3459
 
Bidding World Conference 2027 - NSGF Mexico.pdf
Bidding World Conference 2027 - NSGF Mexico.pdfBidding World Conference 2027 - NSGF Mexico.pdf
Bidding World Conference 2027 - NSGF Mexico.pdf
ISGF - International Scout and Guide Fellowship
 
Profit Growth Drivers for Small Business.pdf
Profit Growth Drivers for Small Business.pdfProfit Growth Drivers for Small Business.pdf
Profit Growth Drivers for Small Business.pdf
TheodoreHawkins
 
THE SEXUAL HARASSMENT OF WOMAN AT WORKPLACE (PREVENTION, PROHIBITION & REDRES...
THE SEXUAL HARASSMENT OF WOMAN AT WORKPLACE (PREVENTION, PROHIBITION & REDRES...THE SEXUAL HARASSMENT OF WOMAN AT WORKPLACE (PREVENTION, PROHIBITION & REDRES...
THE SEXUAL HARASSMENT OF WOMAN AT WORKPLACE (PREVENTION, PROHIBITION & REDRES...
ASHISHKUMAR504404
 
The Business Dynamics of Quick Commerce.pdf
The Business Dynamics of Quick Commerce.pdfThe Business Dynamics of Quick Commerce.pdf
The Business Dynamics of Quick Commerce.pdf
RDinuRao
 
Bidding World Conference 2027 - Ghana.pptx
Bidding World Conference 2027 - Ghana.pptxBidding World Conference 2027 - Ghana.pptx
Bidding World Conference 2027 - Ghana.pptx
ISGF - International Scout and Guide Fellowship
 
Basic.pptxsksdjsdjdvkfvfvfvfvfvfvfvfvfvvvv
Basic.pptxsksdjsdjdvkfvfvfvfvfvfvfvfvfvvvvBasic.pptxsksdjsdjdvkfvfvfvfvfvfvfvfvfvvvv
Basic.pptxsksdjsdjdvkfvfvfvfvfvfvfvfvfvvvv
hkthmrz42n
 
fundamentals of communicationclass notes.pptx
fundamentals of communicationclass notes.pptxfundamentals of communicationclass notes.pptx
fundamentals of communicationclass notes.pptx
Sunkod
 
THE SEXUAL HARASSMENT OF WOMAN AT WORKPLACE (PREVENTION, PROHIBITION & REDRES...
THE SEXUAL HARASSMENT OF WOMAN AT WORKPLACE (PREVENTION, PROHIBITION & REDRES...THE SEXUAL HARASSMENT OF WOMAN AT WORKPLACE (PREVENTION, PROHIBITION & REDRES...
THE SEXUAL HARASSMENT OF WOMAN AT WORKPLACE (PREVENTION, PROHIBITION & REDRES...
ASHISHKUMAR504404
 
cardiovascular outcome in trial of new antidiabetic drugs
cardiovascular outcome in trial of new antidiabetic drugscardiovascular outcome in trial of new antidiabetic drugs
cardiovascular outcome in trial of new antidiabetic drugs
Mohammed Ahmed Bamashmos
 
Speech 3-A Vision for Tomorrow for GE2025
Speech 3-A Vision for Tomorrow for GE2025Speech 3-A Vision for Tomorrow for GE2025
Speech 3-A Vision for Tomorrow for GE2025
Noraini Yunus
 
816111728-IELTS-WRITING test óft-PPT.pptx
816111728-IELTS-WRITING test óft-PPT.pptx816111728-IELTS-WRITING test óft-PPT.pptx
816111728-IELTS-WRITING test óft-PPT.pptx
787mianahmad
 
Setup & Implementation of OutSystems Cloud Connector ODC
Setup & Implementation of OutSystems Cloud Connector ODCSetup & Implementation of OutSystems Cloud Connector ODC
Setup & Implementation of OutSystems Cloud Connector ODC
outsystemspuneusergr
 
NASIG ISSN 2025 updated for the_4-30meeting.pptx
NASIG ISSN 2025 updated for the_4-30meeting.pptxNASIG ISSN 2025 updated for the_4-30meeting.pptx
NASIG ISSN 2025 updated for the_4-30meeting.pptx
reine1
 
Wood Age and Trees of life - talk at Newcastle City Library
Wood Age and Trees of life - talk at Newcastle City LibraryWood Age and Trees of life - talk at Newcastle City Library
Wood Age and Trees of life - talk at Newcastle City Library
Woods for the Trees
 
Lec 3 - Chapter 2 Carl Jung’s Theory of Personality.pptx
Lec 3 - Chapter 2 Carl Jung’s Theory of Personality.pptxLec 3 - Chapter 2 Carl Jung’s Theory of Personality.pptx
Lec 3 - Chapter 2 Carl Jung’s Theory of Personality.pptx
TayyabaSiddiqui12
 
Besu Shibpur Enquesta 2012 Intra College General Quiz Prelims.pptx
Besu Shibpur Enquesta 2012 Intra College General Quiz Prelims.pptxBesu Shibpur Enquesta 2012 Intra College General Quiz Prelims.pptx
Besu Shibpur Enquesta 2012 Intra College General Quiz Prelims.pptx
Rajdeep Chakraborty
 
Effects of physical activity, exercise and sedentary behaviors to
Effects of physical activity, exercise and sedentary behaviors toEffects of physical activity, exercise and sedentary behaviors to
Effects of physical activity, exercise and sedentary behaviors to
DancanNyabuto
 
Reflections on an ngo peace conference in zimbabwe
Reflections on an ngo peace conference in zimbabweReflections on an ngo peace conference in zimbabwe
Reflections on an ngo peace conference in zimbabwe
jujuaw05
 
A Bot Identification Model and Tool Based on GitHub Activity Sequences
A Bot Identification Model and Tool Based on GitHub Activity SequencesA Bot Identification Model and Tool Based on GitHub Activity Sequences
A Bot Identification Model and Tool Based on GitHub Activity Sequences
natarajan8993
 
ICSE 2025 Keynote: Software Sustainability and its Engineering: How far have ...
ICSE 2025 Keynote: Software Sustainability and its Engineering: How far have ...ICSE 2025 Keynote: Software Sustainability and its Engineering: How far have ...
ICSE 2025 Keynote: Software Sustainability and its Engineering: How far have ...
patricialago3459
 
Profit Growth Drivers for Small Business.pdf
Profit Growth Drivers for Small Business.pdfProfit Growth Drivers for Small Business.pdf
Profit Growth Drivers for Small Business.pdf
TheodoreHawkins
 
THE SEXUAL HARASSMENT OF WOMAN AT WORKPLACE (PREVENTION, PROHIBITION & REDRES...
THE SEXUAL HARASSMENT OF WOMAN AT WORKPLACE (PREVENTION, PROHIBITION & REDRES...THE SEXUAL HARASSMENT OF WOMAN AT WORKPLACE (PREVENTION, PROHIBITION & REDRES...
THE SEXUAL HARASSMENT OF WOMAN AT WORKPLACE (PREVENTION, PROHIBITION & REDRES...
ASHISHKUMAR504404
 
The Business Dynamics of Quick Commerce.pdf
The Business Dynamics of Quick Commerce.pdfThe Business Dynamics of Quick Commerce.pdf
The Business Dynamics of Quick Commerce.pdf
RDinuRao
 
Basic.pptxsksdjsdjdvkfvfvfvfvfvfvfvfvfvvvv
Basic.pptxsksdjsdjdvkfvfvfvfvfvfvfvfvfvvvvBasic.pptxsksdjsdjdvkfvfvfvfvfvfvfvfvfvvvv
Basic.pptxsksdjsdjdvkfvfvfvfvfvfvfvfvfvvvv
hkthmrz42n
 
fundamentals of communicationclass notes.pptx
fundamentals of communicationclass notes.pptxfundamentals of communicationclass notes.pptx
fundamentals of communicationclass notes.pptx
Sunkod
 
THE SEXUAL HARASSMENT OF WOMAN AT WORKPLACE (PREVENTION, PROHIBITION & REDRES...
THE SEXUAL HARASSMENT OF WOMAN AT WORKPLACE (PREVENTION, PROHIBITION & REDRES...THE SEXUAL HARASSMENT OF WOMAN AT WORKPLACE (PREVENTION, PROHIBITION & REDRES...
THE SEXUAL HARASSMENT OF WOMAN AT WORKPLACE (PREVENTION, PROHIBITION & REDRES...
ASHISHKUMAR504404
 
cardiovascular outcome in trial of new antidiabetic drugs
cardiovascular outcome in trial of new antidiabetic drugscardiovascular outcome in trial of new antidiabetic drugs
cardiovascular outcome in trial of new antidiabetic drugs
Mohammed Ahmed Bamashmos
 
Speech 3-A Vision for Tomorrow for GE2025
Speech 3-A Vision for Tomorrow for GE2025Speech 3-A Vision for Tomorrow for GE2025
Speech 3-A Vision for Tomorrow for GE2025
Noraini Yunus
 
816111728-IELTS-WRITING test óft-PPT.pptx
816111728-IELTS-WRITING test óft-PPT.pptx816111728-IELTS-WRITING test óft-PPT.pptx
816111728-IELTS-WRITING test óft-PPT.pptx
787mianahmad
 
Setup & Implementation of OutSystems Cloud Connector ODC
Setup & Implementation of OutSystems Cloud Connector ODCSetup & Implementation of OutSystems Cloud Connector ODC
Setup & Implementation of OutSystems Cloud Connector ODC
outsystemspuneusergr
 
NASIG ISSN 2025 updated for the_4-30meeting.pptx
NASIG ISSN 2025 updated for the_4-30meeting.pptxNASIG ISSN 2025 updated for the_4-30meeting.pptx
NASIG ISSN 2025 updated for the_4-30meeting.pptx
reine1
 
Wood Age and Trees of life - talk at Newcastle City Library
Wood Age and Trees of life - talk at Newcastle City LibraryWood Age and Trees of life - talk at Newcastle City Library
Wood Age and Trees of life - talk at Newcastle City Library
Woods for the Trees
 
Lec 3 - Chapter 2 Carl Jung’s Theory of Personality.pptx
Lec 3 - Chapter 2 Carl Jung’s Theory of Personality.pptxLec 3 - Chapter 2 Carl Jung’s Theory of Personality.pptx
Lec 3 - Chapter 2 Carl Jung’s Theory of Personality.pptx
TayyabaSiddiqui12
 
Besu Shibpur Enquesta 2012 Intra College General Quiz Prelims.pptx
Besu Shibpur Enquesta 2012 Intra College General Quiz Prelims.pptxBesu Shibpur Enquesta 2012 Intra College General Quiz Prelims.pptx
Besu Shibpur Enquesta 2012 Intra College General Quiz Prelims.pptx
Rajdeep Chakraborty
 

Relational Database Management System

  • 1. Database Procedural Programming PL/SQL and Embedded SQL By, B.Nivegeetha I-Msc cs. Nadar Saraswathi College of Arts and Science, Theni.
  • 2. PL/SQL  PL/SQL is Oracle's procedural language exte nsion to SQL.  PL/SQL combines SQL with the procedural fu nctionality of a structured programming langu age, such as IF ... THEN, WHILE, and LOOP.  The PL/SQL engine used to define, compile, and execute PL/SQL program units.  A component of many Oracle products, includ ing Oracle Server.
  • 3. Procedures and Functions  A set of SQL and PL/SQL statements grouped together as a unit (block) to solve a specific problem or perform a set of re lated tasks.  An anonymous block is a PL/SQL block that appears within your application and it is not named or stored in the databas e. In many applications, PL/SQL blocks can appear whereve r SQL statements can appear.  A stored procedure is a PL/SQL block that Oracle stores in t he database and can be called by name from an application.  Functions always return a single value to the caller; procedu res do not return values to the caller.  Packages are groups of procedures and functions.
  • 4. Procedure PL/SQL Example CREATE PROCEDURE credit_labmark (sno NUMBER, cno CHAR, cre dit NUMBER) AS old_mark NUMBER; new_mark NUMBER; BEGIN SELECT labmark INTO old_mark FROM enrol WHERE studno = sno and courseno = cno FOR UPDATE OF la bmark; new_ mark := old_ mark + credit; UPDATE enrol SET labmark = new_mark WHERE studno = sno and courseno = cno; COMMIT; EXCEPTION WHEN NO_DATA_FOUND THEN INSERT INTO enrol(studno, courseno, labmark, exammark) VALUES(sno, cno, credit, null); WHEN OTHERS THEN ROLLBACK; END credit_labmark; PL/SQL sta tement. SQL statement. Locks enrol EXECUTE credit_lab mark (99234,’CS2312’,20)
  • 5. Function create function get_lab_mark(sno number, cno char) return number as f_lab_mark number; no_mark exception; begin select labmark into f_lab_mark from enrol where studno = sno and courseno = cno; if f_lab_mark is null then raise no_mark; else return(f_lab_mark); end if exception when no_mark then …..return(null); end;
  • 6. Stored Procedures Created in a user's schema and s tored, centrally, in compiled for m in the database as a named object that can be:  interactively executed by a user using a tool like SQL*Plus  called explicitly in the code of a d atabase application, such as an Oracle Forms or a Pre compiler a pplication, or in the code of anoth er procedure or trigger When PL/SQL is not stored in the database, applications can sen d blocks of PL/SQL to the data base rather than individual SQ L statements  reducing netw ork traffic. . Program code . . Program code . HIRE_EMP(…); . Program code Program code . . Program code . HIRE_EMP(…); . Program code Program code . . Program code . HIRE_EMP(…); . Program code HIRE_EMP(…) BEGIN . . END; Database Applications Stored Procedure Database
  • 8. Benefits of Stored Procedures I  Security  Control data access through procedures and functions.  E.g. grant users access to a procedure that updates a ta ble, but not grant them access to the table itself.  Performance The information is sent only once between database and application and thereafter invoked when it is used.  Network traffic is reduced compared with issuing individu al SQL statements or sending the text of an entire PL/S QL block  A procedure's compiled form is readily available in the d atabase, so no compilation is required at execution time.  The procedure might be cached
  • 9. Benefits of Procedures II  Memory Allocation  Stored procedures take advantage of the shared memory capabiliti es of Oracle  Only a single copy of the procedure needs to be loaded into memor y for execution by multiple users.  Productivity  By designing applications around a common set of procedures, you can avoid redundant coding and increase your productivity.  Procedures can be written to insert, update, or delete rows from a t able and then called by any application without rewriting the SQL st atements necessary to accomplish these tasks.  If the methods of data management change, only the procedures n eed to be modified, not all of the applications that use the procedur es.
  • 10. Benefits of Procedures III  Integrity  Stored procedures improve the integrity and consistenc y of your applications. By developing all of your applicati ons around a common group of procedures, you can re duce the likelihood of committing coding errors.  You can test a procedure or function to guarantee that it returns an accurate result and, once it is verified, reuse i t in any number of applications without testing it again.  If the data structures referenced by the procedure are al tered in any way, only the procedure needs to be recom piled; applications that call the procedure do not necess arily require any modifications.
  • 11. Packages  A method of encapsulating and storing related proced ures, functions, variables, cursors and other package constructs together as a unit in the database for conti nued use as a unit.  Similar to standalone procedures and functions, pack aged procedures and functions can be called explicitl y by applications or users.  Organize routines  Increased functionality (e.g. global package variab les can be declared and used by any procedure in the package) and  Increased performance (e.g. all objects of the pac kage are parsed, compiled, and loaded into memo ry once).
  • 12. Package manage tasks in database  Database applications expli citly call packaged procedu res as necessary.  After being granted the priv ileges for the package, a us er can explicitly execute an y of the procedures contain ed in it.  EXECUTE marks_mgmt. cr edit_labmark(99234,’CS23 12’,20)  Packages offer several dev elopment and performance advantages over standalon e stored procedures; Program code . EMP_MGMT.FIRE_EMP(…); Program code . EMP_MGMT.HIRE_EMP(…); . Program code Program code . EMP_MGMT.HIRE_EMP(…); Program code . EMP_MGMT.SAL_RAISE(…); . Program code FIRE_EMP(…) BEGIN . . END; HIRE_EMP(…) BEGIN . . END; SAL_RAISE(…) BEGIN . . END; Database
  • 13. Benefits of Packages  Encapsulation of related procedures and variables providing:  Better organization during the development process and for granti ng privileges  Declaration of public and private procedures, variables, constants, an d cursors  Better performance  An entire package is loaded into memory when a procedure withi n the package is called for the first time in one operation, as oppo sed to the separate loads required for standalone procedures. W hen calls to related packaged procedures occur, no disk I/O is ne cessary to execute the compiled code already in memory.  A package body can be replaced and recompiled without affectin g the specification. Objects that reference a package's constructs (always via the specification) need not be recompiled unless the package specification is also replaced. Unnecessary recompilatio ns can be minimized, so in less impact on overall database perfor mance.
  • 14. Triggers vs Procedures and Packages  Triggers are similar to stored procedures. A trigger ca n include SQL and PL/SQL statements to execute as a unit and can invoke stored procedures. Triggers are stored in the database separate from their associated tables.  Procedures and triggers differ in the way that they ar e invoked.  A procedure is explicitly executed by a user, applic ation, or trigger.  Triggers (one or more) are implicitly fired (execute d) by Oracle when a triggering INSERT, UPDATE, or DELETE statement is issued, no matter which u ser is connected or which application is being use d.
  • 15. Retrieval: Impedance Mismatch  What happens when the query returns several rows? T he host variables can only hold one value.  Oracle will only pass the first row returned by the query to the PL/SQL block (or host language program).  Re-executing the SELECT operation will only run the q uery again and so the first row will be selected again.  Different type systems  Different execution models
  • 16. Cursors  When a query returns multiple rows a cursor must be declared to process each row return ed by the query and to keep track of which ro w is currently being processed.  The rows returned by a query are stored in an area called the Active Set.  A cursor can be thought of as pointing to a ro w in the active set.
  • 17. Cursors and RetrievalPROCEDURE apply_marks IS CURSOR marks_cursor IS SELECT sno, cno, kind, amount FROM marks WHERE status = 'Pending' ORDER BY time_tag FOR UPDATE OF marks; BEGIN FOR marks IN marks_cursor LOOP /* implicit open and f etch */ new_status := ’Accepted'; IF marks.kind = ’L' THEN credit_labmark(marks.sno, marks.cno, marks.amount); ELSIF trans.kind = ’E' THEN credit_exammark(marks.sno, marks.cno, marks.amoun t); ELSE new_status := 'Rejected'; END IF; UPDATE marks SET status = new_status WHERE CURRENT OF marks_cursor; END LOOP; COMMIT; END apply_marks;
  • 18. Embedded SQL  SQL statements placed within a program. The source program is called the host program, and the language in which it is written is called the host language  You can execute any SQL statement using embedde d SQL statements just as if you were in SQL*Plus.  CREATE, ALTER and DROP database tables  SELECT, INSERT, UPDATE and DELETE rows of data  COMMIT transactions (make any changes to the d atabase permanent)
  • 19. Embedded SQL Statements  Embedded SQL statements incorporate DDL, DML, and tran saction control statements within a procedural language pro gram. They are used with the Oracle pre-compilers, e.g. Pro *C.  Embedded SQL statements enable you to  define, allocate, and release cursors (DECLARE CURSO R, OPEN, CLOSE)  declare a database name and connect to Oracle (DECLA RE DATABASE, CONNECT)  assign variable names (DECLARE STATEMENT)  initialize descriptors (DESCRIBE)  specify how error and warning conditions are handled (W HENEVER)  parse and execute SQL statements (PREPARE, EXECU TE, EXECUTE IMMEDIATE)  retrieve data from the database (FETCH).
  • 20. Executable and Declarative Statements  Embedded SQL includes all the interactive SQL statements pl us others that allow you to transfer data between Oracle and a host program. There are two types of embedded SQL state ments:  Executable:  used to connect to Oracle, to define, query and manipulate Oracle data, to control access to Oracle data and to proces s transactions. They can be placed wherever host-languag e executable statements can be placed.  Declarative:  do not operate on SQL data. Use them to declare Oracle o bjects, communication areas and SQL variables which will be used by Oracle and your host program. They can be pla ced wherever host-language declarations can be placed.
  • 21. Binding Variables  A host variable is prefixed with a colon (:) in SQL statements bu t must not be prefixed with a colon in C statements. EXEC SQL BEGIN DECLARE SECTION; INT sno; VARCHAR cno[5]; INT labmark; EXEC SQL END DECLARE SECTION; … EXEC SQL SELECT labmark INTO :labmark F ROM enrol WHERE studno = :sno and courseno = :cno  The case of the host variable is significant when referencing the m. database attribute host variable
  • 22. SELECT EXEC SQL SELECT courseno, subject INTO :courseno, :subject FROM course WHERE courseno = :menu_selection; Attributes in the staff table. INTO clause specifies the host variables which will hold the values of the attribute s returned. Host variable used to supply the WHERE claus e with a value to base the query on. In SQL*Plus this would be done using a literal value. Pro*C allows variables to be used to sp ecify a value. Host variables used in this way must contain a value before the SELECT state ment is used.
  • 23. Example Declare any host variables EXEC SQL BEGIN DECLARE SECTION; VARCHAR studname[21]; VARCHAR cno[5]; INT labmark; VARCHAR o_connect_uid[18]; EXEC SQL END DECLARE SECTION; Include the error handlers EXEC SQL INCLUDE sqlca; EXEC SQL INCLUDE oraca; Log on procedure void Oracle_Connect(void) { (void)strcpy(o_connect_uid.arr,"/@t:ora-srv:mucs7"); o_connect_uid.len = strlen(o_connect_uid.arr); EXEC SQL CONNECT :o_connect_uid; }
  • 24. Connect to Oracle Server and Do the Query main() { EXEC SQL WHENEVER SQLERROR DO sqlerror() EXEC ORACLE OPTION (ORACA=YES); oraca.orastxtf = 1; Oracle_Connect(); printf("Connected to O raclen");  Cursor for query EXEC SQL DECLARE studcursor CURSOR FOR SELECT s.name, e.courseno, e.labmark, FROM student s, enrol e WHERE s.studno = e.studno;  Do the query EXEC SQL OPEN studcursor; printf(”Name/Course/LabMark n");  Loop to fetch rows while (sqlca.sqlcode == 0) { EXEC SQL FETCH studcursor INTO :studname, :cno, :labmark printf("%s,%s,%d", studname, cno, labmark); } printf("%ld rows selected.n",sqlca.sqlerrd[2]); EXEC SQL CLOSE studcursor; EXEC SQL COMMIT WORK RELEASE; exit(1);}
  • 25. Examples of Packages and Procedures
  • 26. Create Package Specification create package marks_mgmt (null) as max_mark CONSTANT NUMBER := 100.00; PROCEDURE apply_marks; PROCEDURE enter_marks(sno number,cno char , kind char, credit number); end marks_mgmt;
  • 27. Create Package Body CREATE PACKAGE BODY marks_mgmt AS new_status CHAR(20); /* Global variable to record status of tra nsaction being applied. Used for update in enter_marks. */ PROCEDURE do_journal_entry (sno NUMBER, cno CHAR, kind CH AR) IS /* Records a journal entry for each marks credit applied by the enter_ marks procedure. */ BEGIN INSERT INTO journal VALUES (sno, cno, kind, sysdate); IF kind = ’L' THEN new_status := ’Lab credit'; ELSIF kind = ’E' THEN new_status := ’Exam credit'; ELSE new_status := 'New enrolment'; END IF; END do_journal_entry;
  • 28. Create Package Body I CREATE PROCEDURE credit_labmark (sno NUMBER, cno CHAR, credit NUMBER) AS old_mark NUMBER; new_mark NUMBER; mark_overflow EXCEPTION; BEGIN SELECT labmark INTO old_mark FROM enrol WHERE studno = sno and courseno = cno FOR UPDATE OF labmark; new_ mark := old_ mark + credit; IF new_mark <= max_mark THEN UPDATE enrol SET labmark = new_mark WHERE studno = sno and courseno = cno ; do_journal_entry(sno, cno, L); ELSE RAISE mark_overflow ENDIF;
  • 29. Create Package Body II EXCEPTION WHEN NO_DATA_FOUND THEN /* Create new enrolment if not found */ INSERT INTO enrol (studno, courseno, labmark, exammark) VALUES(sno, cno, credit, null); do_journal_entry(sno, cno, 'N'); WHEN mark_overflow THEN new_status := ’Mark Overflow’; WHEN OTHERS THEN /* Return other errors to application */ new_status := 'Error: ' || SQLERRM(SQLCODE); END credit_labmark; CREATE PROCEDURE credit_exammark (sno NUMBER, cno CHAR, cr edit NUMBER) AS… END credit_exammark;
  • 30. PROCEDURE apply_marks IS …. complete shortly... END apply_marks; PROCEDURE enter_marks(sno NUMBER, cno CHAR, kind CHAR , credit NUMBER) IS /* A new mark is always put into this 'queue' before b eing applied to the specified enrolment instance by the APPLY_MARKS procedure. */ BEGIN INSERT INTO marks VALUES (sno, cno, kind, amount, 'Pending', sysdate); COMMIT; END enter_marks; END marks_mgmt ; /* end package */ Create Package Body
  • 32. An error handling procedure void sqlerror(void) { int o_errl; int len = 550; char o_err[550]; EXEC SQL WHENEVER SQLERROR CONTINUE; sqlca.sqlerrm.sqlerrmc[sqlca.sqlerrm.sqlerrml] = NULL; printf("nOracle Error:n%s", sqlca.sqlerrm.sqlerrmc); oraca.orastxt.orastxtc[oraca.orastxt.orastxtl] = NULL; printf("ERROR statement:%sn", oraca.orastxt.orastxtc); sqlglm(o_err, &len, &oerrl); o_err[o_errl] = NULL; printf("ERROR Details: %sn",o_err); oraca.orasfnm.orasfnmc[oraca.orasfnm.orasfnml] = NULL; printf("ERROR at line %ld in %sn", oraca.oraslnr,oraca .orasfnm.orasfnmc); EXEC SQL ROLLBACK WORK RELEASE;