+ All Categories
Home > Documents > Copyright Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

Copyright Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

Date post: 05-Jan-2016
Category:
Upload: lee-hoover
View: 220 times
Download: 0 times
Share this document with a friend
37
Copyright Oracle Corporation, 1998. All rights reserved. 16 16 Declaring Variables
Transcript
Page 1: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

Copyright Oracle Corporation, 1998. All rights reserved.

1616

Declaring VariablesDeclaring Variables

Page 2: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-2 Copyright Oracle Corporation, 1998. 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

Page 3: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-3 Copyright Oracle Corporation, 1998. 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.

Page 4: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-4 Copyright Oracle Corporation, 1998. All rights reserved.

Benefits of PL/SQLBenefits of PL/SQL

IntegrationIntegrationIntegrationIntegration

ApplicationApplication

Oracle ServerOracle ServerSharedSharedlibrarylibrary

Page 5: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-5 Copyright Oracle Corporation, 1998. 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

Improved PerformanceImproved PerformanceImproved PerformanceImproved Performance

Page 6: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-6 Copyright Oracle Corporation, 1998. All rights reserved.

Benefits of PL/SQLBenefits of PL/SQL

Modularize program developmentModularize program developmentModularize program developmentModularize program development

DECLAREDECLARE

BEGINBEGIN

EXCEPTIONEXCEPTION

END;END;

Page 7: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-7 Copyright Oracle Corporation, 1998. All rights reserved.

Benefits of PL/SQLBenefits of PL/SQL

• It is portable.

• You can declare identifiers.

• It is portable.

• You can declare identifiers.

Page 8: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-8 Copyright Oracle Corporation, 1998. All rights reserved.

Benefits of PL/SQLBenefits of PL/SQL

• You can program with procedural language control structures.

• It can handle errors.

• You can program with procedural language control structures.

• It can handle errors.

Page 9: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-9 Copyright Oracle Corporation, 1998. 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 whenerrors occur

• END; – Mandatory

• DECLARE – Optional

– Variables, cursors, user-defined exceptions

• BEGIN – Mandatory

– SQL statements

– PL/SQL statements

• EXCEPTION – Optional

– Actions to perform whenerrors occur

• END; – Mandatory

DECLAREDECLARE

BEGINBEGIN

EXCEPTIONEXCEPTION

END;END;

Page 10: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-10 Copyright Oracle Corporation, 1998. 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;

Page 11: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-11 Copyright Oracle Corporation, 1998. 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;

Page 12: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-12 Copyright Oracle Corporation, 1998. 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;

Page 13: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-13 Copyright Oracle Corporation, 1998. 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

Page 14: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-14 Copyright Oracle Corporation, 1998. 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.

Page 15: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-15 Copyright Oracle Corporation, 1998. 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

Page 16: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-17 Copyright Oracle Corporation, 1998. All rights reserved.

TRUETRUE

Types 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

Page 17: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-18 Copyright Oracle Corporation, 1998. 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;

Page 18: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-19 Copyright Oracle Corporation, 1998. All rights reserved.

Declaring PL/SQL VariablesDeclaring PL/SQL Variables

GuidelinesGuidelines

• Follow naming conventions.

• Initialize variables designated as NOT NULL.

• 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.

• Initialize identifiers by using the assignment operator (:=) or the DEFAULT reserved word.

• Declare at most one identifier per line.

Page 19: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-20 Copyright Oracle Corporation, 1998. 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

Page 20: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-21 Copyright Oracle Corporation, 1998. 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;

Page 21: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-22 Copyright Oracle Corporation, 1998. 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

Page 22: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-23 Copyright Oracle Corporation, 1998. All rights reserved.

Scalar DatatypesScalar Datatypes

• Hold a single value

• Have no internal components

• Hold a single value

• Have no internal components

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.”

TRUETRUE

256120.08256120.08

Page 23: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-24 Copyright Oracle Corporation, 1998. All rights reserved.

Base 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

Page 24: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-25 Copyright Oracle Corporation, 1998. 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

Page 25: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-26 Copyright Oracle Corporation, 1998. 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

Page 26: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-27 Copyright Oracle Corporation, 1998. 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;...

Page 27: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-28 Copyright Oracle Corporation, 1998. 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.

Page 28: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-29 Copyright Oracle Corporation, 1998. All rights reserved.

Composite DatatypesComposite Datatypes

• Have internal components that can be manipulated individually

• PL/SQL TABLES

• PL/SQL RECORDS

• NESTED TABLE

• VARRAY types

• Have internal components that can be manipulated individually

• PL/SQL TABLES

• PL/SQL RECORDS

• NESTED TABLE

• VARRAY types

Page 29: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-30 Copyright Oracle Corporation, 1998. All rights reserved.

LOB Datatype VariablesLOB Datatype Variables

RecipeRecipe(CLOB)(CLOB)

PhotoPhoto(BLOB)(BLOB)

MovieMovie(BFILE)(BFILE)

NCLOBNCLOB

Page 30: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-31 Copyright Oracle Corporation, 1998. All rights reserved.

Bind VariablesBind Variables

Server

O/SO/SBind VariableBind Variable

Page 31: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-32 Copyright Oracle Corporation, 1998. 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;

Page 32: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-33 Copyright Oracle Corporation, 1998. All rights reserved.

Example:Example:

VARIABLE g_salary NUMBERVARIABLE g_salary NUMBER

BEGINBEGIN

SELECT salary INTO :g_salary FROM empSELECT salary INTO :g_salary FROM emp

WHERE emp_id = 178;WHERE emp_id = 178;

END;END;

//

PRINT g_salaryPRINT g_salary

Example:Example:

VARIABLE g_salary NUMBERVARIABLE g_salary NUMBER

BEGINBEGIN

SELECT salary INTO :g_salary FROM empSELECT salary INTO :g_salary FROM emp

WHERE emp_id = 178;WHERE emp_id = 178;

END;END;

//

PRINT g_salaryPRINT g_salary

Page 33: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-34 Copyright Oracle Corporation, 1998. All rights reserved.

ExampleExample

SET SERVEROUTPUT ONSET SERVEROUTPUT ON

DEFINE p_annual_sal = 60000DEFINE p_annual_sal = 60000

DECLAREDECLARE

v_salv_sal NUMBER(9,2) := &p_annual_sal;NUMBER(9,2) := &p_annual_sal;

BEGINBEGIN

v_sal := v_sal/12;v_sal := v_sal/12;

DBMS_OUTPUT.PUT_LINE (‘The monthly salary is ‘||DBMS_OUTPUT.PUT_LINE (‘The monthly salary is ‘||TO_CHAR(v_sal));TO_CHAR(v_sal));

END;END;

//

SET SERVEROUTPUT ONSET SERVEROUTPUT ON

DEFINE p_annual_sal = 60000DEFINE p_annual_sal = 60000

DECLAREDECLARE

v_salv_sal NUMBER(9,2) := &p_annual_sal;NUMBER(9,2) := &p_annual_sal;

BEGINBEGIN

v_sal := v_sal/12;v_sal := v_sal/12;

DBMS_OUTPUT.PUT_LINE (‘The monthly salary is ‘||DBMS_OUTPUT.PUT_LINE (‘The monthly salary is ‘||TO_CHAR(v_sal));TO_CHAR(v_sal));

END;END;

//

Page 34: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-35 Copyright Oracle Corporation, 1998. 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 ONSET 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 ONSET SERVEROUTPUT ON

Page 35: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-36 Copyright Oracle Corporation, 1998. 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;

Page 36: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-37 Copyright Oracle Corporation, 1998. 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

Page 37: Copyright  Oracle Corporation, 1998. All rights reserved. 16 Declaring Variables.

16-38 Copyright Oracle Corporation, 1998. All rights reserved.

Practice OverviewPractice Overview

• Determining validity of declarations

• Developing a simple PL/SQL block

• Determining validity of declarations

• Developing a simple PL/SQL block


Recommended