Upload
ursula
View
39
Download
2
Embed Size (px)
DESCRIPTION
Declaring Variables. Objectives. After completing this lesson, you should be able to do the following: List the benefits of PL/SQL Recognize the basic PL/SQL block and its sections Describe the significance of variables in PL/SQL Declare PL/SQL variables Execute a PL/SQL block. - PowerPoint PPT Presentation
Citation preview
Copyright Oracle Corporation, 1999. All rights reserved.
1616
Declaring VariablesDeclaring Variables
16-2 Copyright Oracle Corporation, 1999. All rights reserved.
ObjectivesObjectives
After completing this lesson, you should After completing this lesson, you should be able to do the following:be able to do the following:
• List the benefits of PL/SQL
• Recognize the basic PL/SQL block and its sections
• Describe the significance of variables in PL/SQL
• Declare PL/SQL variables
• Execute a PL/SQL block
After completing this lesson, you should After completing this lesson, you should be able to do the following:be able to do the following:
• List the benefits of PL/SQL
• Recognize the basic PL/SQL block and its sections
• Describe the significance of variables in PL/SQL
• Declare PL/SQL variables
• Execute a PL/SQL block
16-3 Copyright Oracle Corporation, 1999. All rights reserved.
About PL/SQLAbout PL/SQL
• PL/SQL is an extension to SQL with design features of programming languages.
• Data manipulation and query statements of SQL are included within procedural units of code.
• PL/SQL is an extension to SQL with design features of programming languages.
• Data manipulation and query statements of SQL are included within procedural units of code.
16-4 Copyright Oracle Corporation, 1999. All rights reserved.
Benefits of PL/SQLBenefits of PL/SQL
IntegrationIntegrationIntegrationIntegration
ApplicationApplication
Oracle ServerOracle ServerSharedSharedlibrarylibrary
16-5 Copyright Oracle Corporation, 1999. All rights reserved.
Benefits 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 performanceImprove performanceImprove performance
16-6 Copyright Oracle Corporation, 1999. All rights reserved.
PL/SQL Block StructurePL/SQL Block Structure
• DECLARE – Optional
Variables, cursors, user-defined exceptions
• BEGIN – Mandatory
– SQL statements
– PL/SQL statements
• EXCEPTION – Optional
Actions to perform when errors occur
• END; – Mandatory
• DECLARE – Optional
Variables, cursors, user-defined exceptions
• BEGIN – Mandatory
– SQL statements
– PL/SQL statements
• EXCEPTION – Optional
Actions to perform when errors occur
• END; – MandatoryDECLAREDECLARE
BEGINBEGIN
EXCEPTIONEXCEPTION
END;END;
16-7 Copyright Oracle Corporation, 1999. All rights reserved.
PL/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;
16-8 Copyright Oracle Corporation, 1999. All rights reserved.
Block TypesBlock Types
AnonymousAnonymous ProcedureProcedureFunctionFunction
[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;
16-9 Copyright Oracle Corporation, 1999. All rights reserved.
Program ConstructsProgram Constructs
AnonymousAnonymousblockblock
AnonymousAnonymousblockblock
ApplicationApplicationtriggertrigger
ApplicationApplicationtriggertrigger
Stored Stored procedure/procedure/
functionfunction
Stored Stored procedure/procedure/
functionfunction
DatabaseDatabasetriggertrigger
DatabaseDatabasetriggertrigger
ApplicationApplicationprocedure/procedure/
functionfunction
ApplicationApplicationprocedure/procedure/
functionfunction
PackagedPackagedprocedure/procedure/
functionfunction
PackagedPackagedprocedure/procedure/
functionfunction
DECLAREDECLARE
BEGINBEGIN
EXCEPTIONEXCEPTION
END;END;
16-11 Copyright Oracle Corporation, 1999. All rights reserved.
Use of VariablesUse of Variables
Use variables for:Use variables for:
• Temporary storage of data
• Manipulation of stored values
• Reusability
• Ease of maintenance
Use variables for:Use variables for:
• Temporary storage of data
• Manipulation of stored values
• Reusability
• Ease of maintenance
16-12 Copyright Oracle Corporation, 1999. All rights reserved.
Handling Variables in PL/SQLHandling Variables in PL/SQL
• Declare and initialize variables in the declaration section.
• Assign new values to variables in the executable section.
• Pass values into PL/SQL blocks through parameters.
• View results through output variables.
• Declare and initialize variables in the declaration section.
• Assign new values to variables in the executable section.
• Pass values into PL/SQL blocks through parameters.
• View results through output variables.
16-13 Copyright Oracle Corporation, 1999. All rights reserved.
Types of VariablesTypes of Variables
• PL/SQL variables:
– Scalar
– Composite
– Reference
– LOB (large objects)
• Non-PL/SQL variables: Bind and host variables
• PL/SQL variables:
– Scalar
– Composite
– Reference
– LOB (large objects)
• Non-PL/SQL variables: Bind and host variables
16-15 Copyright Oracle Corporation, 1999. All rights reserved.
Declaring PL/SQL VariablesDeclaring PL/SQL Variables
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;
16-16 Copyright Oracle Corporation, 1999. All rights reserved.
Declaring PL/SQL VariablesDeclaring PL/SQL Variables
GuidelinesGuidelines
• Follow naming conventions.
• Initialize variables designated as NOT NULL and CONSTANT.
• Initialize identifiers by using the assignment operator (:=) or the DEFAULT reserved word.
• Declare at most one identifier per line.
GuidelinesGuidelines
• Follow naming conventions.
• Initialize variables designated as NOT NULL and CONSTANT.
• Initialize identifiers by using the assignment operator (:=) or the DEFAULT reserved word.
• Declare at most one identifier per line.
16-17 Copyright Oracle Corporation, 1999. All rights reserved.
Naming RulesNaming Rules
• Two variables can have the same name, provided they are in different blocks.
• The variable name (identifier) should not be the same as the name of table columns used in the block.
• Two variables can have the same name, provided they are in different blocks.
• The variable name (identifier) should not be the same as the name of table columns used in the 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
16-18 Copyright Oracle Corporation, 1999. All rights reserved.
Assigning Values to VariablesAssigning Values to Variables
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;
16-19 Copyright Oracle Corporation, 1999. All rights reserved.
Variable Initialization and Keywords
Variable Initialization and Keywords
Using:Using:
• Assignment operator (:=)
• DEFAULT keyword
• NOT NULL constraint
Using:Using:
• Assignment operator (:=)
• DEFAULT keyword
• NOT NULL constraint
16-20 Copyright Oracle Corporation, 1999. All rights reserved.
Base Scalar DatatypesBase Scalar Datatypes
• VARCHAR2 (maximum_length)
• NUMBER [(precision, scale)]
• DATE
• CHAR [(maximum_length)]
• LONG
• LONG RAW
• BOOLEAN
• BINARY_INTEGER
• PLS_INTEGER
• VARCHAR2 (maximum_length)
• NUMBER [(precision, scale)]
• DATE
• CHAR [(maximum_length)]
• LONG
• LONG RAW
• BOOLEAN
• BINARY_INTEGER
• PLS_INTEGER
16-22 Copyright Oracle Corporation, 1999. All rights reserved.
Scalar Variable DeclarationsScalar Variable Declarations
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;
ExamplesExamplesExamplesExamples
16-23 Copyright Oracle Corporation, 1999. All rights reserved.
The %TYPE AttributeThe %TYPE Attribute
• Declare a variable according to:
– A database column definition
– Another previously declared variable
• Prefix %TYPE with:
– The database table and column
– The previously declared variable name
• Declare a variable according to:
– A database column definition
– Another previously declared variable
• Prefix %TYPE with:
– The database table and column
– The previously declared variable name
16-24 Copyright Oracle Corporation, 1999. All rights reserved.
Declaring Variables with the %TYPE Attribute
Declaring Variables with the %TYPE Attribute
ExamplesExamplesExamplesExamples
... 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;...
16-25 Copyright Oracle Corporation, 1999. All rights reserved.
Declaring Boolean VariablesDeclaring Boolean Variables
• Only the values TRUE, FALSE, and NULL can be assigned to a Boolean variable.
• The variables are connected by the logical operators AND, OR, and NOT.
• The variables always yield TRUE, FALSE, or NULL.
• Arithmetic, character, and date expressions can be used to return a Boolean value.
• Only the values TRUE, FALSE, and NULL can be assigned to a Boolean variable.
• The variables are connected by the logical operators AND, OR, and NOT.
• The variables always yield TRUE, FALSE, or NULL.
• Arithmetic, character, and date expressions can be used to return a Boolean value.
16-26 Copyright Oracle Corporation, 1999. All rights reserved.
Bind VariablesBind Variables
Server
O/SO/SBind variableBind variable
16-27 Copyright Oracle Corporation, 1999. All rights reserved.
Referencing Non-PL/SQL Variables
Referencing Non-PL/SQL Variables
Store the annual salary into a SQL*Plus Store the annual salary into a SQL*Plus host variable.host variable.
• Reference non-PL/SQL variables as host variables.
• Prefix the references with a colon (:).
Store the annual salary into a SQL*Plus Store the annual salary into a SQL*Plus host variable.host variable.
• Reference non-PL/SQL variables as host variables.
• Prefix the references with a colon (:).
:g_monthly_sal := v_sal / 12;:g_monthly_sal := v_sal / 12;
16-28 Copyright Oracle Corporation, 1999. All rights reserved.
DBMS_OUTPUT.PUT_LINEDBMS_OUTPUT.PUT_LINE
• An Oracle-supplied packaged procedure
• An alternative for displaying data from a PL/SQL block
• Must be enabled in SQL*Plus with SET SERVEROUTPUT ON
• An Oracle-supplied packaged procedure
• An alternative for displaying data from a PL/SQL block
• Must be enabled in SQL*Plus with SET SERVEROUTPUT ON
16-29 Copyright Oracle Corporation, 1999. All rights reserved.
SummarySummary
• PL/SQL blocks are composed of the following sections:
– Declarative (optional)
– Executable (required)
– Exception handling (optional)
• A PL/SQL block can be an anonymous block, procedure, or function.
• PL/SQL blocks are composed of the following sections:
– Declarative (optional)
– Executable (required)
– Exception handling (optional)
• A PL/SQL block can be an anonymous block, procedure, or function.
DECLAREDECLARE
BEGINBEGIN
EXCEPTIONEXCEPTION
END;END;
16-30 Copyright Oracle Corporation, 1999. All rights reserved.
SummarySummary
• PL/SQL identifiers:
– Are defined in the declarative section
– Can be of scalar, composite, reference, or LOB datatype
– Can be based on the structure of another variable or database object
– Can be initialized
• PL/SQL identifiers:
– Are defined in the declarative section
– Can be of scalar, composite, reference, or LOB datatype
– Can be based on the structure of another variable or database object
– Can be initialized
16-34 Copyright Oracle Corporation, 1999. All rights reserved.