oracle database 11g using data types index by tables and cursors in plsql

Upload: yelena-bytenskaya

Post on 02-Jun-2018

270 views

Category:

Documents


2 download

TRANSCRIPT

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    1/50

    | Print | Contents | Close |

    Working with Composite Data Types

    Learning objective

    After completing this topic, you should be able to recognize the steps for creating user-defined PL/SQL records and records with the % !"#$P attribute&

    1. Creating user- e!ine PL"#$L recor s

    Disclaimer

    Although certain aspects of Oracle Database 11g are case and spacing insensitive, acommon coding convention has been used throughout all aspects of this course. This

    convention uses lowercase characters for schema, role, user, and constraint names, andfor permissions, synonyms, and table names (with the e ception of the D!A" table#."owercase characters are also used for column names and user$defined procedure,function, and variable names shown in code. !ppercase characters are used for Oracle%eywords and functions, for view, table, schema, and column names shown in te t, forcolumn aliases that are not shown in &uotes, for pac%ages, and for data dictionary views.

    The spacing convention re&uires one space after a comma and one space before andafter operators that are not Oracle$specific, such as ', $, , and ). There should be nospace between an Oracle$specific %eyword or operator and an opening brac%et, a closingbrac%et and a comma, between the last part of a statement and the closing semicolon, or

    before a statement. *tring literals in single &uotes are an e ception to all convention rulesprovided. +lease use this convention for all interactive parts of this course.$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

    n +" *-", variables of scalar data type can hold only one value, whereas a variable ofcomposite data type can hold multiple values of scalar data type or composite data type.The two %inds of composite data types are

    +" *-" records

    +" *-" collections

    PL"#$L recor s

    +" *-" records are used to treat related but dissimilar data as a logical unit. A +" *-"record can have variables of different types.

    or e ample, you can define a record to hold employee details. This involves storing anemployee number as NUMBER, a first name and a last name as VARCHAR2, and so on. /y

    http://%20window.print%28%29/http://%20window.print%28%29/http://library.skillport.com/courseware/cbtlib/257817/257819/eng/thin/transcript.html#contentshttp://%20parent.window.close%28%29/http://%20parent.window.close%28%29/http://library.skillport.com/courseware/cbtlib/257817/257819/eng/thin/transcript.html#contentshttp://%20parent.window.close%28%29/http://%20window.print%28%29/
  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    2/50

    creating a record to store employee details, you create a logical collective unit. This ma%esdata access and manipulation easier.

    PL"#$L collections

    +" *-" collections are used to treat data as a single unit. 0ollections are of three types

    INDEX BY tables or associative arrays

    nested table

    VARRAY

    2ou should use composite data types when you have all the related data as a single unitand so you can easily access and modify the data. 0omposite data types ma%e dataeasier to manage, relate, and transport.

    An analogy is having a single bag for all laptop components rather than a separate bagfor each component.

    f both +" *-" records and +" *-" collections are composite types, use +" *-" recordswhen you want to store values of different data types that are logically related. f youcreate a record to hold employee details, indicate that all the values stored are relatedbecause they provide information about a particular employee.

    !se +" *-" collections when you want to store values of the same data type. This datatype can also be of the composite type, such as records. 2ou can define a collection tohold the first names of all employees. 2ou may have stored n names in the collection3however, name 1 is not related to name 4. The relation between these names is only thatthey are employee names.

    These collections are similar to arrays in programming languages such as 0, 0'', and5ava.

    A record is a group of related data items stored in fields, each with its own name and datatype. 6emember

    7ach record defined can have as many fields as necessary.

    6ecords can be assigned initial values and can be defined as NOT NULL . ields without initialvalues are initiali8ed to NULL.

    The DEFAULT %eyword can also be used when defining fields. 2ou can define RECORD types and declare user$defined records in the declarative part of any

    bloc%, subprogram, or pac%age. 2ou can declare and reference nested records. One record can be the component of another

    record.

    +" *-" records are user$defined composite types. To use them

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    3/50

    1. define the record in the declarative section of a +" *-" bloc%

    4. declare (and optionally initiali8e# the internal components of this record type

    To define+" *-" record, you use this synta

    type'name

    field'name field'type

    e(pr

    NOT NULL

    type_name

    The type_name is the name of the RECORD type. (This identifier is used to declarerecords.#

    field_name

    The field_name is the name of a field within the record.

    field_type

    The field_type is the data type of the field. ( t represents any +" *-" data type e ceptREF CURSOR . 2ou can use the %TYPE and %ROWTYPE attributes.#

    expr

    The expr is the field_t !e or an initial value.

    NOT NULL

    The NOT NULL constraint prevents assigning nulls to those fields. /e sure to initiali8e theNOT NULL fields.

    2ou can then declare the record using this synta .

    identifier type_name

    ield declarations used in defining a record are li%e variable declarations. 7ach field hasa uni&ue name and a specific data type. There are no predefined data types for +" *-"records, as there are for scalar variables. Therefore, you must create the record type firstand then declare an identifier using that type.

    n this code, a record type, t_"e# , is defined to declare variables to store the name, 9ob,and salary of a new employee. Then a record called $_ "e# of the t_"e# type isdeclared.

    DECLARE TYPE t_"e# IS RECORD &$_'(l )* +e"&,-.

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    4/50

    $_ i)'(l )* +e"&,- def(*lt /000. $_1i"e_d(te e !l ee'31i"e_d(te%t !e. $_"e#/ e !l ee'%" 4t !e-5 $_ "e# t_"e#5BE6IN $_ "e#3$_'(l 78 $_ "e#3$_ i)'(l 9 :005 $_ "e#3$_1i"e_d(te 78 ' 'd(te5 SELECT ; INTO $_ "e#3$_"e#/ FROM e !l ee' WHERE e !l ee_id 8 /005 DBMS_OUTPUT3PUT_LINE&$_ "e#3$_"e#/3l('t_)( e

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    5/50

    n +" *-" records, DEFAULT can define a field. 2ou can declare and referencenested records.

    Option 1 is correct. The DEFAULT keyword can be used when defining fields aswell as in variable declarations.

    Option is incorrect. Records can be assigned initial values and can be definedas NOT NULL . !ields without initial values are initialized to NULL.

    Option " is incorrect. You can define RECORD types and declare user#definedrecords in the declarative section of any block$ subprogram$ or package.

    Option % is correct. You can declare and reference nested records. One recordcan be the component of another record.

    '. Creating recor s with ()*WT+P, attribute

    The %TYPE attribute is used to declare a variable of a column type. The variable has thesame data type and si8e as the table column. The benefit of %TYPE is that you do nothave to change the variable if the column is altered. Also, if the variable is used in anycalculations, you need not worry about its precision.

    The %ROWTYPE attribute is used to declare a record that can hold an entire row of a tableor view. The fields in the record ta%e their names and data types from the columns of thetable or view. The record can also store an entire row of data fetched from a cursor orcursor variable.

    :hen declaring a record, you

    declare a variable according to a collection of columns in a database table or view

    prefi %ROWTYPE with the database table or view fields in the record ta%e their names and data types from the columns of the table or view

    D70"A67identifier reference>6O:T2+73

    The synta for declaring a record consist of these components

    identifier

    reference

    identifier

    The identifier is the name chosen for the record as a whole.

    reference

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    6/50

    The reference is the name of the table, view, cursor, or cursor variable on which the

    record is to be based. (The table or view must e ist for this reference to be valid.#

    n this sample code, a record is declared using %ROWTYPE as a data type specifier.

    The e !_"e# "d record has a structure consisting of fields, where each field representsa column in the EMPLOYEES table.

    DECLAREe !_"e# "d e !l ee'%ROWTYPE5333

    This is not code but simply the structure of the composite variable.

    To reference an individual field, use dot notation record_name.field_name

    or e ample, you reference the commission_pct field in the emp_record record asemp_record.commission_pct

    2ou can then assign a value to the record fieldemp_record.commission_pct:= .35 3

    2ou can assign a list of common values to a record using the SELECT or FETCHstatement. ?a%e sure that the column names appear in the same order as the fields inyour record. 2ou can also assign one record to another if both have the samecorresponding data types.

    A record of type e !l ee'%ROWTYPE and a user$defined record type having analogousfields of the EMPLOYEES table will have the same data type. Therefore, if a user definedrecord contains fields similar to the fields of a %ROWTYPE record, you can assign that user defined record to the %ROWTYPE record.

    2ou use the %ROWTYPE attribute when you are not sure about the structure of theunderlying database table.

    The main advantage of using %ROWTYPE is that it simplifies maintenance. !sing%ROWTYPE ensures that the data types of the variables declared with this attribute changedynamically when the underlying table is altered.

    f a DD" statement changes the columns in a table, then the +" *-" program unit isinvalidated. :hen the program is recompiled, it will automatically reflect the new tableformat.

    The %ROWTYPE attribute is particularly useful when you want to retrieve an entire row

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    7/50

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    8/50

    $_e !l ee_)* +e" )* +e"78 /2@5 $_e !_"e# "eti"ed_e !'%ROWTYPE5BE6IN SELECT e !l ee_id. l('t_)( e. > +_id. ()( e"_id. 1i"e_d(te. 1i"e_d(te. '(l(" . # i''i )_!#t. de!("t e)t_id INTO $_e !_"e# FROM e !l ee' WHERE e !l ee_id 8 $_e !l ee_)* +e"5INSERT INTO "eti"ed_e !' VALUES $_e !_"e#5END5

    SELECT ; FROM "eti"ed_e !'5

    To update a row in a table by using a record, the ROW %eyword is used to represent theentire row. The sample code updates the le($ed(te of the employee. The record isupdated.

    SET VERIFY OFFDECLARE $_e !l ee_)* +e" )* +e"78 /2@5 $_e !_"e# "eti"ed_e !'%ROWTYPE5BE6IN SELECT ; INTO $_e !_"e# FROM "eti"ed_e !'5 $_e !_"e#3le($ed(te78CURRENT_DATE5 UPDATE "eti"ed_e !' SET ROW 8 $_e !_"e# WHERE e !) 8$_e !l ee_)* +e"5END5

    SELECT ; FROM "eti"ed_e !'5

    $uestion

    :hich statements best illustrate the capabilities of the %ROWTYPE attribute;

    Options

    1. %ROWTYPE is identical to %TYPE

    4. %ROWTYPE records can store an entire row

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    9/50

    Option 1 is incorrect. %TYPE has limitations in that it can not define the data of anentire row.

    Option is correct. The %ROWTYPE attribute is used to declare a record that canhold an entire row of a table or view. The record can also store an entire row of

    data fetched from a cursor or cursor variable.

    Option " is correct. The fields in the record take their names and data types fromthe columns of the table or view.

    Option % is incorrect. The reference is the name of the table$ view$ cursor$ orcursor variable on which the record is to be based. The table or view must e&ist for this reference to be valid.

    $uestion

    :hich statements are true about inserting or updating rows using %ROWTYPE;

    Options

    1. The ROW %eyword can be used to represent individual columns

    4. :hen inserting, the number of fields in the record must be e&ual to the number offield names in the INTO clause

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    10/50

    Option % is incorrect. )lthough you have the ability to affect a row using%ROWTYPE$ you may also use a WHERE clause to limit the records that are affected by comparing columnar data within the table.

    #ummary

    A +" *-" record is a collection of individual fields that represent a row in a table. !singrecords, you can group the data into one structure and then manipulate this structure asone entity or logical unit. This helps reduce coding and %eeps the coding easy to maintainand understand.

    The %ROWTYPEattribute is used to declare a record that can hold an entire row of a tableor view. Data types are automatically defined using %ROWTYPE. :hen inserting rowsusing %ROWTYPE, the number of fields in the record must be e&ual to the number of fieldnames in the INTO clause. Also, you can insert an entire row at once using %ROWTYPErecord type.

    Table o! Contents

    | Top o! page |

    | Learning objective |

    | 1. Creating user- e!ine PL"#$L recor s |

    | '. Creating recor s with ()*WT+P, attribute |

    | #ummary |

    0opyright B 4CC *%ill*oft. All rights reserved.*%ill*oft and the *%ill*oft logo are trademar%s or registered trademar%s

    of *%ill*oft in the !nited *tates and certain other countries. All other logos or trademar%s are the property of their respective owners.

    | Print | Contents | Close |

    sing %D,/ 0+ %este Tables an 2&))&+s

    Learning objective

    After completing this topic, you should be able to recognize the steps for creating an )*+ $ table and table of records, and identify the uses of nested tables and.A A$s&

    1. Creating %D,/ 0+ tables

    http://library.skillport.com/courseware/cbtlib/257817/257819/eng/thin/transcript.html#pagetophttp://library.skillport.com/courseware/cbtlib/257817/257819/eng/thin/transcript.html#pagetophttp://library.skillport.com/courseware/cbtlib/257817/257819/eng/thin/transcript.html#objectivehttp://library.skillport.com/courseware/cbtlib/257817/257819/eng/thin/transcript.html#section_1http://library.skillport.com/courseware/cbtlib/257817/257819/eng/thin/transcript.html#section_1http://library.skillport.com/courseware/cbtlib/257817/257819/eng/thin/transcript.html#section_2http://library.skillport.com/courseware/cbtlib/257817/257819/eng/thin/transcript.html#summaryhttp://%20window.print%28%29/http://%20window.print%28%29/http://library.skillport.com/courseware/cbtlib/257817/257820/eng/thin/transcript.html#contentshttp://%20parent.window.close%28%29/http://%20parent.window.close%28%29/http://library.skillport.com/courseware/cbtlib/257817/257819/eng/thin/transcript.html#pagetophttp://library.skillport.com/courseware/cbtlib/257817/257819/eng/thin/transcript.html#objectivehttp://library.skillport.com/courseware/cbtlib/257817/257819/eng/thin/transcript.html#section_1http://library.skillport.com/courseware/cbtlib/257817/257819/eng/thin/transcript.html#section_2http://library.skillport.com/courseware/cbtlib/257817/257819/eng/thin/transcript.html#summaryhttp://%20window.print%28%29/http://library.skillport.com/courseware/cbtlib/257817/257820/eng/thin/transcript.html#contentshttp://%20parent.window.close%28%29/
  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    11/50

    INDEX BY tables are composite types (collections# and are user defined. They can storedata using a primary %ey value as the inde , where the %ey values are not necessarilyse&uential. INDEX BY tables are sets of %ey value pairs.

    INDEX BY tables have only two columns

    A column of integer or string type that acts as the primary %ey. The %ey can be numeric, either

    BINARY_INTE6ER or PLS_INTE6ER . The BINARY_INTE6ER and PLS_INTE6ER %eys re&uireless storage than NUMBER. They are used to represent mathematical integers in a compact formand to implement arithmetic operations by using machine arithmetic. Arithmetic operations onthese data types are faster than NUMBER arithmetic. The %ey can also be of type VARCHAR2 or oneof its subtypes.

    A column of scalar or record data type to hold values. f the column is of scalar type, it can holdonly one value. f the column is of record type, it can hold multiple values.

    The INDEX BY tables are unconstrained in si8e. @owever, the %ey in the PLS_INTE6ER column is restricted to the ma imum value that a PLS_INTE6ER can hold. The %eys canbe both positive and negative. The %eys in INDEX BY tables are not necessarily inse&uence.

    There are two steps involved in creating an INDEX BY table

    1. declare a TABLE data type

    4. declare a variable of that data type

    This is the synta for creating an INDEX BY table.

    T2+7 type_name * TA/"7 OEcolumn_type | variable>T2+7| table.column>T2+7F G OT !""H| table>6O:T2+7G D7I /2 +"*J T7K76 | / A62J T7K76| LA60@A64() size M#H3identifier typeJname3

    These are some %ey components in the synta for an INDEX BY table.

    type'name column'type

    identifier NOT NULL

    type_name

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    12/50

    type'name is the name of the TABLE type. t is a type specifier used in subse&uentdeclarations of the +" *-" table identifiers.

    column_type

    column'type is any scalar or composite data type such as VARCHAR2, DATE, NUMBER, or

    %TYPE. 2ou can use the

    %TYPE attribute to provide the column data type.

    identifier

    identifier is the name of the identifier that represents an entire +" *-" table.

    NOT NULL

    The NOT NULL constraint prevents nulls from being assigned to the +" *-" table of thattype. Do not initiali8e the INDEX BY table.

    INDEX BY tables can have the element of any scalar type.

    They are not automatically populated when you create them. 2ou must programmatically

    populate the INDEX BY tables in your +" *-" programs and then use them.

    This sample code declares an INDEX BY table to store the last names of employees.

    333TYPE e)( e_t(+le_t !e IS TABLE OFe !l ee'3l('t_)( e%TYPEINDEX BY PLS_INTE6ER5333e)( e_t(+le e)( e_t(+le_t !e5

    "i%e the si8e of a database table, the si8e of an INDEX BY table is unconstrained. Thatis, the number of rows in an INDEX BY table can increase dynamically so that yourINDEX BY table grows as new rows are added.

    INDEX BY tables can have one column and a uni&ue identifier to that column, neither ofwhich can be named. The column can belong to any scalar or record data type. Theprimary %ey is either a number or a string. 2ou cannot initiali8e an INDEX BY table in itsdeclaration. An INDEX BY table is not populated at the time of declaration. t contains no%eys or values. An e plicit e ecutable statement is re&uired to populate the INDEX BY table.

    This sample code creates two INDEX BY tables.

    DECLARE TYPE e)( e_t(+le_t !e IS TABLE OF e !l ee'3l('t_)( e%TYPE INDEX BY PLS_INTE6ER5 TYPE 1i"ed(te_t(+le_t !e IS TABLE OF DATE

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    13/50

    INDEX BY PLS_INTE6ER5 e)( e_t(+le e)( e_t(+le_t !e5 1i"ed(te_t(+le 1i"ed(te_t(+le_t !e5BE6IN e)( e_t(+le&/- 78 =CAMERON=5 1i"ed(te_t(+le&,- 78 SYSDATE 9 5 IF e)( e_t(+le3EXISTS&/- THEN INSERT INTO 333 333END5

    2ou use the %ey of the INDEX BY table to access an element in the table. This is thesynta for using the %ey in which i)de belongs to type PLS_INTE6ER .

    D7IJ/2JtableJname(inde #

    This e ample shows how to reference the third row in an INDEX BY table callede)( e_t(+le . The magnitude range of PLS_INTE6ER is G2./@ .@, . @ through2./@ .@, . @ , so the primary %ey value can be negative. nde ing does not need tostart with 1.

    e)( e_t(+le& -

    %ote

    The e i't'&i- method returns TRUE if a row with inde& i is returned. You use

    the e i't' method to prevent an error that is raised in reference to a none&istent table element.

    An INDEX BY table method is a built$in procedure or function that operates on a +" *-"table and is called by using dot notation.

    This is the synta of an INDEX BY table method.

    table_name.method_name G ( parameters # H

    These are the INDEX BY table methods

    EXISTS& n - COUNT FIRST LAST PRIOR&n -

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    14/50

    NEXT&n - DELETE

    EXISTS( n )

    The EXISTS& n - method returns TRUE if the nth element in a +" *-" table e ists.

    COUNT

    The COUNT method returns the number of elements that a +" *-" table currently contains.

    FIRST

    The FIRST method

    returns the first or smallest inde number in a +" *-" table

    returns NULL if the +" *-" table is empty

    LAST

    The LAST method

    returns the last or largest inde number in a +" *-" table

    returns NULL if the +" *-" table is empty

    PRIOR( n )

    The PRIOR&n # method returns the inde number that precedes inde n in a +" *-" table.

    NEXT( n )

    The NEXT&n # method returns the inde number that succeeds inde n in a +" *-" table.

    DELETE

    DELETE removes all elements from a +" *-" table.

    DELETE&n # removes the nth element from a +" *-" table.

    DELETE&m. n # removes all elements in the range m&&&n from a +" *-" table.

    At any particular time, an INDEX BY table declared as a table of scalar data type canstore the details of only one column in a database table. There is often a need to store allthe columns retrieved by a &uery. The INDEX BY table of records offers a solution to this./ecause only one table definition is needed to hold information about all the fields of adatabase table, the table of records greatly increases the functionality of INDEX BY tables.

    n this sample code, you can refer to fields in the de!t_t(+le record because eachelement of the table is a record.

    DECLARE TYPE de!t_t(+le_t !e IS TABLE OF de!("t e)t'%ROWTYPE INDEX BY VARCHAR2&20-5

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    15/50

    de!t_t(+le de!t_t(+le_t !e5 JJ E(#1 ele e)t f de!t_t(+le i' ( "e# "d

    This is the synta to refer to the fields in the record.

    table(inde #.field

    n the sample code, LOCATION_ID represents a field in DEPT_TABLE .

    de!t_t(+le&IT-3l #(ti )_id 78 /@005

    2ou can use the %ROWTYPE attribute to declare a record that represents a row in adatabase table. The differences between the %ROWTYPE attribute and the composite datatype +" *-" record are

    +" *-" record types can be user defined, whereas %ROWTYPE implicitly defines the record. +" *-" records enable you to specify the fields and their data types when declaring them. :hen

    you use %ROWTYPE, you cannot specify the fields. The %ROWTYPE attribute represents a table rowwith all the fields based on the definition of that table.

    !ser$defined records are static. %ROWTYPE records are dynamic because they are based on atable structure. f the table structure changes, the record structure also pic%s up the change.

    This sample code declares an INDEX BY table of records e !_t(+le_t !e totemporarily store the details of employees whose employee Ds are between /00 and/0@ . !sing a loop, the information of the employees from the EMPLOYEES table isretrieved and stored in the INDEX BY table. Another loop is used to print the last names

    from the INDEX BY table.

    ote the use of the FIRST and LAST methods in the e ample.

    DECLARE TYPE e !_t(+le_t !e IS TABLE OF e !l ee'%ROWTYPE INDEX BY PLS_INTE6ER5 _e !_t(+le e !_t(+le_t !e5 ( _# *)t NUMBER& -78 /0@5BE6IN FOR i IN /0033 ( _# *)t

    LOOP SELECT ; INTO _e !_t(+le&i- FROM e !l ee' WHERE e !l ee_id 8 i5 END LOOP5 FOR i IN _e !_t(+le3FIRST33 _e !_t(+le3LAST LOOP DBMS_OUTPUT3PUT_LINE& _e !_t(+le&i-3l('t_)( e-5 END LOOP5

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    16/50

    END5

    %ote

    The sample code demonstrates one way to work with an INDEX BY table ofrecords* however$ you can do the same more efficiently using cursors.

    $uestion

    :hich statements are true about INDEX BY table methods;

    Options

    1. COUNT returns the total number of table elements

    4. EXISTS returns NULL if the +" *-" table is empty

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    17/50

    7lements can be deleted from anywhere in a nested table, leaving a sparse table withnonse&uential %eys. The rows of a nested table are not in any particular order. :hen youretrieve values from a nested table, the rows are given consecutive subscripts startingfrom 1. ested tables can be stored in the database, unli%e INDEX BY tables.

    This is the synta for a nested table.

    T2+7 type_name * TA/"7 OEcolumnJtype | variable>T2+7| table.column>T2+7F G OT !""H| table.>6O:T2+7

    *tarting with Oracle Database 1Cg, nested tables can be compared for e&uality. 2ou canchec% whether an element e ists in a nested table and also whether a nested table is asubset of another.

    @ere is sample code and its output that depicts the use of nested tables.

    DECLARE TYPE l #(ti )_t !e IS TABLE OF l #(ti )'3#it %TYPE5 ffi#e' l #(ti )_t !e5 t(+le_# *)t NUMBER5BE6IN ffi#e' 78 l #(ti )_t !e&=B +( =. =T K =.=Si) (! "e=.=O f "d=-5FOR i i) /33 ffi#e'3# *)t&- LOOP DBMS_OUTPUT3PUT_LINE& ffi#e'&i--5 END LOOP5END5

    JJO*t!*tJJ() ) *' +l #K # !letedB +(T KSi) (! "eO f "d

    f you do not initiali8e a nested table, it is automatically initiali8ed to NULL. 2ou caninitiali8e the ffi#e' nested table by using a constructor.

    A variable$si8e array ( VARRAY# is similar to a +" *-" table, e cept that a VARRAY isconstrained in si8e. A VARRAY is valid in a schema$level table. tems of VARRAY type arecalled VARRAYs. VARRAYs have a fi ed upper bound. 2ou have to specify the upperbound when you declare them. This is similar to arrays in the 0 language.

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    18/50

    The ma imum si8e of a VARRAY is 4 K/, as in nested tables. The distinction between anested table and a VARRAY is the physical storage mode. The elements of a VARRAY arestored contiguously in memory and not in the database. 2ou can create a VARRAY type inthe database by using *-".

    This sample code uses a VARRAY. n this code, the si8e of this VARRAY is restricted to .2ou can initiali8e a VARRAY by using constructors. f you try to initiali8e the VARRAY withmore than three elements, a N*ubscript outside of limitN error message is displayed.

    TYPE l #(ti )_t !e IS VARRAY& - OF l #(ti )'3#it %TYPE5ffi#e' l #(ti )_t !e5

    $uestion

    :hich statements best illustrate nested tables;

    Options

    1. ested table %eys can be a negative value similar to INDEX BY

    4. ested tables that are not e plicitly initiali8ed are initiali8ed to NULL

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    19/50

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    20/50

    | 1. Creating %D,/ 0+ tables |

    | '. sing neste tables an 2&))&+s |

    | #ummary |

    0opyright B 4CC *%ill*oft. All rights reserved.*%ill*oft and the *%ill*oft logo are trademar%s or registered trademar%s

    of *%ill*oft in the !nited *tates and certain other countries. All other logos or trademar%s are the property of their respective owners.

    | Print | Contents | Close |

    Working with %D,/ 0+ Tables an PL"#$L )ecor s

    Learning objective

    After completing this topic, you should be able to define, create, and use )*+ $tables and a PL/SQL record in a gi en scenario&

    ,3ercise overview

    n this e ercise, you are re&uired to identify code lines and segments that complete+" *-" bloc%s based on specified re&uirements.

    This involves the following tas%s

    identifying the code that declares variables and completing a +" *-" bloc% so that it returns there&uired output

    identifying the code that completes the creation of a +" *-" bloc% to retrieve the name of 1Cdepartments from the DEPARTMENTS table, print each department name on the screen, andincorporate an INDEX BY table

    2ou are a database administrator for a company. As part of your responsibilities, youneed to identify code lines and segments that complete +" *-" bloc%s, retrieve the nameof 1C departments, print each department name, and incorporate a table.

    Task 14 Declaring PL"#$L block variables

    2ou have written a +" *-" code bloc%. 2ou need to identify the code in the declarativesection of a +" *-" bloc% to declare variables and assign different values to it.

    #tep 1 o! 5

    http://library.skillport.com/courseware/cbtlib/257817/257820/eng/thin/transcript.html#section_1http://library.skillport.com/courseware/cbtlib/257817/257820/eng/thin/transcript.html#section_2http://library.skillport.com/courseware/cbtlib/257817/257820/eng/thin/transcript.html#summaryhttp://%20window.print%28%29/http://%20window.print%28%29/http://library.skillport.com/courseware/cbtlib/257817/257821/eng/consim/transcript.html#contentshttp://%20parent.window.close%28%29/http://%20parent.window.close%28%29/http://library.skillport.com/courseware/cbtlib/257817/257820/eng/thin/transcript.html#section_1http://library.skillport.com/courseware/cbtlib/257817/257820/eng/thin/transcript.html#section_2http://library.skillport.com/courseware/cbtlib/257817/257820/eng/thin/transcript.html#summaryhttp://%20window.print%28%29/http://library.skillport.com/courseware/cbtlib/257817/257821/eng/consim/transcript.html#contentshttp://%20parent.window.close%28%29/
  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    21/50

    :hich line of code in the declarative section of a +" *-" bloc% declares a variableV_COUNTRYID and assigns a value of CA to it;

    Options

    1. $_# *)t" _id VARCHAR2&20- 78 =CA=5 4. $_# *)t" id VARCHAR&20- 78 =CA=5

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    22/50

    Option 1 is incorrect. To use the %ROWTYPE attribute$ you need to prefi&%ROWTYPE with the database table or view name.

    Option is correct. The %ROWTYPE attribute allows you to declare a variableaccording to a collection of columns in a database table or view. To declare a

    variable with the %ROWTYPE attribute$ you specify the variable name$ followed bythe table or view name and %ROWTYPE.

    Option " is incorrect. The %ROWTYPE attribute should be preceded by the name ofthe table or view. )lso$ the re'uired name of the variable is V_COUNTRY_RECORD not V_COUNTRYRECORD.

    Option % is incorrect. The %ROWTYPE attribute should be preceded by the name ofthe database table or view that contains the re'uired columns.

    ow you now want to display country information in a particular format.

    #tep 5 o! 5

    2ou want to display country information in a way that returns the sample outputC *)t" ID7 CA C *)t" N( e7 C()(d( Re i )7 2 .

    0omplete the code to return this output successfully;

    DECLARE v_cty_id varchar2(20) : !CA!" v_cty_r#c c$%&tri#' RO T*PE"+E,IN SELECT - INTO v_cty_r#c FRO. c$%&tri#' /ERE c$%&try_id UPPER(v_cty_id)" D+.S_OUTPUT PUT_LINE 1 i''i&3 c$d#4 END"

    Options

    1. =C *)t" ID7 =

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    23/50

    =. &=C *)t" ID7 =

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    24/50

    =. TYPE de!t_t(+le_t !e i' t(+le f de!("t e)t'3de!("t e)t_)( e%TYPE INDEX BY PLS_INTE6ER5

    )esult

    This code declares anINDEX BY

    table namedDEPT_TABLE_TYPE

    of type

    DEPARTMENTS3DEPARTMENT_NAMETYPE de!t_t(+le_t !e i' t(+le f de!("t e)t'3de!("t e)t_)( e%TYPEINDEX BY PLS_INTE6ER5

    Option 1 is incorrect. The keyword TYPE is re'uired before the name of the type tocreate an INDEX BY table. )lso$ the % symbol is re'uired between the columntype and TYPE.

    Option is incorrect. The keyword TYPE is re'uired before the name of the type to

    create an INDEX BY table.

    Option " is incorrect. The re'uired type name is DEPT_TABLE_TYPE $ notDEPT3TABLE_TYPE .

    Option % is correct. This line of code declares an INDEX BY table namedDEPT_TABLE_TYPE that is of type DEPARTMENTS3DEPARTMENT_NAME. 2t isinde&ed by PLS_INTE6ER .

    2ou want to declare a variable to temporarily store the name of departments.

    #tep ' o! 6

    :hich line of code declares a variable MY_DEPT_TABLE of typeDEPT_TABLE_TYPE used to temporarily store the name of departments;

    Options

    1. de!t_t(+le_t !e _de!t_t(+le5

    4. de!t_t(+le_t !e TYPE _de!t_t(+le5

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    25/50

    Option 1 is incorrect. The name of the variable should precede the name of thetype.

    Option is incorrect. The TYPE keyword is not re'uired to declare the variableMY_DEPT_TABLE of the type DEPT_TABLE_TYPE . )lso$ the name of the variable

    should precede the name of the type.

    Option " is correct. There are two steps re'uired to create an INDEX BY table.!irst$ you declare a TABLE data type and then you declare a variable of that type.This line of code declares the variable MY_DEPT_TABLE of the typeDEPT_TABLE_TYPE .

    Option % is incorrect. The TYPE keyword is not re'uired to declare the variableMY_DEPT_TABLE of the type DEPT_TABLE_TYPE .

    2ou want to declare two variables with the data type NUMBER and assign some values to

    those variables.

    #tep 5 o! 6

    2ou want to declare two variables, F_LOOP_COUNT and V_DEPTNO, with the datatype NUMBER. 2ou also want to assign an initial value of /0 to F_LOOP_COUNT anda value of 0 to V_DEPTNO.

    :hich lines of code must you include in the declarative section of your +" *-"bloc%;

    Options

    1. f_l !_# *)t NUMBER&2-5$_de!t) NUMBER&@-5

    4. f_l !_# *)t NUMBER&2- 8 /05$_de!t) NUMBER&@- 8 05

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    26/50

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    27/50

    4. $_de!t) 8 $_de!t) 9 /05

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    28/50

    PUT_LINE& _de!t_t(+le&i--5END LOOP5END5

    )esult

    This code enables you to retrieve the department names from an INDEX BY tableFOR i IN /33f_l !_# *)tLOOPDBMS_OUTPUT3PUT_LINE& _de!t_t(+le&i--5END LOOP5END5

    Option 1 is incorrect. 3ithin the loop$ the call to DBMS_OUTPUT3PUT_LINE should reference the implicitly declared counter i and not a value of /0 .

    Option is correct. This code segment loops through the values 1 to 17$ the valueof F_LOOP_COUNT. 8ach iteration of the loop prints out the current value ofMY_DEPT_TABLE&i- . 2n this case$ it prints department names.

    Option " is incorrect. This code segment would result in an error because afunction with the name V_DEPTNO does not e&ist in scope. MY_DEPT_TABLE should be used in the place of V_DEPTNO in the call toDBMS_OUTPUT3PUT_LINE .

    Option % is incorrect. The name of the package DBMS_OUTPUT must precede the procedure PUT_LINE within the loop.

    Table o! Contents

    | Top o! page |

    | Learning objective |

    | ,3ercise overview |

    | Task 14 Declaring PL"#$L block variables |

    | Task '4 Creating PL"#$L block |

    0opyright B 4CC *%ill*oft. All rights reserved.*%ill*oft and the *%ill*oft logo are trademar%s or registered trademar%s

    of *%ill*oft in the !nited *tates and certain other countries. All other logos or trademar%s are the property of their respective owners.

    | Print | Contents | Close |

    http://library.skillport.com/courseware/cbtlib/257817/257821/eng/consim/transcript.html#pagetophttp://library.skillport.com/courseware/cbtlib/257817/257821/eng/consim/transcript.html#pagetophttp://library.skillport.com/courseware/cbtlib/257817/257821/eng/consim/transcript.html#objectivehttp://library.skillport.com/courseware/cbtlib/257817/257821/eng/consim/transcript.html#section_1http://library.skillport.com/courseware/cbtlib/257817/257821/eng/consim/transcript.html#section_1http://library.skillport.com/courseware/cbtlib/257817/257821/eng/consim/transcript.html#section_2http://library.skillport.com/courseware/cbtlib/257817/257821/eng/consim/transcript.html#section_2http://library.skillport.com/courseware/cbtlib/257817/257821/eng/consim/transcript.html#section_3http://library.skillport.com/courseware/cbtlib/257817/257821/eng/consim/transcript.html#section_3http://%20window.print%28%29/http://%20window.print%28%29/http://library.skillport.com/courseware/cbtlib/257817/257823/eng/thin/transcript.html#contentshttp://%20parent.window.close%28%29/http://%20parent.window.close%28%29/http://library.skillport.com/courseware/cbtlib/257817/257821/eng/consim/transcript.html#pagetophttp://library.skillport.com/courseware/cbtlib/257817/257821/eng/consim/transcript.html#objectivehttp://library.skillport.com/courseware/cbtlib/257817/257821/eng/consim/transcript.html#section_1http://library.skillport.com/courseware/cbtlib/257817/257821/eng/consim/transcript.html#section_2http://library.skillport.com/courseware/cbtlib/257817/257821/eng/consim/transcript.html#section_3http://%20window.print%28%29/http://library.skillport.com/courseware/cbtlib/257817/257823/eng/thin/transcript.html#contentshttp://%20parent.window.close%28%29/
  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    29/50

    sing ,3plicit Cursors an Cursor &ttributes

    Learning objective

    After completing this topic, you should be able to identify the steps for declaring andcontrolling e(plicit cursors, and for writing 0! loops to fetch data from them&

    1. n erstan ing e3plicit cursor operations

    7very e ecuted *-" statement by Oracle server has an associated individual cursor.There are two types of cursors

    implicit

    e plicit

    The Oracle server uses wor% areas, called private /, areas , to e ecute *-" statementsand store processing information. 2ou can use e plicit cursors to name a private *-"area and to access its stored information.

    These types of cursors can be used with the *-" statement

    implicit

    e plicit

    implicit

    mplicit cursors are declared by +" *-" implicitly for all dynamic manipulation language(D?"# and +" *-" SELECT statements.

    e3plicit

    or &ueries that return more than one row, e plicit cursors are declared and managed bythe programmer and manipulated through specific statements in the bloc%Ps e ecutableactions.

    The Oracle server implicitly opens a cursor to process each *-" statement that is notassociated with an e plicitly declared cursor. !sing +" *-", you can refer to the mostrecent implicit cursor as the *-" cursor.

    2ou can declare e plicit cursors in +" *-" when you have a SELECT statement thatreturns multiple rows. 2ou can process each row returned by the SELECT statement.

    The set of rows returned by a multiple$row &uery is called the active set . ts si8e is thenumber of rows that meet your search criteria. @ere an e plicit cursor points to thecurrent row in the active set. This enables a program to process the rows one at a time.

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    30/50

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    31/50

    The OPEN statement e ecutes the &uery associated with the cursor, identifies the activeset, and positions the cursor at the first row. The OPEN statement is included in thee ecutable section of the +" *-" bloc%.

    FETC/

    TheFETCH

    statement retrieves the current row and advances the cursor to the ne t rowuntil there are no more rows or a specified condition is met.

    CLOSE

    The CLOSE statement releases the cursor.

    '. Declaring e3plicit cursors

    n the synta to declare a cursor, cursor_name is the +" *-" identifier, and the

    select_statement is used to identify the SELECT statement without an INTO clause.

    0!6*O6 cursor_name *select_statement 3

    The active set of a cursor is determined by the SELECT statement in the cursordeclaration. t is mandatory to have an INTO clause for a SELECT statement in +" *-".@owever, the SELECT statement in the cursor declaration cannot have an INTO clause.This is because you are only defining a cursor in the declarative section and not retrievingany rows into the cursor.

    2ou need to consider these guidelines when declaring a cursor

    do not include the INTO clause in the cursor declaration because it appears later in the FETCH statement

    if processing rows in a specific se&uence is re&uired, use the ORDER BY clause in the &uery the cursor can be any valid SELECT statement, including 9oins, sub&ueries, and so on

    n this e ample, the #_e !_#*"' " is being declared to retrieve the EMPLOYEE_ID andLAST_NAME columns for those employees wor%ing in the department with aDEPARTMENT_ID of 0 .

    DECLARE CURSOR #_e !_#*"' " IS SELECT e !l ee_id. l('t_)( e FROM e !l ee' WHERE de!("t e)t_id 8 05

    n this sample code, the #_de!t_#*"' " cursor is declared to retrieve all the details forthe department with the LOCATION_ID / 00 .

    ote that a variable is used while declaring the cursor. These variables are considered

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    32/50

    bind variables, which must be visible when you are declaring the cursor. These variablesare e amined only once at the time the cursor opens. 7 plicit cursors are used when youhave to retrieve and operate on multiple rows in +" *-". @owever, this e ample showsthat you can use the e plicit cursor even if your SELECT statement returns only one row.

    DECLARE$_l #id NUMBER78 / 005CURSOR #_de!t_#*"' " ISSELECT ; FROM de!("t e)t'WHERE l #(ti )_id 8 $_l #id5333

    OPEN is an e ecutable statement that performs these operations

    1. it dynamically allocates memory for a conte t area

    4. it parses theSELECT

    statement

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    33/50

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    34/50

    Alternatively, you can define a record for the cursor and reference the record in theFETCH INTO clause. Then, you need to test to find out whether the cursor contains rows.f a fetch ac&uires no values, there are no rows left to process in the active set and noerror is recorded.

    DECLARE CURSOR #_e !_#*"' " IS SELECT e !l ee_id. l('t_)( e FROM e !l ee' WHERE de!("t e)t_id 8 05 $_e !) e !l ee'3e !l ee_id%TYPE5 $_l)( e e !l ee'3l('t_)( e%TYPE5BE6IN OPEN #_e !_#*"' "5 FETCH #_e !_#*"' " INTO $_e !) . $_l)( e5 DBMS_OUTPUT3PUT_LINE& $_e !)

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    35/50

    // T +i('

    //, Hi *"

    // C l e)("e'

    The CLOSE statement disables the cursor, releases the conte t area, and undefines theactive set. 2ou should close the cursor after completing the FETCH statement processing.2ou can reopen the cursor if re&uired. A cursor can be reopened only if it is closed. f youattempt to fetch data from a cursor after it is been closed, then an INVALID_CURSOR e ception is raised.

    333 LOOP FETCH #_e !_#*"' " INTO e !) . l)( e5 EXIT WHEN #_e !_#*"' "%NOTFOUND5 DBMS_OUTPUT3PUT_LINE& $_e !)

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    36/50

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    37/50

    FOR e !_"e# "d IN #_e !_#*"' " LOOP DBMS_OUTPUT3PUT_LINE& e !_"e# "d3e !l ee_id

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    38/50

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    39/50

    $_e !_"e# "d #_e !_#*"' "%ROWTYPE5BE6IN OPEN #_e !_#*"' "5 LOOP FETCH #_e !_#*"' " INTO $_e !_"e# "d5 EXIT WHEN #_e !_#*"' "%ROWCOUNT /0 OR#_e !_#*"' "%NOTFOUND5 DBMS_OUTPUT3PUT_LINE& $_e !_"e# "d3e !l ee_id

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    40/50

    =. 2ou can use the %NOTFOUND attribute to determine whether the entire cursor hasbeen processed

    &nswer

    7ach variable must correspond to a column positionally, and you can use the%NOTFOUND attribute to determine the processing of the entire cursor.

    Option 1 is correct. 8ach variable used to fetch data must correspond to thecolumns in size$ type and position.

    Option is incorrect. The FETCH statement retrieves the rows from the cursor oneat a time. )fter each fetch$ the cursor advances to the ne&t row in the active set.

    Option " is incorrect. You can define a record for the cursor and reference therecord in the FETCH INTO clause.

    Option % is correct. You can use the %NOTFOUND attribute to determine whetherthe entire active set has been retrieved. Once the entire cursor has been

    processed$ the %NOTFOUND attribute returns TRUE. 2t returns FALSE if the cursoris still processing.

    $uestion

    :hich statements about e plicit cursor attributes are true;

    Options

    1. %ISOPEN returns a B le() value

    4. %ROWCOUNT allows you to process a fi ed amount of rows

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    41/50

    Option " is incorrect. The %ROWCOUNT attribute can be used for the e&it conditionof a loop. %ROWCOUNT evaluates the total number of rows returned so far.

    Option % is incorrect. :sing %ISOPEN $ you can fetch rows only when the cursor isopen. You use the %ISOPEN cursor attribute to determine whether the cursor is

    open.

    $uestion

    :hich statement accurately describes cursor FOR loops;

    Options

    1. FOR loops are useful in processing implicit cursors

    4. FOR loops must be terminated e plicitly after the cursor has finished processing

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    42/50

    fetch, and close the cursor however, cursor FOR loops do this implicitly.

    7very e plicit cursor and cursor variable has %FOUND, %ISOPEN , %NOTFOUND, and%ROWCOUNT attributes. :hen appended to the cursor variable name, these attributesreturn useful information about the e ecution of a *-" statement.

    Table o! Contents

    | Top o! page |

    | Learning objective |

    | 1. n erstan ing e3plicit cursor operations |

    | '. Declaring e3plicit cursors |

    | 5. Processing e3plicit cursors |

    | #ummary |

    0opyright B 4CC *%ill*oft. All rights reserved.*%ill*oft and the *%ill*oft logo are trademar%s or registered trademar%s

    of *%ill*oft in the !nited *tates and certain other countries. All other logos or trademar%s are the property of their respective owners.

    | Print | Contents | Close |

    sing Cursors with Parameters

    Learning objective

    After completing this topic, you should be able to recognize the steps for declaring andusing cursors with parameters, loc1ing rows, and referencing the current row in ane(plicit cursor&

    1. sing cursors with parameters

    2ou can pass parameters to a cursor when the cursor is opened and the &uery is

    e ecuted. This means that you can open and close an e plicit cursor several times in abloc%, returning a different active set on each occasion. or each e ecution, the previouscursor is closed and reopened with a new set of parameters.

    @ere is the synta for cursor declaration using parameters.

    0!6*O6 cursor_nameG( parameter_name datatype , ...#H

    http://library.skillport.com/courseware/cbtlib/257817/257823/eng/thin/transcript.html#pagetophttp://library.skillport.com/courseware/cbtlib/257817/257823/eng/thin/transcript.html#pagetophttp://library.skillport.com/courseware/cbtlib/257817/257823/eng/thin/transcript.html#objectivehttp://library.skillport.com/courseware/cbtlib/257817/257823/eng/thin/transcript.html#section_1http://library.skillport.com/courseware/cbtlib/257817/257823/eng/thin/transcript.html#section_1http://library.skillport.com/courseware/cbtlib/257817/257823/eng/thin/transcript.html#section_2http://library.skillport.com/courseware/cbtlib/257817/257823/eng/thin/transcript.html#section_2http://library.skillport.com/courseware/cbtlib/257817/257823/eng/thin/transcript.html#section_3http://library.skillport.com/courseware/cbtlib/257817/257823/eng/thin/transcript.html#summaryhttp://%20window.print%28%29/http://%20window.print%28%29/http://library.skillport.com/courseware/cbtlib/257817/257824/eng/thin/transcript.html#contentshttp://%20parent.window.close%28%29/http://%20parent.window.close%28%29/http://library.skillport.com/courseware/cbtlib/257817/257823/eng/thin/transcript.html#pagetophttp://library.skillport.com/courseware/cbtlib/257817/257823/eng/thin/transcript.html#objectivehttp://library.skillport.com/courseware/cbtlib/257817/257823/eng/thin/transcript.html#section_1http://library.skillport.com/courseware/cbtlib/257817/257823/eng/thin/transcript.html#section_2http://library.skillport.com/courseware/cbtlib/257817/257823/eng/thin/transcript.html#section_3http://library.skillport.com/courseware/cbtlib/257817/257823/eng/thin/transcript.html#summaryhttp://%20window.print%28%29/http://library.skillport.com/courseware/cbtlib/257817/257824/eng/thin/transcript.html#contentshttp://%20parent.window.close%28%29/
  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    43/50

    *select_statement 3

    These are the components in the synta for cursor declaration.

    cursor_name parameter_name

    datatype

    select_statement

    cursor_name

    cursor_name is a +" *-" identifier for the declared cursor.

    parameter_name

    parameter_name is the name of a parameter.

    datatype

    datatype is the scalar data type of the parameter.

    select_statement

    select_statement is a SELECT statement without the INTO clause.

    7ach formal parameter in the cursor declaration must have a corresponding actualparameter in the OPEN statement. The parameter notation does not offer greaterfunctionality3 it simply allows you to specify input values easily and clearly. This isparticularly useful when the same cursor is referenced repeatedly.

    O+7 cursor_name ( parameter_value ,.....# 3

    +arameter data types are the same as those for scalar variables, but you do not givethem si8es. The parameter names are for references in the &uery e pression of thecursor.

    n this sample code, a cursor is declared and is defined with one parameter.

    DECLARECURSOR #_e !_#*"' " &de!t) NUMBER- ISSELECT e !l ee_id. l('t_)( eFROM e !l ee'WHERE de!("t e)t_id 8 de!t) 5333BE6INOPEN #_e !_#*"' " &/0-5333CLOSE #_e !_#*"' "5OPEN #_e !_#*"' " &20-5333

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    44/50

    n the sample code, the OPEN statements open the cursor and return different active sets.

    2ou can also pass parameters to the cursor that is used in a cursor FOR loop.

    DECLARE

    CURSOR #_e !_#*"' "&!_de!t) NUMBER. !_> + VARCHAR2-ISSELECT 333BE6INFOR e !_"e# "d IN #_e !_#*"' "&/0. =S(le'=- LOOP 333

    $uestion

    :hich statements are true about using cursors with parameters;

    Options

    1. An e plicit cursor may only be opened once4. Any parameter declared in a cursor must have a corresponding actual parameter in

    the OPEN statement

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    45/50

    '. Locking an re!erencing rows

    f there are multiple sessions for a single database, there is the possibility that the rows of a particular table were updated after you opened the cursor. 2ou see the updated dataonly when you reopen the cursor. Therefore, you should use e plicit loc%ing to denyaccess to other sessions for the duration of a transaction.

    t is better to have loc%s on the rows before you update or delete rows. 2ou can loc% therows with the FOR UPDATE clause in the cursor &uery.

    The FOR UPDATE clause is the last clause in a SELECT statement. t is placed even afterthe ORDER BY clause if that clause e ists. :hen &uerying multiple tables, you can usethe FOR UPDATE clause to confine row loc%ing to particular tables. FOR UPDATE OF# l_)( e&'- loc%s rows only in tables that contain # l_)( e&'- .

    *7"70T ...6O? ...O6 !+DAT7 GO column_reference HG O:A T | :A T n H3

    These are the components in the synta for the FOR UPDATE clause.

    column_reference NOWAIT WAIT n

    column_reference

    column_reference is a column in the table against which the &uery is performed. A listof columns may also be used.

    NO AIT

    The NOWAIT %eyword returns an Oracle server error if the rows are loc%ed by anothersession. This optional %eyword tells the Oracle server not to wait if re&uested rows havebeen loc%ed by another user. 0ontrol is immediately returned to your program so that itcan do other wor% before trying again to ac&uire the loc%. f you omit the NOWAIT %eyword,the Oracle server waits until the rows are available.

    AIT n

    2ou can use WAIT instead of NOWAIT, specify the number of seconds to wait, anddetermine whether the rows are unloc%ed. f the rows are still loc%ed after n seconds, anerror is returned.

    The SELECT 333 FOR UPDATE statement identifies the rows that are to be updated ordeleted, and then loc%s each row in the result set. This is useful when you want to basean update on the e isting values in a row. n this case, you must ensure that the row isnot changed by another session before the update.

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    46/50

    f the Oracle server cannot ac&uire the loc%s on the rows that it needs in a SELECT FORUPDATE operation, it waits indefinitely. 2ou can use NOWAIT to handle such situations. fthe rows are loc%ed by another session and you have specified NOWAIT, opening thecursor results in an error. 2ou can try to open the cursor later.

    DECLARECURSOR #_e !_#*"' " ISSELECT e !l ee_id. l('t_)( e FROM e !l ee'WHERE de!("t e)t_id 8 ,0 FOR UPDATE OF '(l(" NOWAIT5333

    t is not mandatory for the FOR UPDATE OF clause to refer to a column, but it isrecommended for better readability and maintenance.

    To refer to the current row in an e plicit cursor, you can use the WHERE CURRENT OF clause in con9unction with the FOR UPDATE clause.

    n the synta , cursor i s the name of a declared cursor that must have been declared withthe FOR UPDATE clause.

    :@767 0!667 T O cursor 3

    2ou use cursors to update or delete the current row. The WHERE CURRENT OF clause isused in the UPDATE or DELETE statement, whereas the FOR UPDATE clause is specifiedin the cursor declaration.

    This sample code uses the WHERE CURRENT OF clause in an UPDATE statement.

    UPDATE e !l ee'SET '(l(" 8 333WHERE CURRENT OF #_e !_#*"' "5

    2ou can use a combination of the WHERE CURRENT OF clause and the FOR UPDATE clause for updating and deleting the current row from the corresponding database table.This enables you to apply updates and deletes to the row currently being addressed,without the need to e plicitly reference the row D.

    2ou must include the FOR UPDATE clause in the cursor &uery so that the rows are loc%ed

    on OPEN.

    2ou can also use sub&ueries with cursors. A sub&uery is a &uery, usually enclosed byparentheses, that appears within another *-" statement. :hen evaluated, the sub&ueryprovides a value or set of values to the outer &uery.

    *ub&ueries are often used in the WHERE clause of a SELECT statement. They can also beused in the FROM clause, creating a temporary data source for that &uery.

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    47/50

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    48/50

    #tep 7 Open #_de!t_#*"' " , use a simple loop, and fetch values into the variablesdeclared. Display the department number and department name.

    #tep 6 or each department, open #_e !_#*"' " by passing the current departmentnumber as a parameter. *tart another loop and fetch the values of e !_#*"' " into

    variables and print all the details retrieved from the EMPLOYEES table. To print a line afteryou have displayed the details of each department, use appropriate attributes for the e itcondition and chec% whether a cursor is already open before opening the cursor.

    #tep 9 0lose all loops and cursors, end the e ecutable section, and e ecute the script byclic%ing )un #cript .

    This is the sample output of the code.

    $uestion

    :hich statements are true about the FOR UPDATE clause;

    Options

    1. FOR UPDATE OF must refer to a column

    4. FOR UPDATE loc%s rows that are being affected by a transaction

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    49/50

  • 8/10/2019 Oracle Database 11g Using Data Types INDEX by Tables and Cursors in PLSQL

    50/50

    This ensures that the data you are using is not updated by another session after youopen the cursor. 2ou use a WHERE CURRENT OF clause in con9unction with the FORUPDATE clause to reference the current row fetched by the cursor.

    Table o! Contents

    | Top o! page |

    | Learning objective |

    | 1. sing cursors with parameters |

    | '. Locking an re!erencing rows |

    | #ummary |

    0opyright B 4CC *%ill*oft. All rights reserved.*%ill*oft and the *%ill*oft logo are trademar%s or registered trademar%sof *%ill*oft in the !nited *tates and certain other countries.

    All other logos or trademar%s are the property of their respective owners.

    http://library.skillport.com/courseware/cbtlib/257817/257824/eng/thin/transcript.html#pagetophttp://library.skillport.com/courseware/cbtlib/257817/257824/eng/thin/transcript.html#pagetophttp://library.skillport.com/courseware/cbtlib/257817/257824/eng/thin/transcript.html#objectivehttp://library.skillport.com/courseware/cbtlib/257817/257824/eng/thin/transcript.html#section_1http://library.skillport.com/courseware/cbtlib/257817/257824/eng/thin/transcript.html#section_1http://library.skillport.com/courseware/cbtlib/257817/257824/eng/thin/transcript.html#section_2http://library.skillport.com/courseware/cbtlib/257817/257824/eng/thin/transcript.html#section_2http://library.skillport.com/courseware/cbtlib/257817/257824/eng/thin/transcript.html#summaryhttp://library.skillport.com/courseware/cbtlib/257817/257824/eng/thin/transcript.html#pagetophttp://library.skillport.com/courseware/cbtlib/257817/257824/eng/thin/transcript.html#objectivehttp://library.skillport.com/courseware/cbtlib/257817/257824/eng/thin/transcript.html#section_1http://library.skillport.com/courseware/cbtlib/257817/257824/eng/thin/transcript.html#section_2http://library.skillport.com/courseware/cbtlib/257817/257824/eng/thin/transcript.html#summary