PL/SQLPL/SQLPL/SQLPL/SQL Declaring VariablesDeclaring Variables Writing Writing ExecutableExecutable
Statements Statements Interacting with the Oracle SeInteracting with the Oracle Se
rverrver Writing Control StructuresWriting Control Structures Working with Composite Working with Composite
DatatypesDatatypes CursorsCursors Handling ExceptionsHandling Exceptions
Declaring VariablesDeclaring Variables Writing Writing ExecutableExecutable
Statements Statements Interacting with the Oracle SeInteracting with the Oracle Se
rverrver Writing Control StructuresWriting Control Structures Working with Composite Working with Composite
DatatypesDatatypes CursorsCursors Handling ExceptionsHandling Exceptions
Declaring Declaring VariablesVariablesDeclaring Declaring VariablesVariables
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.
PL/SQL Block StructurePL/SQL Block StructurePL/SQL Block StructurePL/SQL Block Structure
DECLARE – OptionalVariables, cursors, user-defined Variables, cursors, user-defined
exceptionsexceptions
BEGIN – Mandatory– SQL statementsSQL statements
– PL/SQL statementsPL/SQL statements
EXCEPTION – OptionalActions to perform when errors occurActions to perform when errors occur
END; – Mandatory
DECLARE – OptionalVariables, cursors, user-defined Variables, cursors, user-defined
exceptionsexceptions
BEGIN – Mandatory– SQL statementsSQL statements
– PL/SQL statementsPL/SQL statements
EXCEPTION – OptionalActions to perform when errors occurActions to perform when errors occur
END; – Mandatory
DECLAREDECLARE
BEGINBEGIN
EXCEPTIONEXCEPTION
END;END;
PL/SQL Block StructurePL/SQL Block StructurePL/SQL Block StructurePL/SQL Block Structure
DECLARE v_variable VARCHAR2(5);BEGIN SELECT column_name INTO v_variable FROM table_name;EXCEPTION WHEN exception_name THEN ...END;
DECLARE v_variable VARCHAR2(5);BEGIN SELECT column_name INTO v_variable FROM table_name;EXCEPTION WHEN exception_name THEN ...END;
DECLAREDECLARE
BEGINBEGIN
EXCEPTIONEXCEPTION
END;END;
Block TypesBlock TypesBlock TypesBlock Types AnonymousAnonymous ProcedureProcedure
FunctionFunction[DECLARE][DECLARE]
BEGINBEGIN --statements--statements
[EXCEPTION][EXCEPTION]
END;END;
[DECLARE][DECLARE]
BEGINBEGIN --statements--statements
[EXCEPTION][EXCEPTION]
END;END;
PROCEDURE namePROCEDURE nameISIS
BEGINBEGIN --statements--statements
[EXCEPTION][EXCEPTION]
END;END;
PROCEDURE namePROCEDURE nameISIS
BEGINBEGIN --statements--statements
[EXCEPTION][EXCEPTION]
END;END;
FUNCTION nameFUNCTION nameRETURN datatypeRETURN datatypeISISBEGINBEGIN --statements--statements RETURN value;RETURN value;[EXCEPTION][EXCEPTION]
END;END;
FUNCTION nameFUNCTION nameRETURN datatypeRETURN datatypeISISBEGINBEGIN --statements--statements RETURN value;RETURN value;[EXCEPTION][EXCEPTION]
END;END;
Types of VariablesTypes of VariablesTypes of VariablesTypes of Variables
PL/SQL variables:PL/SQL variables: ScalarScalar CompositeComposite ReferenceReference LOB (large objects)LOB (large objects)
Non-PL/SQL variables: Bind and Non-PL/SQL variables: Bind and host variableshost variables
PL/SQL variables:PL/SQL variables: ScalarScalar CompositeComposite ReferenceReference LOB (large objects)LOB (large objects)
Non-PL/SQL variables: Bind and Non-PL/SQL variables: Bind and host variableshost variables
TRUETRUE
Types of VariablesTypes of VariablesTypes of VariablesTypes of Variables
25-OCT-9925-OCT-99
AtlantaAtlanta256120.08256120.08
Declaring PL/SQL Declaring PL/SQL VariablesVariables
Declaring PL/SQL Declaring PL/SQL VariablesVariables
SyntaxSyntax
ExamplesExamples
SyntaxSyntax
ExamplesExamples
identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr];
identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr];
Declare v_hiredate DATE; v_deptno NUMBER(2) NOT NULL := 10; v_location VARCHAR2(13) := 'Atlanta'; c_comm CONSTANT NUMBER := 1400;
Declare v_hiredate DATE; v_deptno NUMBER(2) NOT NULL := 10; v_location VARCHAR2(13) := 'Atlanta'; c_comm CONSTANT NUMBER := 1400;
Declaring PL/SQL Declaring PL/SQL VariablesVariables
Declaring PL/SQL Declaring PL/SQL VariablesVariables
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
v_ename := 'Maduro';v_ename := 'Maduro';
v_hiredate := '31-DEC-98';v_hiredate := '31-DEC-98';
SyntaxSyntax
ExamplesExamples
Set a predefined hiredate for new Set a predefined hiredate for new employees. employees.
SyntaxSyntax
ExamplesExamples
Set a predefined hiredate for new Set a predefined hiredate for new employees. employees.
Set the employee name to Maduro. Set the employee name to Maduro. Set the employee name to Maduro. Set the employee name to Maduro.
identifier := expr; identifier := expr;
Scalar DatatypesScalar DatatypesScalar DatatypesScalar Datatypes
• Hold a single value
• Have no internal components
• Hold a single value
• Have no internal components
25-OCT-9925-OCT-99
AtlantaAtlanta
TRUETRUE
256120.08256120.08
Base Scalar DatatypesBase Scalar DatatypesBase Scalar DatatypesBase Scalar Datatypes VARCHAR2 (VARCHAR2 (maximum_lengthmaximum_length)) NUMBER [(NUMBER [(precision, scaleprecision, scale)])] DATEDATE CHAR [(CHAR [(maximum_lengthmaximum_length)])] LONGLONG BOOLEANBOOLEAN BINARY_INTEGERBINARY_INTEGER
VARCHAR2 (VARCHAR2 (maximum_lengthmaximum_length)) NUMBER [(NUMBER [(precision, scaleprecision, scale)])] DATEDATE CHAR [(CHAR [(maximum_lengthmaximum_length)])] LONGLONG BOOLEANBOOLEAN BINARY_INTEGERBINARY_INTEGER
Scalar Variable Scalar Variable DeclarationsDeclarations
Scalar Variable Scalar Variable DeclarationsDeclarations
v_job VARCHAR2(9);v_count BINARY_INTEGER := 0;v_total_sal NUMBER(9,2) := 0;v_orderdate DATE := SYSDATE + 7;c_tax_rate CONSTANT NUMBER(3,2) := 8.25;v_valid BOOLEAN NOT NULL := TRUE;
v_job VARCHAR2(9);v_count BINARY_INTEGER := 0;v_total_sal NUMBER(9,2) := 0;v_orderdate DATE := SYSDATE + 7;c_tax_rate CONSTANT NUMBER(3,2) := 8.25;v_valid BOOLEAN NOT NULL := TRUE;
ExamplesExamples ExamplesExamples
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
ExamplesExamples ExamplesExamples
... v_ename emp.ename%TYPE; v_balance NUMBER(7,2); v_min_balance v_balance%TYPE := 10;...
... v_ename emp.ename%TYPE; v_balance NUMBER(7,2); v_min_balance v_balance%TYPE := 10;...
Declaring Boolean Declaring Boolean VariablesVariables
Declaring Boolean Declaring Boolean VariablesVariables
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
TRUE 23-DEC-98 ATLANTA
LOB Datatype VariablesLOB Datatype VariablesLOB Datatype VariablesLOB Datatype VariablesBookBook
(CLOB)(CLOB)
PhotoPhoto(BLOB)(BLOB)
MovieMovie(BFILE)(BFILE)
NCLOBNCLOB
Bind Variables ExampleBind Variables Example SQL>Variable m_sal NUMBERSQL>Variable m_sal NUMBER SQL>Set SERVEROUTPUT ONSQL>Set SERVEROUTPUT ON SQL>DeclareSQL>Declare V_sal NUMBER; V_sal NUMBER; BeginBegin :m_sal :=300;:m_sal :=300; V_sal=&m_sal;V_sal=&m_sal; DBMS_OUTPUT.PUT_LINE(‘salary is: ‘||DBMS_OUTPUT.PUT_LINE(‘salary is: ‘||
v_sal);v_sal); End;End; SQL>Print m_sal SQL>Print m_sal
Writing Writing Executable Executable StatementsStatements
Writing Writing Executable Executable StatementsStatements
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
PL/SQL FunctionsPL/SQL FunctionsPL/SQL FunctionsPL/SQL Functions
ExamplesExamples Build the mailing list for a company.Build the mailing list for a company.
Convert the employee name to Convert the employee name to lowercase.lowercase.
ExamplesExamples Build the mailing list for a company.Build the mailing list for a company.
Convert the employee name to Convert the employee name to lowercase.lowercase.
v_mailing_address := v_name||CHR(10)||
v_address||CHR(10)||v_state||
CHR(10)||v_zip;
v_mailing_address := v_name||CHR(10)||
v_address||CHR(10)||v_state||
CHR(10)||v_zip;
v_ename := LOWER(v_ename);v_ename := LOWER(v_ename);
Datatype ConversionDatatype ConversionDatatype ConversionDatatype Conversion
Convert data to comparable Convert data to comparable datatypes.datatypes.
Mixed datatypes can result in an Mixed datatypes can result in an error and affect performance.error and affect performance.
Conversion functions:Conversion functions: TO_CHARTO_CHAR TO_DATETO_DATE TO_NUMBERTO_NUMBER
Convert data to comparable Convert data to comparable datatypes.datatypes.
Mixed datatypes can result in an Mixed datatypes can result in an error and affect performance.error and affect performance.
Conversion functions:Conversion functions: TO_CHARTO_CHAR TO_DATETO_DATE TO_NUMBERTO_NUMBER
DECLARE v_date VARCHAR2(15);BEGIN SELECT TO_CHAR(hiredate,
'MON. DD, YYYY') INTO v_date FROM emp WHERE empno = 7839;END;
DECLARE v_date VARCHAR2(15);BEGIN SELECT TO_CHAR(hiredate,
'MON. DD, YYYY') INTO v_date FROM emp WHERE empno = 7839;END;
Datatype ConversionDatatype ConversionDatatype ConversionDatatype Conversion
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.
v_date := 'January 13, 1998'; v_date := 'January 13, 1998';
v_date := TO_DATE ('January 13, 1998', 'Month DD, YYYY');
v_date := TO_DATE ('January 13, 1998', 'Month DD, YYYY');
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;
Scope of x
Scope of y
ExampleExample
Nested Blocks ExampleNested Blocks Example SQL> DECLARESQL> DECLARE v_m VARCHAR2(50) :='Oracle';v_m VARCHAR2(50) :='Oracle'; BEGINBEGIN DECLAREDECLARE v_z VARCHAR2(20):='Second';v_z VARCHAR2(20):='Second'; BEGINBEGIN v_m:=v_m || v_z;v_m:=v_m || v_z; END;END; v_m:=v_m || ‘ Exam';v_m:=v_m || ‘ Exam'; DBMS_OUTPUT.PUT_LINE(v_m);DBMS_OUTPUT.PUT_LINE(v_m); END;END; //Output: Oracle Second ExamOutput: Oracle Second Exam
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
always yield nullalways yield null ExamplesExamples
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
always yield nullalways yield null ExamplesExamples
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);
Operators in PL/SQLOperators in PL/SQLOperators in PL/SQLOperators in PL/SQL
Programming Programming GuidelinesGuidelines
Programming Programming GuidelinesGuidelines
Use commentsUse comments Use a case convention for the Use a case convention for the
codecode Write keywords in uppercaseWrite keywords in uppercase Write identifiers in lowercaseWrite identifiers in lowercase
Use naming convention for Use naming convention for identifiersidentifiers Variables: v_nameVariables: v_name Constants: c_nameConstants: c_name ……
Use IndentationUse Indentation
Use commentsUse comments Use a case convention for the Use a case convention for the
codecode Write keywords in uppercaseWrite keywords in uppercase Write identifiers in lowercaseWrite identifiers in lowercase
Use naming convention for Use naming convention for identifiersidentifiers Variables: v_nameVariables: v_name Constants: c_nameConstants: c_name ……
Use IndentationUse Indentation
Indenting CodeIndenting CodeIndenting CodeIndenting Code
For clarity, indent each level of For clarity, indent each level of code.code.
ExampleExample
For clarity, indent each level of For clarity, indent each level of code.code.
ExampleExampleBEGIN IF x=0 THEN y:=1; END IF;END;
BEGIN IF x=0 THEN y:=1; END IF;END;
DECLARE v_deptno NUMBER(2); v_location VARCHAR2(13);BEGIN SELECT deptno, loc INTO v_deptno,
v_location FROM dept WHERE dname = 'SALES'; ...END;
DECLARE v_deptno NUMBER(2); v_location VARCHAR2(13);BEGIN SELECT deptno, loc INTO v_deptno,
v_location FROM dept WHERE dname = 'SALES'; ...END;
Determining Variable Determining Variable ScopeScope
Determining Variable Determining Variable ScopeScope Class ExerciseClass Exercise Class ExerciseClass Exercise
...DECLARE V_SAL NUMBER(7,2) := 60000; V_COMM NUMBER(7,2) := V_SAL * .20; V_MESSAGE VARCHAR2(255) := ' eligible for commission';BEGIN ...
DECLARE V_SAL NUMBER(7,2) := 50000; V_COMM NUMBER(7,2) := 0; V_TOTAL_COMP NUMBER(7,2) := V_SAL + V_COMM; BEGIN ... V_MESSAGE := 'CLERK not'||V_MESSAGE; END;
V_MESSAGE := 'SALESMAN'||V_MESSAGE;END;
...DECLARE V_SAL NUMBER(7,2) := 60000; V_COMM NUMBER(7,2) := V_SAL * .20; V_MESSAGE VARCHAR2(255) := ' eligible for commission';BEGIN ...
DECLARE V_SAL NUMBER(7,2) := 50000; V_COMM NUMBER(7,2) := 0; V_TOTAL_COMP NUMBER(7,2) := V_SAL + V_COMM; BEGIN ... V_MESSAGE := 'CLERK not'||V_MESSAGE; END;
V_MESSAGE := 'SALESMAN'||V_MESSAGE;END;
Interacting Interacting with with
the Oracle the Oracle ServerServer
Interacting Interacting with with
the Oracle the Oracle ServerServer
PL/SQL StatementsPL/SQL Statements
Valid PL/SQL statements:Valid PL/SQL statements: DML commandsDML commands Some DCL commands (Commit, Some DCL commands (Commit,
rollack, savepoint,…)rollack, savepoint,…)
Invalid PL/SQL statements:Invalid PL/SQL statements: DDL commandsDDL commands Some DCL commands (Grant, Some DCL commands (Grant,
Revoke,…)Revoke,…)
SELECT Statements in SELECT Statements in PL/SQLPL/SQL
SELECT Statements in SELECT Statements in PL/SQLPL/SQL
Retrieve data from the database Retrieve data from the database with SELECT.with SELECT.
SyntaxSyntax
Retrieve data from the database Retrieve data from the database with SELECT.with SELECT.
SyntaxSyntaxSELECT select_listINTO {variable_name[, variable_name]...
| record_name} FROM tableWHERE condition;
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;
Naming ConventionsNaming ConventionsNaming ConventionsNaming Conventions DECLARE orderdate ord.orderdate%TYPE; shipdate ord.shipdate%TYPE; ordid ord.ordid%TYPE := 601;
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
DECLARE orderdate ord.orderdate%TYPE; shipdate ord.shipdate%TYPE; ordid ord.ordid%TYPE := 601;
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;. . .
IF-THEN-ELSE IF-THEN-ELSE Statement Execution Statement Execution
FlowFlow
IF-THEN-ELSE IF-THEN-ELSE Statement Execution Statement Execution
FlowFlowIF conditionIF condition
TRUETRUE
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.
ExampleExample...IF v_shipdate - v_orderdate < 5 THEN v_ship_flag := 'Acceptable';ELSE v_ship_flag := 'Unacceptable';END IF;...
...IF v_shipdate - v_orderdate < 5 THEN v_ship_flag := 'Acceptable';ELSE v_ship_flag := 'Unacceptable';END IF;...
IF-THEN-ELSIF IF-THEN-ELSIF Statement Execution Statement Execution
FlowFlow
IF-THEN-ELSIF IF-THEN-ELSIF Statement Execution Statement Execution
FlowFlowIF conditionIF condition
TRUETRUE
THEN actionsTHEN actionsTHEN actionsTHEN actions
FALSEFALSE
ELSIFELSIFconditioncondition
ELSIFELSIFconditioncondition
TRUETRUE
THEN actionsTHEN actionsTHEN actionsTHEN actions
FALSEFALSE
ELSEELSEactionsactionsELSEELSE
actionsactions
IF-THEN-ELSIF IF-THEN-ELSIF StatementsStatements
IF-THEN-ELSIF IF-THEN-ELSIF StatementsStatements
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.
ExampleExample. . .IF v_start > 100 THEN v_start := 2 * v_start;ELSIF v_start >= 50 THEN v_start := .5 * v_start;ELSE v_start := .1 * v_start;END IF;. . .
. . .IF v_start > 100 THEN v_start := 2 * v_start;ELSIF v_start >= 50 THEN v_start := .5 * v_start;ELSE v_start := .1 * v_start;END IF;. . .
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.
NOT
TRUE
FALSE
NULL
OR
TRUE
FALSE
NULL
TRUE FALSE NULL
FALSE
TRUE
NULL
AND
TRUE
FALSE
NULL
TRUE FALSE NULL
TRUE
NULL NULL
NULL
FALSE FALSE
FALSE
FALSE
FALSE
TRUE
TRUE
TRUE
TRUETRUE
FALSE
NULL NULL
NULL
Boolean ConditionsBoolean ConditionsBoolean ConditionsBoolean Conditions
What is the value of V_FLAG in What is the value of V_FLAG in each case?each case?
What is the value of V_FLAG in What is the value of V_FLAG in each case?each case?
V_REORDER_FLAG V_AVAILABLE_FLAG V_FLAG
TRUE TRUE
TRUE FALSE
NULL TRUE
NULL FALSE
v_flag := v_reorder_flag AND v_available_flag; v_flag := v_reorder_flag AND v_available_flag;
TRUETRUE
FALSEFALSE
NULLNULL
FALSEFALSE
Iterative Control: LOOP Iterative Control: LOOP StatementsStatements
Iterative Control: LOOP Iterative Control: LOOP StatementsStatements
Loops repeat a statement or Loops repeat a statement or sequence of statements multiple sequence of statements multiple times.times.
There are three loop types:There are three loop types: Basic loopBasic loop FOR loopFOR loop WHILE loopWHILE loop
Loops repeat a statement or Loops repeat a statement or sequence of statements multiple sequence of statements multiple times.times.
There are three loop types:There are three loop types: Basic loopBasic loop FOR loopFOR loop WHILE loopWHILE loop
Basic LoopBasic LoopBasic LoopBasic Loop
SyntaxSyntax SyntaxSyntaxLOOP statement1; . . . EXIT [WHEN condition];END LOOP;
LOOP statement1; . . . EXIT [WHEN condition];END LOOP;
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
Composite DatatypesComposite DatatypesComposite DatatypesComposite Datatypes
Types:Types: PL/SQL RECORDSPL/SQL RECORDS PL/SQL TABLESPL/SQL TABLES
Contain internal componentsContain internal components
Types:Types: PL/SQL RECORDSPL/SQL RECORDS PL/SQL TABLESPL/SQL TABLES
Contain internal componentsContain internal components
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;
field_name {field_type | variable%TYPE | table.column%TYPE | table%ROWTYPE} [[NOT NULL] {:= | DEFAULT} expr]
field_name {field_type | variable%TYPE | table.column%TYPE | table%ROWTYPE} [[NOT NULL] {:= | DEFAULT} expr]
Creating a PL/SQL Creating a PL/SQL RecordRecord
Creating a PL/SQL Creating a PL/SQL RecordRecord
Declare variables to store the Declare variables to store the name, job, and salary of a new name, job, and salary of a new employee.employee.
ExampleExample
Declare variables to store the Declare variables to store the name, job, and salary of a new name, job, and salary of a new employee.employee.
ExampleExample... TYPE emp_record_type IS RECORD (ename VARCHAR2(10), job VARCHAR2(9), sal NUMBER(7,2)); emp_record emp_record_type;...
... TYPE emp_record_type IS RECORD (ename VARCHAR2(10), job VARCHAR2(9), sal NUMBER(7,2)); emp_record emp_record_type;...
PL/SQL Record StructurePL/SQL Record StructurePL/SQL Record StructurePL/SQL Record Structure
Field1 (datatype)Field1 (datatype) Field2 (datatype) Field3 (datatype) Field2 (datatype) Field3 (datatype)
empno number(4) ename varchar2(10) job varchar2(9)
Field1 (datatype)Field1 (datatype) Field2 (datatype) Field3 (datatype) Field2 (datatype) Field3 (datatype)
ExampleExampleExampleExample
The %ROWTYPE The %ROWTYPE AttributeAttribute
The %ROWTYPE The %ROWTYPE AttributeAttribute
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.
dept_record dept%ROWTYPE; dept_record dept%ROWTYPE;
emp_record emp%ROWTYPE; emp_record emp%ROWTYPE;
%ROWTYPE Example%ROWTYPE Example
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
PL/SQL TablesPL/SQL TablesPL/SQL TablesPL/SQL Tables
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.
PL/SQL Table StructurePL/SQL Table StructurePL/SQL Table StructurePL/SQL Table Structure
Primary keyPrimary key ColumnColumn ...... ......
11 JonesJones 22 SmithSmith 33 MaduroMaduro
...... ......
BINARY_INTEGERBINARY_INTEGER ScalarScalar
Tables ExampleTables ExampleTables ExampleTables Example
SQL> DECLARESQL> DECLARE TYPE ename_table_type IS TABLE OF TYPE ename_table_type IS TABLE OF
emp.ename%TYPE INDEX BY emp.ename%TYPE INDEX BY BINARY_INTEGER;BINARY_INTEGER;
ename_table ename_table_type;ename_table ename_table_type; BEGINBEGIN ename_table(2):='Mike';ename_table(2):='Mike';
DBMS_OUTPUT.PUT_LINE(ename_table(DBMS_OUTPUT.PUT_LINE(ename_table(2));2));
END;END; //MikeMike
SQL> DECLARESQL> DECLARE TYPE ename_table_type IS TABLE OF TYPE ename_table_type IS TABLE OF
emp.ename%TYPE INDEX BY emp.ename%TYPE INDEX BY BINARY_INTEGER;BINARY_INTEGER;
ename_table ename_table_type;ename_table ename_table_type; BEGINBEGIN ename_table(2):='Mike';ename_table(2):='Mike';
DBMS_OUTPUT.PUT_LINE(ename_table(DBMS_OUTPUT.PUT_LINE(ename_table(2));2));
END;END; //MikeMike
CursorsCursorsCursorsCursors
SQL CursorSQL CursorSQL CursorSQL Cursor 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.
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
Number of rows
processed
Parsed commandstatement
Database Server Memory
SQL Cursor AttributesSQL Cursor AttributesSQL Cursor AttributesSQL Cursor Attributes
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
empno=7900;empno=7900; r:=SQL%ROWCOUNT;r:=SQL%ROWCOUNT; DBMS_OUTPUT.PUT_LINE(r);DBMS_OUTPUT.PUT_LINE(r); END;END; //11
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
Explicit Cursor FunctionsExplicit Cursor FunctionsExplicit Cursor FunctionsExplicit Cursor Functions
Active setActive set
Current rowCurrent rowCursor
7369 SMITH CLERK
7566 JONES MANAGER
7788 SCOTT ANALYST
7876 ADAMS CLERK
7902 FORD ANALYST
Controlling Explicit Controlling Explicit CursorsCursors
Controlling Explicit Controlling Explicit CursorsCursors
• Create a Create a named named SQL areaSQL area
DECLAREDECLAREDECLAREDECLARE
• Identify Identify the active the active setset
OPENOPENOPENOPEN
• Load the Load the current current row into row into variablesvariables
FETCHFETCHFETCHFETCH
• Test for Test for existing existing rowsrows
EMPTY?
• Return to Return to FETCH if FETCH if rows rows foundfound
NoNo
• Release Release the active the active setset
CLOSECLOSECLOSECLOSEYesYes
Controlling Explicit Controlling Explicit CursorsCursors
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.
CLOSE cursor_name;CLOSE cursor_name;
Explicit Cursor Explicit Cursor AttributesAttributes
Explicit Cursor Explicit Cursor AttributesAttributes Obtain status information about Obtain status information about
a cursor.a cursor.
Obtain status information about Obtain status information about a cursor.a cursor.Attribute Type Description
%ISOPEN Boolean Evaluates to TRUE if the cursor is open
%NOTFOUND Boolean Evaluates to TRUE if the most recent fetch does not return a row
%FOUND Boolean Evaluates to TRUE if the mostrecent fetch returns a row; complement of %NOTFOUND
%ROWCOUNT Number Evaluates to the total number of rows returned so far
Controlling Multiple Controlling Multiple FetchesFetches
Controlling Multiple Controlling Multiple FetchesFetches
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.
Explicit Cursor %ISOPEN Explicit Cursor %ISOPEN ExampleExample
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;
Handling Handling ExceptionsExceptionsHandling Handling
ExceptionsExceptions
Handling Exceptions Handling Exceptions with PL/SQLwith PL/SQL
Handling Exceptions Handling Exceptions with PL/SQLwith PL/SQL
What is an exception?What is an exception?Identifier in PL/SQL that is raised Identifier in PL/SQL that is raised during executionduring execution
How is it raised?How is it raised? An Oracle error occurs.An Oracle error occurs. You raise it explicitly.You raise it explicitly.
How do you handle it?How do you handle it? Trap it with a handler.Trap it with a handler.
What is an exception?What is an exception?Identifier in PL/SQL that is raised Identifier in PL/SQL that is raised during executionduring execution
How is it raised?How is it raised? An Oracle error occurs.An Oracle error occurs. You raise it explicitly.You raise it explicitly.
How do you handle it?How do you handle it? Trap it with a handler.Trap it with a handler.
Handling ExceptionsHandling ExceptionsHandling ExceptionsHandling Exceptions
Trap the Trap the exceptionexception
DECLAREDECLARE
BEGINBEGIN
END;END;
Exception Exception is raisedis raised
EXCEPTIONEXCEPTION
Exception Exception is trappedis trapped
Exception TypesException TypesException TypesException Types
Predefined Oracle ServerPredefined Oracle Server Non-predefined Oracle ServerNon-predefined Oracle Server User-definedUser-defined
Predefined Oracle ServerPredefined Oracle Server Non-predefined Oracle ServerNon-predefined Oracle Server User-definedUser-defined
}} Implicitly Implicitly raisedraised
Explicitly raisedExplicitly raised
Trapping ExceptionsTrapping ExceptionsTrapping ExceptionsTrapping Exceptions
EXCEPTION WHEN exception1 [OR exception2 . . .] THEN statement1; statement2; . . . [WHEN exception3 [OR exception4 . . .] THEN statement1; statement2; . . .] [WHEN OTHERS THEN statement1; statement2; . . .]
EXCEPTION WHEN exception1 [OR exception2 . . .] THEN statement1; statement2; . . . [WHEN exception3 [OR exception4 . . .] THEN statement1; statement2; . . .] [WHEN OTHERS THEN statement1; statement2; . . .]
SyntaxSyntax SyntaxSyntax
Trapping Exceptions Trapping Exceptions GuidelinesGuidelines
Trapping Exceptions Trapping Exceptions GuidelinesGuidelines
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.
Sample predefined exceptions: Sample predefined exceptions:
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.
Sample predefined exceptions: Sample predefined exceptions: Error Code Exception Name Description ORA-00001 DUP_VAL_ON_INDEX Unique constraint violated ORA-01001 INVALID_CURSOR Illegal cursor operation
ORA-01403 NO_DATA_FOUND Query returns no records
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
Predefined ExceptionPredefined ExceptionPredefined ExceptionPredefined Exception
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
Exception-handlingException-handlingsectionsection
Less-common errors that have not been given predefined namesLess-common errors that have not been given predefined names
DECLARE e_emps_remaining EXCEPTION; PRAGMA EXCEPTION_INIT (
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;
DECLARE e_emps_remaining EXCEPTION; PRAGMA EXCEPTION_INIT (
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.
e_emps_remaining EXCEPTION; 1PRAGMA EXCEPTION_INIT (
e_emps_remaining, -2292); 2
e_emps_remaining 3
Functions for Trapping Functions for Trapping ExceptionsExceptions
Functions for Trapping Functions for Trapping ExceptionsExceptions
SQLCODESQLCODEReturns the numeric value for the Returns the numeric value for the error codeerror code
SQLERRMSQLERRMReturns the message associated with Returns the message associated with the error numberthe error number
SQLCODESQLCODEReturns the numeric value for the Returns the numeric value for the error codeerror code
SQLERRMSQLERRMReturns the message associated with Returns the message associated with the error numberthe error number
Functions for Trapping Functions for Trapping ExceptionsExceptions
Functions for Trapping Functions for Trapping ExceptionsExceptions
DECLARE v_error_code NUMBER; v_error_message VARCHAR2(255);BEGIN...EXCEPTION... WHEN OTHERS THEN ROLLBACK; v_error_code := SQLCODE ; v_error_message := SQLERRM ;
INSERT INTO errors
VALUES(v_error_code, v_error_message);END;
ExampleExample ExampleExample
SQLCODESQLERRM
Trapping User-Defined Trapping User-Defined ExceptionsExceptions
Trapping User-Defined Trapping User-Defined ExceptionsExceptions
• Name the Name the exceptionexception
DeclareDeclare
DeclarativeDeclarativesectionsection
RaiseRaise
• Explicitly raise Explicitly raise the exception by the exception by using the RAISE using the RAISE statementstatement
ExecutableExecutablesectionsection
Reference Reference
• Handle the Handle the raised raised exceptionexception
Exception-handlingException-handlingsectionsection
User-Defined ExceptionUser-Defined ExceptionUser-Defined ExceptionUser-Defined Exception
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
raise_application_error (error_number,message[, {TRUE | FALSE}]);
RAISE_APPLICATION_ERRRAISE_APPLICATION_ERROROR
ExampleExample
RAISE_APPLICATION_ERRRAISE_APPLICATION_ERROROR
ExampleExample……
EXCEPTIONEXCEPTION
WHEN NO_DATA_FOUND THENWHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR(-RAISE_APPLICATION_ERROR(-20201, 'Invalid Number');20201, 'Invalid Number');
END;END;
……
EXCEPTIONEXCEPTION
WHEN NO_DATA_FOUND THENWHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR(-RAISE_APPLICATION_ERROR(-20201, 'Invalid Number');20201, 'Invalid Number');
END;END;