PL/SQL PL/SQL Declaring Variables Declaring Variables Writing Writing Executable Executable Statements Statements Interacting with the Oracl Interacting with the Oracl e Server e Server Writing Control Structures Writing Control Structures Working with Composite Working with Composite Datatypes Datatypes Cursors Cursors
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
ObjectivesObjectivesObjectivesObjectives After completing this lesson, you After completing this lesson, you
should be able to do the should be able to do the following:following: List the benefits of PL/SQLList the benefits of PL/SQL Recognize the basic PL/SQL block Recognize the basic PL/SQL block
and its sectionsand its sections Describe the significance of Describe the significance of
variables in PL/SQLvariables in PL/SQL Declare PL/SQL variablesDeclare PL/SQL variables Execute a PL/SQL blockExecute a PL/SQL block
After completing this lesson, you After completing this lesson, you should be able to do the should be able to do the following:following: List the benefits of PL/SQLList the benefits of PL/SQL Recognize the basic PL/SQL block Recognize the basic PL/SQL block
and its sectionsand its sections Describe the significance of Describe the significance of
variables in PL/SQLvariables in PL/SQL Declare PL/SQL variablesDeclare PL/SQL variables Execute a PL/SQL blockExecute a PL/SQL block
About PL/SQLAbout PL/SQLAbout PL/SQLAbout PL/SQL
PL/SQL is an extension to SQL with PL/SQL is an extension to SQL with design features of programming design features of programming languages.languages.
Data manipulation and query Data manipulation and query statements of SQL are included statements of SQL are included within procedural units of code.within procedural units of code.
PL/SQL is an extension to SQL with PL/SQL is an extension to SQL with design features of programming design features of programming languages.languages.
Data manipulation and query Data manipulation and query statements of SQL are included statements of SQL are included within procedural units of code.within procedural units of code.
GuidelinesGuidelines Follow naming conventions.Follow naming conventions. Initialize variables designated as Initialize variables designated as
NOT NULL and CONSTANT.NOT NULL and CONSTANT. Initialize identifiers by using the Initialize identifiers by using the
assignment operator (:=) or the assignment operator (:=) or the DEFAULT reserved word.DEFAULT reserved word.
Declare at most one identifier per Declare at most one identifier per line.line.
GuidelinesGuidelines Follow naming conventions.Follow naming conventions. Initialize variables designated as Initialize variables designated as
NOT NULL and CONSTANT.NOT NULL and CONSTANT. Initialize identifiers by using the Initialize identifiers by using the
assignment operator (:=) or the assignment operator (:=) or the DEFAULT reserved word.DEFAULT reserved word.
Declare at most one identifier per Declare at most one identifier per line.line.
Naming RulesNaming RulesNaming RulesNaming Rules Two variables can have the same Two variables can have the same
name, provided they are in name, provided they are in different blocks.different blocks.
The variable name (identifier) The variable name (identifier) should not be the same as the should not be the same as the name of table columns used in the name of table columns used in the block.block.
Two variables can have the same Two variables can have the same name, provided they are in name, provided they are in different blocks.different blocks.
The variable name (identifier) The variable name (identifier) should not be the same as the should not be the same as the name of table columns used in the name of table columns used in the block.block.DECLARE empno NUMBER(4);BEGIN SELECT empno INTO empno FROM emp WHERE ename = 'SMITH';END;
DECLARE empno NUMBER(4);BEGIN SELECT empno INTO empno FROM emp WHERE ename = 'SMITH';END;
Adopt a naming convention for
Adopt a naming convention for
PL/SQL identifiers:
PL/SQL identifiers:
for example, v_empno
for example, v_empno
Adopt a naming convention for
Adopt a naming convention for
PL/SQL identifiers:
PL/SQL identifiers:
for example, v_empno
for example, v_empno
Assigning Values to Assigning Values to VariablesVariables
Assigning Values to Assigning Values to VariablesVariables
The %TYPE AttributeThe %TYPE AttributeThe %TYPE AttributeThe %TYPE Attribute
Declare a variable according to: Declare a variable according to: A database column definitionA database column definition Another previously declared variableAnother previously declared variable
Prefix %TYPE with:Prefix %TYPE with: The database table and columnThe database table and column The previously declared variable nameThe previously declared variable name
Declare a variable according to: Declare a variable according to: A database column definitionA database column definition Another previously declared variableAnother previously declared variable
Prefix %TYPE with:Prefix %TYPE with: The database table and columnThe database table and column The previously declared variable nameThe previously declared variable name
Declaring Variables Declaring Variables with the %TYPE Attributewith the %TYPE Attribute
Declaring Variables Declaring Variables with the %TYPE Attributewith the %TYPE Attribute
Only the values TRUE, FALSE, and Only the values TRUE, FALSE, and NULL can be assigned to a Boolean NULL can be assigned to a Boolean variable.variable.
The variables are connected by the The variables are connected by the logical operators AND, OR, and logical operators AND, OR, and NOT.NOT.
The variables always yield TRUE, The variables always yield TRUE, FALSE, or NULL.FALSE, or NULL.
Arithmetic, character, and date Arithmetic, character, and date expressions can be used to return a expressions can be used to return a Boolean value.Boolean value.
Only the values TRUE, FALSE, and Only the values TRUE, FALSE, and NULL can be assigned to a Boolean NULL can be assigned to a Boolean variable.variable.
The variables are connected by the The variables are connected by the logical operators AND, OR, and logical operators AND, OR, and NOT.NOT.
The variables always yield TRUE, The variables always yield TRUE, FALSE, or NULL.FALSE, or NULL.
Arithmetic, character, and date Arithmetic, character, and date expressions can be used to return a expressions can be used to return a Boolean value.Boolean value.
1 5000
2 2345
3 12
4 3456
1
SMITH
2
JONES
3
NANCY
4 TIM
PL/SQL table structure PL/SQL table structure
BINARY_INTEGER
VARCHAR2
BINARY_INTEGER
NUMBER
PL/SQL Record StructurePL/SQL Record StructurePL/SQL Record StructurePL/SQL Record Structure
PL/SQL Block Syntax PL/SQL Block Syntax and Guidelinesand Guidelines
PL/SQL Block Syntax PL/SQL Block Syntax and Guidelinesand Guidelines
IdentifiersIdentifiers Can contain up to 30 charactersCan contain up to 30 characters Cannot contain reserved words Cannot contain reserved words
unless enclosed in double unless enclosed in double quotation marksquotation marks
Must begin with an alphabetic Must begin with an alphabetic charactercharacter
Should not have the same name as Should not have the same name as a database table column namea database table column name
IdentifiersIdentifiers Can contain up to 30 charactersCan contain up to 30 characters Cannot contain reserved words Cannot contain reserved words
unless enclosed in double unless enclosed in double quotation marksquotation marks
Must begin with an alphabetic Must begin with an alphabetic charactercharacter
Should not have the same name as Should not have the same name as a database table column namea database table column name
PL/SQL Block Syntax and PL/SQL Block Syntax and GuidelinesGuidelines
PL/SQL Block Syntax and PL/SQL Block Syntax and GuidelinesGuidelines
LiteralsLiterals Character and date literals must be Character and date literals must be
enclosed in single quotation marks.enclosed in single quotation marks.
A PL/SQL block is terminated by a A PL/SQL block is terminated by a slash ( / ) on a line by itself.slash ( / ) on a line by itself.
LiteralsLiterals Character and date literals must be Character and date literals must be
enclosed in single quotation marks.enclosed in single quotation marks.
A PL/SQL block is terminated by a A PL/SQL block is terminated by a slash ( / ) on a line by itself.slash ( / ) on a line by itself.
v_ename := 'Henderson';v_ename := 'Henderson';
Commenting CodeCommenting CodeCommenting CodeCommenting Code Prefix single-line comments with two Prefix single-line comments with two
dashes (--).dashes (--). Place multi-line comments between Place multi-line comments between
the symbols /* and */.the symbols /* and */. ExampleExample
Prefix single-line comments with two Prefix single-line comments with two dashes (--).dashes (--).
Place multi-line comments between Place multi-line comments between the symbols /* and */.the symbols /* and */.
ExampleExample... v_sal NUMBER (9,2);BEGIN /* Compute the annual salary based on the monthly salary input from the user */ v_sal := &p_monthly_sal * 12;END; -- This is the end of the block
... v_sal NUMBER (9,2);BEGIN /* Compute the annual salary based on the monthly salary input from the user */ v_sal := &p_monthly_sal * 12;END; -- This is the end of the block
This statement produces a compilation This statement produces a compilation error if the variable v_date is declared as error if the variable v_date is declared as datatype DATE.datatype DATE.
This statement produces a compilation This statement produces a compilation error if the variable v_date is declared as error if the variable v_date is declared as datatype DATE.datatype DATE.
To correct the error, use the TO_DATE To correct the error, use the TO_DATE conversion function.conversion function.To correct the error, use the TO_DATE To correct the error, use the TO_DATE conversion function.conversion function.
Nested Blocks Nested Blocks and Variable Scopeand Variable Scope
Nested Blocks Nested Blocks and Variable Scopeand Variable Scope
The body and the exception The body and the exception parts in the PL/SQL block could parts in the PL/SQL block could contain nested blocks.contain nested blocks.
An identifier is visible in the An identifier is visible in the regions in which you can regions in which you can reference the identifier:reference the identifier: A block can look up to the A block can look up to the
enclosing block.enclosing block. A block cannot look down to A block cannot look down to
enclosed blocks.enclosed blocks.
The body and the exception The body and the exception parts in the PL/SQL block could parts in the PL/SQL block could contain nested blocks.contain nested blocks.
An identifier is visible in the An identifier is visible in the regions in which you can regions in which you can reference the identifier:reference the identifier: A block can look up to the A block can look up to the
enclosing block.enclosing block. A block cannot look down to A block cannot look down to
enclosed blocks.enclosed blocks.
Nested Blocks Nested Blocks and Variable Scopeand Variable Scope
Nested Blocks Nested Blocks and Variable Scopeand Variable Scope
... x BINARY_INTEGER; BEGIN ... DECLARE y NUMBER; BEGIN ... END; ... END;
... x BINARY_INTEGER; BEGIN ... DECLARE y NUMBER; BEGIN ... END; ... END;
The PL/SQL operators are The PL/SQL operators are generally the same as those of generally the same as those of SQL(Arithmetic, logical,..)SQL(Arithmetic, logical,..)
** is the exponential operator in ** is the exponential operator in PL/SQLPL/SQL dbms_output.put_line(2**3); --dbms_output.put_line(2**3); --
Output is 8Output is 8 Comparison involving null Comparison involving null
V_count := v_count+1;V_count := v_count+1; V_equal :=(v_n1=v_n2);V_equal :=(v_n1=v_n2); V_valid :=(v_empno IS NOT V_valid :=(v_empno IS NOT
NULL);NULL);
The PL/SQL operators are The PL/SQL operators are generally the same as those of generally the same as those of SQL(Arithmetic, logical,..)SQL(Arithmetic, logical,..)
** is the exponential operator in ** is the exponential operator in PL/SQLPL/SQL dbms_output.put_line(2**3); --dbms_output.put_line(2**3); --
Output is 8Output is 8 Comparison involving null Comparison involving null
SELECT Statements in SELECT Statements in PL/SQLPL/SQL
SELECT Statements in SELECT Statements in PL/SQLPL/SQL
The INTO clause is required.The INTO clause is required. ExampleExample
The INTO clause is required.The INTO clause is required. ExampleExampleDECLARE v_deptno NUMBER(2); v_loc VARCHAR2(15);BEGIN SELECT deptno, loc INTO v_deptno, v_loc FROM dept WHERE dname = 'SALES'; ...END;
DECLARE v_deptno NUMBER(2); v_loc VARCHAR2(15);BEGIN SELECT deptno, loc INTO v_deptno, v_loc FROM dept WHERE dname = 'SALES'; ...END;
Retrieving Data in Retrieving Data in PL/SQLPL/SQL
Retrieving Data in Retrieving Data in PL/SQLPL/SQL Retrieve the order date and the ship date for the Retrieve the order date and the ship date for the
specified order.specified order. ExampleExample
Retrieve the order date and the ship date for the Retrieve the order date and the ship date for the specified order.specified order.
ExampleExample
DECLARE v_orderdate ord.orderdate%TYPE; v_shipdate ord.shipdate%TYPE; BEGIN SELECT orderdate, shipdate INTO v_orderdate, v_shipdate FROM ord WHERE id = 620;
...END;
DECLARE v_orderdate ord.orderdate%TYPE; v_shipdate ord.shipdate%TYPE; BEGIN SELECT orderdate, shipdate INTO v_orderdate, v_shipdate FROM ord WHERE id = 620;
...END;
Retrieving Data in Retrieving Data in PL/SQLPL/SQL
Retrieving Data in Retrieving Data in PL/SQLPL/SQL
Return the sum of the salaries Return the sum of the salaries for all employees in the specified for all employees in the specified department.department.
ExampleExample
Return the sum of the salaries Return the sum of the salaries for all employees in the specified for all employees in the specified department.department.
ExampleExampleDECLARE v_sum_sal emp.sal%TYPE; v_deptno NUMBER NOT NULL := 10; BEGIN SELECT SUM(sal) -- group function INTO v_sum_sal FROM emp WHERE deptno = v_deptno;END;
INSERT
UPDATE
DELETE
Manipulating Data Using Manipulating Data Using PL/SQLPL/SQL
Manipulating Data Using Manipulating Data Using PL/SQLPL/SQL
Make changes to database Make changes to database tables by using DML commands:tables by using DML commands: INSERTINSERT UPDATEUPDATE DELETEDELETE
Make changes to database Make changes to database tables by using DML commands:tables by using DML commands: INSERTINSERT UPDATEUPDATE DELETEDELETE
Inserting DataInserting DataInserting DataInserting Data
Add new employee information Add new employee information to the EMP table.to the EMP table.
ExampleExample
Add new employee information Add new employee information to the EMP table.to the EMP table.
ExampleExampleBEGIN INSERT INTO emp(empno, ename, job, deptno) VALUES (empno_sequence.NEXTVAL, 'HARDING',
'CLERK', 10);END;
BEGIN INSERT INTO emp(empno, ename, job, deptno) VALUES (empno_sequence.NEXTVAL, 'HARDING',
'CLERK', 10);END;
Updating DataUpdating DataUpdating DataUpdating Data
Increase the salary of all Increase the salary of all employees in the EMP table who employees in the EMP table who are Analysts.are Analysts.
ExampleExample
Increase the salary of all Increase the salary of all employees in the EMP table who employees in the EMP table who are Analysts.are Analysts.
ExampleExampleDECLARE v_sal_increase emp.sal%TYPE := 2000; BEGIN UPDATE emp SET sal = sal + v_sal_increase WHERE job = 'ANALYST';END;
Deleting DataDeleting DataDeleting DataDeleting Data
Delete rows that belong to Delete rows that belong to department 10 from the EMP table.department 10 from the EMP table.
ExampleExample
Delete rows that belong to Delete rows that belong to department 10 from the EMP table.department 10 from the EMP table.
ExampleExampleDECLARE v_deptno emp.deptno%TYPE := 10; BEGIN DELETE FROM emp WHERE deptno = v_deptno;END;
DECLARE v_deptno emp.deptno%TYPE := 10; BEGIN DELETE FROM emp WHERE deptno = v_deptno;END;
BEGIN SELECT orderdate, shipdate INTO orderdate, shipdate FROM ord WHERE ordid = ordid; END; SQL> / DECLARE * ERROR at line 1: ORA-01422: exact fetch returns more than
BEGIN SELECT orderdate, shipdate INTO orderdate, shipdate FROM ord WHERE ordid = ordid; END; SQL> / DECLARE * ERROR at line 1: ORA-01422: exact fetch returns more than
requested number of rows ORA-06512: at line 6
Writing Writing Control Control
StructuresStructures
Writing Writing Control Control
StructuresStructures
Controlling PL/SQL Flow Controlling PL/SQL Flow of Executionof Execution
Controlling PL/SQL Flow Controlling PL/SQL Flow of Executionof Execution
You can change the logical You can change the logical flow of statements using flow of statements using conditional IF statements and conditional IF statements and loop control structures. loop control structures.
Conditional IFConditional IF statements:statements: IF-THEN-END IFIF-THEN-END IF IF-THEN-ELSE-END IFIF-THEN-ELSE-END IF IF-THEN-ELSIF-END IFIF-THEN-ELSIF-END IF
You can change the logical You can change the logical flow of statements using flow of statements using conditional IF statements and conditional IF statements and loop control structures. loop control structures.
Conditional IFConditional IF statements:statements: IF-THEN-END IFIF-THEN-END IF IF-THEN-ELSE-END IFIF-THEN-ELSE-END IF IF-THEN-ELSIF-END IFIF-THEN-ELSIF-END IF
IF StatementsIF StatementsIF StatementsIF Statements
IF condition THEN statements;[ELSIF condition THEN statements;][ELSE statements;]END IF;
IF condition THEN statements;[ELSIF condition THEN statements;][ELSE statements;]END IF;
SyntaxSyntax
Simple IF statement:Simple IF statement:
Set the manager ID to 22 if the employee Set the manager ID to 22 if the employee name is Osborne.name is Osborne.
SyntaxSyntax
Simple IF statement:Simple IF statement:
Set the manager ID to 22 if the employee Set the manager ID to 22 if the employee name is Osborne.name is Osborne.IF v_ename = 'OSBORNE' THEN v_mgr := 22;END IF;
IF v_ename = 'OSBORNE' THEN v_mgr := 22;END IF;
Simple IF StatementsSimple IF StatementsSimple IF StatementsSimple IF Statements
Set the job title to Salesman, the department number to 35, and the Set the job title to Salesman, the department number to 35, and the commission to 20% of the current salary if the last name is Miller.commission to 20% of the current salary if the last name is Miller.
ExampleExample
Set the job title to Salesman, the department number to 35, and the Set the job title to Salesman, the department number to 35, and the commission to 20% of the current salary if the last name is Miller.commission to 20% of the current salary if the last name is Miller.
ExampleExample
. . .IF v_ename = 'MILLER' THEN v_job := 'SALESMAN'; v_deptno := 35; v_new_comm := sal * 0.20; END IF;. . .
. . .IF v_ename = 'MILLER' THEN v_job := 'SALESMAN'; v_deptno := 35; v_new_comm := sal * 0.20; END IF;. . .
THEN actionsTHEN actions(including further IFs)(including further IFs)
THEN actionsTHEN actions(including further IFs)(including further IFs)
FALSEFALSE
ELSE actionsELSE actions(including further IFs)(including further IFs)
ELSE actionsELSE actions(including further IFs)(including further IFs)
IF-THEN-ELSE IF-THEN-ELSE StatementsStatements
IF-THEN-ELSE IF-THEN-ELSE StatementsStatements
Set a flag for orders where there Set a flag for orders where there are fewer than five days are fewer than five days between order date and ship between order date and ship date.date.
ExampleExample
Set a flag for orders where there Set a flag for orders where there are fewer than five days are fewer than five days between order date and ship between order date and ship date.date.
For a given value, calculate a For a given value, calculate a percentage of that value based percentage of that value based on a condition.on a condition.
ExampleExample
For a given value, calculate a For a given value, calculate a percentage of that value based percentage of that value based on a condition.on a condition.
Building Logical Building Logical ConditionsConditions
Building Logical Building Logical ConditionsConditions
You can handle null values with the You can handle null values with the IS NULL operator.IS NULL operator.
Any arithmetic expression Any arithmetic expression containing a null value evaluates to containing a null value evaluates to NULL.NULL.
Concatenated expressions with null Concatenated expressions with null values treat null values as an values treat null values as an empty string.empty string.
NULL acts as FalseNULL acts as False
You can handle null values with the You can handle null values with the IS NULL operator.IS NULL operator.
Any arithmetic expression Any arithmetic expression containing a null value evaluates to containing a null value evaluates to NULL.NULL.
Concatenated expressions with null Concatenated expressions with null values treat null values as an values treat null values as an empty string.empty string.
NULL acts as FalseNULL acts as False
Logic TablesLogic TablesLogic TablesLogic Tables
Build a simple Boolean condition Build a simple Boolean condition with a comparison operator.with a comparison operator.
Build a simple Boolean condition Build a simple Boolean condition with a comparison operator.with a comparison operator.
where: condition is a Boolean variable or expression (TRUE, FALSE, or NULL);
where: condition is a Boolean variable or expression (TRUE, FALSE, or NULL);
-- delimiter-- delimiter
-- statements-- statements
-- EXIT statement-- EXIT statement
-- delimiter-- delimiter
Basic LoopBasic LoopBasic LoopBasic Loop
DECLARE v_ordid item.ordid%TYPE := 601; v_counter NUMBER(2) := 1;BEGIN LOOP INSERT INTO item(ordid, itemid) VALUES(v_ordid, v_counter); v_counter := v_counter + 1; EXIT WHEN v_counter > 10; END LOOP;END;
DECLARE v_ordid item.ordid%TYPE := 601; v_counter NUMBER(2) := 1;BEGIN LOOP INSERT INTO item(ordid, itemid) VALUES(v_ordid, v_counter); v_counter := v_counter + 1; EXIT WHEN v_counter > 10; END LOOP;END;
ExampleExample ExampleExample
FOR LoopFOR LoopFOR LoopFOR Loop SyntaxSyntax
Use a FOR loop to shortcut the test Use a FOR loop to shortcut the test for the number of iterations.for the number of iterations.
Do not declare the counter; it is Do not declare the counter; it is declared implicitly.declared implicitly.
SyntaxSyntax
Use a FOR loop to shortcut the test Use a FOR loop to shortcut the test for the number of iterations.for the number of iterations.
Do not declare the counter; it is Do not declare the counter; it is declared implicitly.declared implicitly.
FOR counter in [REVERSE] lower_bound..upper_bound LOOP statement1; statement2; . . .END LOOP;
FOR counter in [REVERSE] lower_bound..upper_bound LOOP statement1; statement2; . . .END LOOP;
FOR LoopFOR LoopFOR LoopFOR Loop GuidelinesGuidelines
Reference the counter within the Reference the counter within the loop only; it is undefined outside the loop only; it is undefined outside the loop.loop.
The lower and upper bounds of the The lower and upper bounds of the loop could be values, variables, or loop could be values, variables, or expressionsexpressions
Do Do notnot reference the counter as the reference the counter as the target of an assignment. An error target of an assignment. An error message rises if you do so.message rises if you do so.
GuidelinesGuidelines Reference the counter within the Reference the counter within the
loop only; it is undefined outside the loop only; it is undefined outside the loop.loop.
The lower and upper bounds of the The lower and upper bounds of the loop could be values, variables, or loop could be values, variables, or expressionsexpressions
Do Do notnot reference the counter as the reference the counter as the target of an assignment. An error target of an assignment. An error message rises if you do so.message rises if you do so.
FOR LoopFOR LoopFOR LoopFOR Loop Insert the first 10 new line items Insert the first 10 new line items
for order number 601.for order number 601. ExampleExample
Insert the first 10 new line items Insert the first 10 new line items for order number 601.for order number 601.
ExampleExample
DECLARE v_ordid item.ordid%TYPE := 601;BEGIN FOR i IN 1..10 LOOP INSERT INTO item(ordid, itemid) VALUES(v_ordid, i); END LOOP;END;
DECLARE v_ordid item.ordid%TYPE := 601;BEGIN FOR i IN 1..10 LOOP INSERT INTO item(ordid, itemid) VALUES(v_ordid, i); END LOOP;END;
WHILE LoopWHILE LoopWHILE LoopWHILE Loop
SyntaxSyntax
Use the WHILE loop to Use the WHILE loop to repeat statements while a repeat statements while a condition is TRUE.condition is TRUE.
SyntaxSyntax
Use the WHILE loop to Use the WHILE loop to repeat statements while a repeat statements while a condition is TRUE.condition is TRUE.
WHILE condition LOOP statement1; statement2; . . .END LOOP;
WHILE condition LOOP statement1; statement2; . . .END LOOP;
Condition isCondition isevaluated at the evaluated at the beginning ofbeginning ofeach iteration.each iteration.
WHILE LoopWHILE LoopWHILE LoopWHILE Loop ExampleExample ExampleExample
SQL>ACCEPT v_dept_name PROMPT 'Enter the dept. name: 'SQL>ACCEPT num_depts PROMPT 'Enter number of depts: ' SQL>DECLAREv_count NUMBER(2) := 1;BEGIN WHILE v_count <= &num_depts LOOP INSERT INTO dept(deptno,dname) VALUES (v_count, &v_dept_name); v_count := v_count + 1; END LOOP; COMMIT;END;/
SQL>ACCEPT v_dept_name PROMPT 'Enter the dept. name: 'SQL>ACCEPT num_depts PROMPT 'Enter number of depts: ' SQL>DECLAREv_count NUMBER(2) := 1;BEGIN WHILE v_count <= &num_depts LOOP INSERT INTO dept(deptno,dname) VALUES (v_count, &v_dept_name); v_count := v_count + 1; END LOOP; COMMIT;END;/
Working with Working with Composite Composite DatatypesDatatypes
Working with Working with Composite Composite DatatypesDatatypes
PL/SQL RecordsPL/SQL RecordsPL/SQL RecordsPL/SQL Records Must contain one or more Must contain one or more
components of any scalar, RECORD, components of any scalar, RECORD, or PL/SQL TABLE datatype, called or PL/SQL TABLE datatype, called fieldsfields
Are similar in structure to records in Are similar in structure to records in a 3GLa 3GL
Are not the same as rows in a Are not the same as rows in a database tabledatabase table
Treat a collection of fields as a logical Treat a collection of fields as a logical unitunit
Are convenient for fetching a row of Are convenient for fetching a row of data from a table for processingdata from a table for processing
Must contain one or more Must contain one or more components of any scalar, RECORD, components of any scalar, RECORD, or PL/SQL TABLE datatype, called or PL/SQL TABLE datatype, called fieldsfields
Are similar in structure to records in Are similar in structure to records in a 3GLa 3GL
Are not the same as rows in a Are not the same as rows in a database tabledatabase table
Treat a collection of fields as a logical Treat a collection of fields as a logical unitunit
Are convenient for fetching a row of Are convenient for fetching a row of data from a table for processingdata from a table for processing
Creating a PL/SQL Creating a PL/SQL RecordRecord
Creating a PL/SQL Creating a PL/SQL RecordRecord
SyntaxSyntax
Where Where field_declarationfield_declaration is is
SyntaxSyntax
Where Where field_declarationfield_declaration is is
TYPE type_name IS RECORD (field_declaration[, field_declaration]…);identifier type_name;
TYPE type_name IS RECORD (field_declaration[, field_declaration]…);identifier type_name;
Declare a variable according to a Declare a variable according to a collection of columns in a database collection of columns in a database table or view.table or view.
Prefix %ROWTYPE with the Prefix %ROWTYPE with the database table.database table.
Fields in the record take their Fields in the record take their names and datatypes from the names and datatypes from the columns of the table or view.columns of the table or view.
Declare a variable according to a Declare a variable according to a collection of columns in a database collection of columns in a database table or view.table or view.
Prefix %ROWTYPE with the Prefix %ROWTYPE with the database table.database table.
Fields in the record take their Fields in the record take their names and datatypes from the names and datatypes from the columns of the table or view.columns of the table or view.
The %ROWTYPE The %ROWTYPE AttributeAttribute
The %ROWTYPE The %ROWTYPE AttributeAttribute
ExamplesExamples Declare a variable to store the Declare a variable to store the
same information about a same information about a department as it is stored in the department as it is stored in the DEPT table. DEPT table.
Declare a variable to store the Declare a variable to store the same information about an same information about an employee as it is stored in the employee as it is stored in the EMP table.EMP table.
ExamplesExamples Declare a variable to store the Declare a variable to store the
same information about a same information about a department as it is stored in the department as it is stored in the DEPT table. DEPT table.
Declare a variable to store the Declare a variable to store the same information about an same information about an employee as it is stored in the employee as it is stored in the EMP table.EMP table.
SQL> SET SERVEROUTPUT ON;SQL> SET SERVEROUTPUT ON;SQL> DECLARESQL> DECLARE d dept%ROWTYPE;d dept%ROWTYPE; BEGINBEGIN SELECT deptno,dname,loc INTO d SELECT deptno,dname,loc INTO d
FROM dept WHERE deptno=10;FROM dept WHERE deptno=10; DBMS_OUTPUT.PUT_LINE(d.dname);DBMS_OUTPUT.PUT_LINE(d.dname); END;END; //ACCOUNTINGACCOUNTING
Are composed of two components:Are composed of two components: Primary key of datatype Primary key of datatype
BINARY_INTEGERBINARY_INTEGER Column of scalar or record datatypeColumn of scalar or record datatype
Increase dynamically because they Increase dynamically because they are unconstrainedare unconstrained
Are composed of two components:Are composed of two components: Primary key of datatype Primary key of datatype
BINARY_INTEGERBINARY_INTEGER Column of scalar or record datatypeColumn of scalar or record datatype
Increase dynamically because they Increase dynamically because they are unconstrainedare unconstrained
Creating a PL/SQL TableCreating a PL/SQL TableCreating a PL/SQL TableCreating a PL/SQL Table SyntaxSyntax SyntaxSyntaxTYPE type_name IS TABLE OF {column_type | variable%TYPE | table.column%TYPE} [NOT NULL] [INDEX BY BINARY_INTEGER];identifier type_name;
TYPE type_name IS TABLE OF {column_type | variable%TYPE | table.column%TYPE} [NOT NULL] [INDEX BY BINARY_INTEGER];identifier type_name;
...TYPE ename_table_type IS TABLE OF emp.ename%TYPE INDEX BY BINARY_INTEGER;ename_table ename_table_type;...
...TYPE ename_table_type IS TABLE OF emp.ename%TYPE INDEX BY BINARY_INTEGER;ename_table ename_table_type;...
ExampleExampleExampleExampleDeclare a PL/SQL table to store names.Declare a PL/SQL table to store names.Declare a PL/SQL table to store names.Declare a PL/SQL table to store names.
The Oracle Server uses implicit The Oracle Server uses implicit cursors to parse and execute your cursors to parse and execute your SQL statements.SQL statements.
Explicit cursors are explicitly Explicit cursors are explicitly declared by the programmer.declared by the programmer.
A cursor is a private SQL work A cursor is a private SQL work area.area.
There are two types of cursors:There are two types of cursors: Implicit cursorsImplicit cursors Explicit cursorsExplicit cursors
The Oracle Server uses implicit The Oracle Server uses implicit cursors to parse and execute your cursors to parse and execute your SQL statements.SQL statements.
Explicit cursors are explicitly Explicit cursors are explicitly declared by the programmer.declared by the programmer.
Cursor
Context Area
active setCID CALLID CNAME CCREDIT
1 MIS 101 Intro. to Info. Sy stems 3 2 MIS 301 Sy stems Analy sis 3 3 MIS 441 Database Management 3 4 CS 155 Programming in C++ 3 5 MIS 451 Client/Serv er Sy stems 3
Using SQL cursor attributes, you Using SQL cursor attributes, you can test the outcome of your can test the outcome of your SQL statements. SQL statements.
Using SQL cursor attributes, you Using SQL cursor attributes, you can test the outcome of your can test the outcome of your SQL statements. SQL statements. SQL%ROWCOUNT Number of rows affected by the
most recent SQL statement (an integer value)
SQL%FOUND Boolean attribute that evaluates to TRUE if the most recent SQL statement affects one or more rows
SQL%NOTFOUND Boolean attribute that evaluates to TRUE if the most recent SQLstatement does not affect any rows
SQL%ISOPEN Always evaluates to FALSE because PL/SQL closes implicit cursorsimmediately after they are executed
SQL Cursor AttributesSQL Cursor AttributesSQL Cursor AttributesSQL Cursor Attributes Delete rows that have the Delete rows that have the
specified order number from the specified order number from the ITEM table. Print the number of ITEM table. Print the number of rows deleted.rows deleted.
ExampleExample
Delete rows that have the Delete rows that have the specified order number from the specified order number from the ITEM table. Print the number of ITEM table. Print the number of rows deleted.rows deleted.
ExampleExample VARIABLE rows_deleted VARCHAR2(30)DECLARE v_ordid NUMBER := 605;BEGIN DELETE FROM item WHERE ordid = v_ordid; :rows_deleted := (SQL%ROWCOUNT || ' rows deleted.');END;/PRINT rows_deleted
Implicit Cursor SQLImplicit Cursor SQL%ROWCOUNT Example%ROWCOUNT Example
SQL> SET SERVEROUTPUT ON;SQL> SET SERVEROUTPUT ON;SQL> DECLARESQL> DECLARE r NUMBER;r NUMBER; BEGINBEGIN DELETE FROM emp WHERE DELETE FROM emp WHERE
Implicit Cursor SQLImplicit Cursor SQL%FOUND Example%FOUND Example
SQL> DECLARESQL> DECLARE r BOOLEAN;r BOOLEAN; BEGINBEGIN DELETE FROM emp WHERE empno=1000;DELETE FROM emp WHERE empno=1000; r:=SQL%FOUND;r:=SQL%FOUND; IF r THENIF r THEN DBMS_OUTPUT.PUT_LINE('Rows are founded');DBMS_OUTPUT.PUT_LINE('Rows are founded'); ELSEELSE DBMS_OUTPUT.PUT_LINE('No Rows are founded');DBMS_OUTPUT.PUT_LINE('No Rows are founded'); END IF;END IF; END;END; //No Rows are foundedNo Rows are founded
Implicit Cursor SQLImplicit Cursor SQL%ISOPEN Example%ISOPEN Example
SQL> DECLARESQL> DECLARE r BOOLEAN;r BOOLEAN; BEGINBEGIN UPDATE emp SET sal=1000 WHERE empno>7900;UPDATE emp SET sal=1000 WHERE empno>7900; r:=SQL%ISOPEN;r:=SQL%ISOPEN; IF r THEN IF r THEN DBMS_OUTPUT.PUT_LINE('The cursor is opened');DBMS_OUTPUT.PUT_LINE('The cursor is opened'); ELSEELSE DBMS_OUTPUT.PUT_LINE('The cursor is closed');DBMS_OUTPUT.PUT_LINE('The cursor is closed'); END IF;END IF; END;END; //The cursor is closedThe cursor is closed
About CursorsAbout CursorsAbout CursorsAbout Cursors
Every SQL statement Every SQL statement executed by the Oracle executed by the Oracle Server has an individual Server has an individual cursor associated with it:cursor associated with it: Implicit cursors: Declared for Implicit cursors: Declared for
all DML and PL/SQL SELECT all DML and PL/SQL SELECT statementsstatements
Explicit cursors: Declared and Explicit cursors: Declared and named by the programmernamed by the programmer
Every SQL statement Every SQL statement executed by the Oracle executed by the Oracle Server has an individual Server has an individual cursor associated with it:cursor associated with it: Implicit cursors: Declared for Implicit cursors: Declared for
all DML and PL/SQL SELECT all DML and PL/SQL SELECT statementsstatements
Explicit cursors: Declared and Explicit cursors: Declared and named by the programmernamed by the programmer
Controlling Explicit Controlling Explicit CursorsCursorsOpen the cursor.Open the cursor.
CursorCursor
PointerPointer
Fetch a row from the cursor.Fetch a row from the cursor.
CursorCursor
PointerPointer
Continue until empty.Continue until empty.
CursorCursor
PointerPointer
Close the cursor.Close the cursor.
Explicit Cursor ExampleExplicit Cursor ExampleSQL> DECLARESQL> DECLARE v_num emp.empno%TYPE;v_num emp.empno%TYPE; v_name emp.ename%TYPE;v_name emp.ename%TYPE; CURSOR my_cursor IS SELECT empno,ename FROM emp CURSOR my_cursor IS SELECT empno,ename FROM emp
WHERE empno>7900;WHERE empno>7900; BEGINBEGIN OPEN my_cursor;OPEN my_cursor; LOOPLOOP FETCH my_cursor INTO v_num,v_name;FETCH my_cursor INTO v_num,v_name; EXIT WHEN my_cursor%NOTFOUND;EXIT WHEN my_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE(v_num || ' has the name ' ||v_name);DBMS_OUTPUT.PUT_LINE(v_num || ' has the name ' ||v_name); END LOOP;END LOOP; CLOSE my_cursor;CLOSE my_cursor; END;END; //7902 has the name FORD7902 has the name FORD7934 has the name MILLER7934 has the name MILLER
Declaring the CursorDeclaring the CursorDeclaring the CursorDeclaring the Cursor SyntaxSyntax
Do not include the INTO clause in the cursor Do not include the INTO clause in the cursor declaration.declaration.
If processing rows in a specific sequence is If processing rows in a specific sequence is required, use the ORDER BY clause in the query.required, use the ORDER BY clause in the query.
SyntaxSyntax
Do not include the INTO clause in the cursor Do not include the INTO clause in the cursor declaration.declaration.
If processing rows in a specific sequence is If processing rows in a specific sequence is required, use the ORDER BY clause in the query.required, use the ORDER BY clause in the query.
CURSOR cursor_name IS
select_statement;
CURSOR cursor_name IS
select_statement;
Declaring the CursorDeclaring the CursorDeclaring the CursorDeclaring the Cursor
ExampleExample ExampleExampleDECLARE CURSOR emp_cursor IS SELECT empno, ename FROM emp;
CURSOR dept_cursor IS SELECT * FROM dept WHERE deptno = 10;BEGIN ...
DECLARE CURSOR emp_cursor IS SELECT empno, ename FROM emp;
CURSOR dept_cursor IS SELECT * FROM dept WHERE deptno = 10;BEGIN ...
Opening the CursorOpening the CursorOpening the CursorOpening the Cursor
SyntaxSyntax
Open the cursor to execute the Open the cursor to execute the query and identify the active set.query and identify the active set.
If the query returns no rows, no If the query returns no rows, no exception is raised.exception is raised.
Use cursor attributes to test the Use cursor attributes to test the outcome after a fetch.outcome after a fetch.
SyntaxSyntax
Open the cursor to execute the Open the cursor to execute the query and identify the active set.query and identify the active set.
If the query returns no rows, no If the query returns no rows, no exception is raised.exception is raised.
Use cursor attributes to test the Use cursor attributes to test the outcome after a fetch.outcome after a fetch.
OPEN cursor_name;OPEN cursor_name;
Fetching Data from the Fetching Data from the CursorCursor
Fetching Data from the Fetching Data from the CursorCursor
SyntaxSyntax
Retrieve the current row values Retrieve the current row values into variables.into variables.
Include the same number of Include the same number of variables.variables.
Match each variable to correspond Match each variable to correspond to the columns positionally.to the columns positionally.
Test to see if the cursor contains Test to see if the cursor contains rows.rows.
SyntaxSyntax
Retrieve the current row values Retrieve the current row values into variables.into variables.
Include the same number of Include the same number of variables.variables.
Match each variable to correspond Match each variable to correspond to the columns positionally.to the columns positionally.
Test to see if the cursor contains Test to see if the cursor contains rows.rows.
FETCH cursor_name INTO [variable1, variable2, ...]
| record_name];
FETCH cursor_name INTO [variable1, variable2, ...]
| record_name];
Fetching Data from the Fetching Data from the CursorCursor
Fetching Data from the Fetching Data from the CursorCursor
ExamplesExamples
ExamplesExamples
FETCH emp_cursor INTO v_empno, v_ename;FETCH emp_cursor INTO v_empno, v_ename;
...OPEN defined_cursor;LOOP FETCH defined_cursor INTO defined_variables EXIT WHEN ...; ... -- Process the retrieved data ...END;
...OPEN defined_cursor;LOOP FETCH defined_cursor INTO defined_variables EXIT WHEN ...; ... -- Process the retrieved data ...END;
Closing the CursorClosing the CursorClosing the CursorClosing the Cursor
SyntaxSyntax
Close the cursor after completing Close the cursor after completing the processing of the rows.the processing of the rows.
Reopen the cursor, if required.Reopen the cursor, if required. Do not attempt to fetch data from a Do not attempt to fetch data from a
cursor once it has been closed.cursor once it has been closed.
SyntaxSyntax
Close the cursor after completing Close the cursor after completing the processing of the rows.the processing of the rows.
Reopen the cursor, if required.Reopen the cursor, if required. Do not attempt to fetch data from a Do not attempt to fetch data from a
cursor once it has been closed.cursor once it has been closed.
Process several rows from an Process several rows from an explicit cursor using a loop.explicit cursor using a loop.
Fetch a row with each iteration.Fetch a row with each iteration. Use the %NOTFOUND attribute to Use the %NOTFOUND attribute to
write a test for an unsuccessful write a test for an unsuccessful fetch.fetch.
Use explicit cursor attributes to Use explicit cursor attributes to test the success of each fetch.test the success of each fetch.
Process several rows from an Process several rows from an explicit cursor using a loop.explicit cursor using a loop.
Fetch a row with each iteration.Fetch a row with each iteration. Use the %NOTFOUND attribute to Use the %NOTFOUND attribute to
write a test for an unsuccessful write a test for an unsuccessful fetch.fetch.
Use explicit cursor attributes to Use explicit cursor attributes to test the success of each fetch.test the success of each fetch.
The %ISOPEN AttributeThe %ISOPEN AttributeThe %ISOPEN AttributeThe %ISOPEN Attribute Fetch rows only when the cursor is Fetch rows only when the cursor is
open. open. Use the %ISOPEN cursor attribute Use the %ISOPEN cursor attribute
before performing a fetch to test before performing a fetch to test whether the cursor is open.whether the cursor is open.
ExampleExample
Fetch rows only when the cursor is Fetch rows only when the cursor is open. open.
Use the %ISOPEN cursor attribute Use the %ISOPEN cursor attribute before performing a fetch to test before performing a fetch to test whether the cursor is open.whether the cursor is open.
ExampleExampleIF NOT emp_cursor%ISOPEN THEN
OPEN emp_cursor;END IF;LOOP FETCH emp_cursor...
IF NOT emp_cursor%ISOPEN THENOPEN emp_cursor;
END IF;LOOP FETCH emp_cursor...
The %NOTFOUND The %NOTFOUND and %ROWCOUNT and %ROWCOUNT
AttributesAttributes
The %NOTFOUND The %NOTFOUND and %ROWCOUNT and %ROWCOUNT
AttributesAttributes Use the %ROWCOUNT cursor Use the %ROWCOUNT cursor
attribute to retrieve an exact attribute to retrieve an exact number of rows.number of rows.
The value of %ROWCOUNT before The value of %ROWCOUNT before fetching any row is NULL.fetching any row is NULL.
Use the %NOTFOUND cursor Use the %NOTFOUND cursor attribute to determine when to exit attribute to determine when to exit the loop.the loop.
Use the %ROWCOUNT cursor Use the %ROWCOUNT cursor attribute to retrieve an exact attribute to retrieve an exact number of rows.number of rows.
The value of %ROWCOUNT before The value of %ROWCOUNT before fetching any row is NULL.fetching any row is NULL.
Use the %NOTFOUND cursor Use the %NOTFOUND cursor attribute to determine when to exit attribute to determine when to exit the loop.the loop.
SQL> DECLARESQL> DECLARE v_num emp.empno%TYPE;v_num emp.empno%TYPE; v_name emp.ename%TYPE;v_name emp.ename%TYPE; r BOOLEAN;r BOOLEAN; CURSOR my_cursor IS SELECT empno,ename FROM emp WHERE CURSOR my_cursor IS SELECT empno,ename FROM emp WHERE
empno>7900;empno>7900; BEGINBEGIN OPEN my_cursor;OPEN my_cursor; r:=my_cursor%ISOPEN;r:=my_cursor%ISOPEN; IF r THEN IF r THEN DBMS_OUTPUT.PUT_LINE('The Cursor is opened after the open DBMS_OUTPUT.PUT_LINE('The Cursor is opened after the open
statement');statement'); ELSEELSE DBMS_OUTPUT.PUT_LINE('The Cursor is closed after the open DBMS_OUTPUT.PUT_LINE('The Cursor is closed after the open
statement');statement'); END IF;END IF;
Explicit Cursor %ISOPEN Explicit Cursor %ISOPEN Example Cont.Example Cont.
LOOPLOOP FETCH my_cursor INTO v_num,v_name;FETCH my_cursor INTO v_num,v_name; EXIT WHEN my_cursor%NOTFOUND;EXIT WHEN my_cursor%NOTFOUND; END LOOP;END LOOP; CLOSE my_cursor;CLOSE my_cursor; r:=my_cursor%ISOPEN;r:=my_cursor%ISOPEN; IF r THEN IF r THEN DBMS_OUTPUT.PUT_LINE('The Cursor is opened after the close DBMS_OUTPUT.PUT_LINE('The Cursor is opened after the close
statement');statement'); ELSEELSE DBMS_OUTPUT.PUT_LINE('The Cursor is closed after the close DBMS_OUTPUT.PUT_LINE('The Cursor is closed after the close
statement');statement'); END IF;END IF; END;END; //The Cursor is opened after the open statementThe Cursor is opened after the open statementThe Cursor is closed after the close statementThe Cursor is closed after the close statement
Explicit Cursor Explicit Cursor %ROWCOUNT Example%ROWCOUNT Example
SQL> DECLARESQL> DECLARE v_name emp.ename%TYPE;v_name emp.ename%TYPE; r NUMBER;r NUMBER; c NUMBER:=1;c NUMBER:=1; CURSOR my_cursor IS SELECT ename FROM emp WHERE empno>7900;CURSOR my_cursor IS SELECT ename FROM emp WHERE empno>7900; BEGINBEGIN OPEN my_cursor;OPEN my_cursor; LOOPLOOP FETCH my_cursor INTO v_name;FETCH my_cursor INTO v_name; EXIT WHEN my_cursor%NOTFOUND;EXIT WHEN my_cursor%NOTFOUND; r:=my_cursor%ROWCOUNT;r:=my_cursor%ROWCOUNT; DBMS_OUTPUT.PUT_LINE('After fetch number ' || c || ' ROWCOUNT has the value ' || DBMS_OUTPUT.PUT_LINE('After fetch number ' || c || ' ROWCOUNT has the value ' ||
r);r); c:=c+1;c:=c+1; END LOOP;END LOOP; CLOSE my_cursor;CLOSE my_cursor; END;END; //After fetch number 1 ROWCOUNT has the value 1After fetch number 1 ROWCOUNT has the value 1After fetch number 2 ROWCOUNT has the value 2After fetch number 2 ROWCOUNT has the value 2
Cursors and RecordsCursors and RecordsCursors and RecordsCursors and Records Process the rows of the active Process the rows of the active
set conveniently by fetching set conveniently by fetching values into a PL/SQL RECORD.values into a PL/SQL RECORD.
ExampleExample
Process the rows of the active Process the rows of the active set conveniently by fetching set conveniently by fetching values into a PL/SQL RECORD.values into a PL/SQL RECORD.
ExampleExampleDECLARE 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; ...
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; ...
SyntaxSyntax
The cursor FOR loop is a shortcut to The cursor FOR loop is a shortcut to process explicit cursors.process explicit cursors.
Implicit open, fetch, and close occur.Implicit open, fetch, and close occur. The record is implicitly declared.The record is implicitly declared.
SyntaxSyntax
The cursor FOR loop is a shortcut to The cursor FOR loop is a shortcut to process explicit cursors.process explicit cursors.
Implicit open, fetch, and close occur.Implicit open, fetch, and close occur. The record is implicitly declared.The record is implicitly declared.
Cursor FOR LoopsCursor FOR LoopsCursor FOR LoopsCursor FOR Loops
FOR record_name IN cursor_name LOOP
statement1;
statement2;
. . .
END LOOP;
FOR record_name IN cursor_name LOOP
statement1;
statement2;
. . .
END LOOP;
Cursor FOR LoopsCursor FOR LoopsCursor FOR LoopsCursor FOR Loops
Retrieve employees one by one Retrieve employees one by one until no more are left.until no more are left.
ExampleExample
Retrieve employees one by one Retrieve employees one by one until no more are left.until no more are left.
ExampleExampleDECLARE 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 occursEND;
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 occursEND;
WHEN OTHERS is the last clause.WHEN OTHERS is the last clause. EXCEPTION keyword starts EXCEPTION keyword starts
exception-handling section.exception-handling section. Several exception handlers are Several exception handlers are
allowed.allowed. Only one handler is processed Only one handler is processed
before leaving the block.before leaving the block.
WHEN OTHERS is the last clause.WHEN OTHERS is the last clause. EXCEPTION keyword starts EXCEPTION keyword starts
exception-handling section.exception-handling section. Several exception handlers are Several exception handlers are
allowed.allowed. Only one handler is processed Only one handler is processed
before leaving the block.before leaving the block.
Trapping Predefined Trapping Predefined Oracle Server ErrorsOracle Server ErrorsTrapping Predefined Trapping Predefined Oracle Server ErrorsOracle Server Errors
Common errors that have been given Common errors that have been given predefined namespredefined names
Reference the standard name in the Reference the standard name in the exception-handling routine.exception-handling routine.
ORA-01422 TOO_MANY_ROWS Query returns more rows than expected ORA-01476 ZERO_DIVIDE Division by zero ORA-01722 INVALID_NUMBER Invalid numeric conversion
ORA-06502 VALUE_ERROR Error in arithmetic or numeric function operation
BEGINEXCEPTION WHEN NO_DATA_FOUND THEN statement1; statement2; WHEN TOO_MANY_ROWS THEN statement1; WHEN OTHERS THEN statement1; statement2; statement3;END;
SyntaxSyntax SyntaxSyntax
Trapping Non-Predefined Trapping Non-Predefined Oracle Server ErrorsOracle Server Errors
Trapping Non-Predefined Trapping Non-Predefined Oracle Server ErrorsOracle Server Errors
DeclareDeclare
• Name the Name the exceptionexception
AssociateAssociate
• Code the PRAGMA Code the PRAGMA EXCEPTION_INITEXCEPTION_INIT
Declarative sectionDeclarative section
Reference Reference
• Handle the Handle the raised raised exceptionexception
e_emps_remaining, -2292); v_deptno dept.deptno%TYPE := &p_deptno;BEGIN DELETE FROM dept WHERE deptno = v_deptno; COMMIT;EXCEPTION WHEN e_emps_remaining THEN DBMS_OUTPUT.PUT_LINE ('Cannot remove dept ' || TO_CHAR(v_deptno) || '. Employees exist. ');END;
Non-Predefined ErrorNon-Predefined ErrorNon-Predefined ErrorNon-Predefined Error Trap for Oracle Server error Trap for Oracle Server error
number number –2292, an integrity constraint 2292, an integrity constraint violation.violation.
Trap for Oracle Server error Trap for Oracle Server error number number –2292, an integrity constraint 2292, an integrity constraint violation.violation.
DECLARE e_invalid_product EXCEPTION;BEGIN UPDATE product SET descrip = '&product_description' WHERE prodid = &product_number; IF SQL%NOTFOUND THEN RAISE e_invalid_product; END IF; COMMIT;EXCEPTION WHEN e_invalid_product THEN DBMS_OUTPUT.PUT_LINE('Invalid product number.');END;
ExampleExampleExampleExample
e_invalid_product EXCEPTION; 1
RAISE e_invalid_product; 2
e_invalid_product 3
RAISE_APPLICATION_ERRRAISE_APPLICATION_ERROROR
ProcedureProcedure
RAISE_APPLICATION_ERRRAISE_APPLICATION_ERROROR
ProcedureProcedure SyntaxSyntax
A procedure that lets you issue A procedure that lets you issue user-defined error messages from user-defined error messages from stored subprogramsstored subprograms
Called only from an executing Called only from an executing stored subprogramstored subprogram
SyntaxSyntax
A procedure that lets you issue A procedure that lets you issue user-defined error messages from user-defined error messages from stored subprogramsstored subprograms
Called only from an executing Called only from an executing stored subprogramstored subprogram