1
PL/SQLPL/SQLPL/SQLPL/SQL Declaring VariablesDeclaring Variables Writing Writing ExecutableExecutable Statements Statements Interacting with the Oracle SerInteracting with the Oracle Ser
verver 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 SerInteracting with the Oracle Ser
verver Writing Control StructuresWriting Control Structures Working with Composite Working with Composite
DatatypesDatatypes CursorsCursors Handling ExceptionsHandling Exceptions
2
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
3
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 not case sensitive languagePL/SQL not case sensitive language A semicolon ; must end each PL/SQL A semicolon ; must end each PL/SQL
commandcommand
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 not case sensitive languagePL/SQL not case sensitive language A semicolon ; must end each PL/SQL A semicolon ; must end each PL/SQL
commandcommand
4
Benefits of PL/SQLBenefits of PL/SQLBenefits of PL/SQLBenefits of PL/SQL
IntegrationIntegration IntegrationIntegration
ApplicationApplication
Oracle ServerOracle ServerSharedSharedlibrarylibrary
5
Benefits of PL/SQLBenefits of PL/SQLBenefits of PL/SQLBenefits of PL/SQL
ApplicationApplication Other DBMSsOther DBMSs
ApplicationApplicationOracle with
PL/SQLOracle with
PL/SQL
SQLSQL
SQLSQLSQLSQL
SQLSQL
SQLSQLIF...THENIF...THEN
SQLSQLELSEELSE
SQLSQLEND IF;END IF;SQLSQL
Improve performanceImprove performance Improve performanceImprove performance
6
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;
7
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;
8
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;
•These blocks can be entirely separate or nested one within another.•Anonymous blocks are unnamed blocks.•Subprograms are named PL/SQL blocks that can take parameters and can be invoked.
•These blocks can be entirely separate or nested one within another.•Anonymous blocks are unnamed blocks.•Subprograms are named PL/SQL blocks that can take parameters and can be invoked.
10
Declaring Declaring VariablesVariablesDeclaring Declaring VariablesVariables
11
Use of VariablesUse of VariablesUse of VariablesUse of Variables
Use variables for:Use variables for: Temporary storage of dataTemporary storage of data Manipulation of stored valuesManipulation of stored values ReusabilityReusability Ease of maintenanceEase of maintenance
Use variables for:Use variables for: Temporary storage of dataTemporary storage of data Manipulation of stored valuesManipulation of stored values ReusabilityReusability Ease of maintenanceEase of maintenance
12
Handling Variables in Handling Variables in PL/SQLPL/SQL
Handling Variables in Handling Variables in PL/SQLPL/SQL
Declare and initialize variables in Declare and initialize variables in the declaration section.the declaration section.
When you declare variable, the When you declare variable, the variables default value is always variables default value is always NULL NULL
Assign new values to variables in Assign new values to variables in the executable section.the executable section.
Pass values into PL/SQL blocks Pass values into PL/SQL blocks through parameters.through parameters.
View results through output View results through output variables.variables.
Declare and initialize variables in Declare and initialize variables in the declaration section.the declaration section.
When you declare variable, the When you declare variable, the variables default value is always variables default value is always NULL NULL
Assign new values to variables in Assign new values to variables in the executable section.the executable section.
Pass values into PL/SQL blocks Pass values into PL/SQL blocks through parameters.through parameters.
View results through output View results through output variables.variables.
13
TRUETRUE
Types of VariablesTypes of VariablesTypes of VariablesTypes of Variables
25-OCT-9925-OCT-99
AtlantaAtlanta
“Four score and seven years ago
our fathers brought forth upon
this continent, a new nation,
conceived in LIBERTY, and dedicated
to the proposition that all men
are created equal.”256120.08256120.08
14
Types of VariablesTypes of Variables
The slide illustrates the following The slide illustrates the following variable datatypes: variable datatypes: TRUE represents a Boolean value.TRUE represents a Boolean value. 25-OCT-99 represents a DATE.25-OCT-99 represents a DATE. The photograph represents a BLOB.The photograph represents a BLOB. The text of a speech represents a LONG The text of a speech represents a LONG
RAW.RAW. 256120.08 represents a NUMBER datatype 256120.08 represents a NUMBER datatype
with precision and scale.with precision and scale. The movie represents a BFILE.The movie represents a BFILE. The city name represents a VARCHAR2.The city name represents a VARCHAR2.
15
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
16
Types of Variables - Types of Variables - scalarscalar
Types of Variables - Types of Variables - scalarscalar
All PL/SQL variables have a All PL/SQL variables have a datatype, which specifies a datatype, which specifies a storage format, constraints, and storage format, constraints, and valid range of values.valid range of values.
Scalar datatypes Scalar datatypes hold a single hold a single value.value.
The main datatypes are those that The main datatypes are those that correspond to column types.correspond to column types.
PL/SQL also supports Boolean PL/SQL also supports Boolean variables.variables.
All PL/SQL variables have a All PL/SQL variables have a datatype, which specifies a datatype, which specifies a storage format, constraints, and storage format, constraints, and valid range of values.valid range of values.
Scalar datatypes Scalar datatypes hold a single hold a single value.value.
The main datatypes are those that The main datatypes are those that correspond to column types.correspond to column types.
PL/SQL also supports Boolean PL/SQL also supports Boolean variables.variables.
17
Types of Variables - Types of Variables - scalarscalar
18
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;
19
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.
20
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
21
Variable Initialization Variable Initialization and Keywordsand Keywords
Variable Initialization Variable Initialization and Keywordsand Keywords
Using:Using: Assignment operator (:=)Assignment operator (:=) DEFAULT keywordDEFAULT keyword NOT NULL constraintNOT NULL constraint
Using:Using: Assignment operator (:=)Assignment operator (:=) DEFAULT keywordDEFAULT keyword NOT NULL constraintNOT NULL constraint
22
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;
23
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
24
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
25
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
26
Types of Variables – Types of Variables – Reference Reference
Types of Variables – Types of Variables – Reference Reference
Directly reference specific database Directly reference specific database column or rowcolumn or row
Assume data type of associated Assume data type of associated column or rowcolumn or row
%TYPE data declaration syntax:%TYPE data declaration syntax: var_namevar_name tablename.fieldnametablename.fieldname%TYPE;%TYPE;
%ROWTYPE data declaration syntax:%ROWTYPE data declaration syntax: variable_namevariable_name tablenametablename%ROWTYPE;%ROWTYPE;
Directly reference specific database Directly reference specific database column or rowcolumn or row
Assume data type of associated Assume data type of associated column or rowcolumn or row
%TYPE data declaration syntax:%TYPE data declaration syntax: var_namevar_name tablename.fieldnametablename.fieldname%TYPE;%TYPE;
%ROWTYPE data declaration syntax:%ROWTYPE data declaration syntax: variable_namevariable_name tablenametablename%ROWTYPE;%ROWTYPE;
27
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
28
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;...
29
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.
30
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
31
LOB Datatype VariablesLOB Datatype VariablesLOB Datatype VariablesLOB Datatype VariablesBookBook
(CLOB)(CLOB)
PhotoPhoto(BLOB)(BLOB)
MovieMovie(BFILE)(BFILE)
NCLOBNCLOB
32
Displaying PL/SQL Displaying PL/SQL Program Output in Program Output in
SQL*PlusSQL*Plus PL/SQL output bufferPL/SQL output buffer
Memory area on database server Memory area on database server Stores program’s output values before Stores program’s output values before
they are displayed to userthey are displayed to user Should increase sizeShould increase size
SET SERVEROUTPUT ON SIZE SET SERVEROUTPUT ON SIZE buffer_sizebuffer_size Default buffer size Default buffer size
2000 bytes2000 bytes
33
Displaying PL/SQL Displaying PL/SQL Program Output in Program Output in
SQL*Plus (continued)SQL*Plus (continued) Display program outputDisplay program output
DBMS_OUTPUT.PUT_LINE('DBMS_OUTPUT.PUT_LINE('display_texdisplay_textt');'); Display maximum of 255 characters of Display maximum of 255 characters of
text datatext data
34
Writing a PL/SQL Writing a PL/SQL ProgramProgram
Write PL/SQL program in Notepad Write PL/SQL program in Notepad or another text editoror another text editor
Copy and paste program commands Copy and paste program commands into SQL*Plusinto SQL*Plus
Press Enter after last program Press Enter after last program commandcommand
Type front slash ( / )Type front slash ( / ) Then press Enter againThen press Enter again
35
DBMS_OUTPUT.PUT_LINDBMS_OUTPUT.PUT_LINEE
DBMS_OUTPUT.PUT_LINDBMS_OUTPUT.PUT_LINEE
An Oracle-supplied packaged An Oracle-supplied packaged procedureprocedure
An alternative for displaying data An alternative for displaying data from a PL/SQL blockfrom a PL/SQL block
Must be enabled in SQL*Plus with Must be enabled in SQL*Plus with SET SERVEROUTPUT ONSET SERVEROUTPUT ON
An Oracle-supplied packaged An Oracle-supplied packaged procedureprocedure
An alternative for displaying data An alternative for displaying data from a PL/SQL blockfrom a PL/SQL block
Must be enabled in SQL*Plus with Must be enabled in SQL*Plus with SET SERVEROUTPUT ONSET SERVEROUTPUT ON
36
PL/SQL Program PL/SQL Program CommandsCommands
37
SummarySummarySummarySummary
PL/SQL blocks are composed PL/SQL blocks are composed of the following sections: of the following sections: Declarative (optional)Declarative (optional) Executable (required)Executable (required) Exception handling (optional)Exception handling (optional)
A PL/SQL block can be an A PL/SQL block can be an anonymous block, anonymous block, procedure, or function. procedure, or function.
PL/SQL blocks are composed PL/SQL blocks are composed of the following sections: of the following sections: Declarative (optional)Declarative (optional) Executable (required)Executable (required) Exception handling (optional)Exception handling (optional)
A PL/SQL block can be an A PL/SQL block can be an anonymous block, anonymous block, procedure, or function. procedure, or function.
DECLAREDECLARE
BEGINBEGIN
EXCEPTIONEXCEPTION
END;END;
38
SummarySummarySummarySummary
PL/SQL identifiers:PL/SQL identifiers: Are defined in the declarative sectionAre defined in the declarative section Can be of scalar, composite, Can be of scalar, composite,
reference, or LOB datatypereference, or LOB datatype Can be based on the structure of Can be based on the structure of
another variable or database objectanother variable or database object Can be initializedCan be initialized
PL/SQL identifiers:PL/SQL identifiers: Are defined in the declarative sectionAre defined in the declarative section Can be of scalar, composite, Can be of scalar, composite,
reference, or LOB datatypereference, or LOB datatype Can be based on the structure of Can be based on the structure of
another variable or database objectanother variable or database object Can be initializedCan be initialized
Top Related