les16

7
<Course name> <Lesson number>-1 Copyright Oracle Corporation, 1998. All rights reserved. 16 16 Declaring Variables Declaring Variables 16-2 Copyright Oracle Corporation, 1998. All rights reserved. Objectives Objectives After completing this lesson, you should be able to do the following: Recognize the basic PL/SQL block and its sections Describe the significance of variables in PL/SQL Distinguish between PL/SQL and non- PL/SQL variables Declare PL/SQL variables Execute a PL/SQL block After completing this lesson, you should be After completing this lesson, you should be able to do the following: able to do the following: Recognize the basic PL/SQL block and its sections Describe the significance of variables in PL/SQL Distinguish between PL/SQL and non- PL/SQL variables Declare PL/SQL variables Execute a PL/SQL block 16-3 Copyright Oracle Corporation, 1998. All rights reserved. PL/SQL Block Structure PL/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; – Mandatory DECLARE DECLARE BEGIN BEGIN EXCEPTION EXCEPTION END; END; 16-4 Copyright Oracle Corporation, 1998. All rights reserved. PL/SQL Block Structure PL/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; DECLARE DECLARE BEGIN BEGIN EXCEPTION EXCEPTION END; END;

Upload: iulia-andreea

Post on 14-Dec-2015

212 views

Category:

Documents


0 download

DESCRIPTION

Database course - Declaring variables in SQL

TRANSCRIPT

Page 1: les16

<Course name> <Lesson number>-1

Copyright Oracle Corporation, 1998. All rights reserved.

1616

Declaring VariablesDeclaring Variables

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

ObjectivesObjectives

After completing this lesson, you should be able to do the following:

• Recognize the basic PL/SQL block and its sections

• Describe the significance of variables in PL/SQL

• Distinguish between PL/SQL and non-PL/SQL variables

• Declare PL/SQL variables

• Execute a PL/SQL block

After completing this lesson, you should be After completing this lesson, you should be

able to do the following:able to do the following:

• Recognize the basic PL/SQL block and its sections

• Describe the significance of variables in PL/SQL

• Distinguish between PL/SQL and non-PL/SQL variables

• Declare PL/SQL variables

• Execute a PL/SQL block

16-3 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;

16-4 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 2: les16

<Course name> <Lesson number>-2

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

Block TypesBlock Types

AnonymousAnonymous ProcedureProcedure FunctionFunction

[DECLARE]

BEGIN--statements

[EXCEPTION]

END;

[DECLARE][DECLARE]

BEGINBEGIN----statementsstatements

[EXCEPTION][EXCEPTION]

END;END;

PROCEDURE nameIS

BEGIN--statements

[EXCEPTION]

END;

PROCEDURE namePROCEDURE nameISIS

BEGINBEGIN----statementsstatements

[EXCEPTION][EXCEPTION]

END;END;

FUNCTION nameRETURN datatypeISBEGIN

--statementsRETURN value;

[EXCEPTION]

END;

FUNCTION nameFUNCTION nameRETURN RETURN datatypedatatypeISIS

BEGINBEGIN----statementsstatementsRETURN value;RETURN value;

[EXCEPTION][EXCEPTION]

END;END;

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

Program ConstructsProgram Constructs

Anonymous

block

AnonymousAnonymous

blockblock

Application

trigger

ApplicationApplication

triggertrigger

Stored

procedure/

function

Stored Stored

procedure/procedure/

functionfunction

Database

trigger

DatabaseDatabase

triggertrigger

Application

procedure/

function

ApplicationApplication

procedure/procedure/

functionfunction

Packaged

procedure/

function

PackagedPackaged

procedure/procedure/

functionfunction

DECLAREDECLARE

BEGINBEGIN

EXCEPTIONEXCEPTION

END;END;

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

Use of VariablesUse of Variables

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-8 Copyright Oracle Corporation, 1998. All rights reserved.

Handling Variables in PL/SQLHandling Variables in PL/SQL

• Declare and initialize variables within the declaration section.

• Assign new values to variables within the executable section.

• Pass values into PL/SQL blocks through parameters.

• View results through output variables.

• Declare and initialize variables within the declaration section.

• Assign new values to variables within the executable section.

• Pass values into PL/SQL blocks through parameters.

• View results through output variables.

Page 3: les16

<Course name> <Lesson number>-3

16-9 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

16-10 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

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

Declaring PL/SQL VariablesDeclaring PL/SQL Variables

Syntax

Examples

SyntaxSyntax

ExamplesExamples

identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr];

identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr];

Declarev_hiredate DATE;v_deptno NUMBER(2) NOT NULL := 10;v_location VARCHAR2(13) := 'Atlanta';c_ comm CONSTANT NUMBER := 1400;

Declarev_hiredate DATE;v_deptno NUMBER(2) NOT NULL := 10;v_location VARCHAR2(13) := 'Atlanta';c_ comm CONSTANT NUMBER := 1400;

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

Declaring PL/SQL VariablesDeclaring PL/SQL Variables

Guidelines

• Follow naming conventions.

• Initialize variables designated as NOT NULL.

• Initialize identifiers by using the assignment operator (:=) or by using 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 by using the DEFAULT reserved word.

• Declare at most one identifier per line.

Page 4: les16

<Course name> <Lesson number>-4

16-13 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.

DECLAREempno NUMBER(4);

BEGINSELECT empno

INTO empnoFROM empWHERE ename = 'SMITH';

END;

DECLAREempno NUMBER(4);

BEGINSELECT empno

INTO empnoFROM empWHERE ename = 'SMITH';

END;

16-14 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';

Syntax

Examples

Set a predefined hiredate for new employees.

SyntaxSyntax

ExamplesExamples

Set a predefined Set a predefined hiredatehiredate for new employees. for new employees.

Set the employee name to “Maduro.”Set the employee name to Set the employee name to ““MaduroMaduro..””

identifier := expr;identifier := expr;

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

Variable Initialization and

Keywords

Variable Initialization and

Keywords

Using

• := Assignment Operator

• DEFAULT

• NOT NULL

Using

• := Assignment Operator

• DEFAULT

• NOT NULL

16-16 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 5: les16

<Course name> <Lesson number>-5

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

ExamplesExamplesExamples

16-19 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

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

Declaring Variables with the

%TYPE Attribute

Declaring Variables with the

%TYPE Attribute

ExamplesExamplesExamples

...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 6: les16

<Course name> <Lesson number>-6

16-21 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 may 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 may be used to return a Boolean value.

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

Composite DatatypesComposite Datatypes

Types

• PL/SQL TABLES

• PL/SQL RECORDS

TypesTypes

• PL/SQL TABLES

• PL/SQL RECORDS

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

LOB Datatype VariablesLOB Datatype Variables

RecipeRecipe

(CLOB)(CLOB)

PhotoPhoto

(BLOB)(BLOB)

MovieMovie

(BFILE)(BFILE)

NCLOBNCLOB

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

Bind VariablesBind Variables

Server

O/SO/S

Bind VariableBind Variable

Page 7: les16

<Course name> <Lesson number>-7

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

Referencing Non-PL/SQL VariablesReferencing Non-PL/SQL Variables

Store the annual salary into a SQL*Plus host variable.

• Reference non-PL/SQL variables as host variables.

• Prefix the references with a colon (:).

Store the annual salary into a SQL*Plus host Store the annual salary into a SQL*Plus host

variable.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-26 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;

16-27 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

16-28 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