09.01.2015 Views

PL/SQL User's Guide and Reference

PL/SQL User's Guide and Reference

PL/SQL User's Guide and Reference

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Defining Collection Types<br />

DECLARE<br />

TYPE EmpTabTyp IS TABLE OF emp%ROWTYPE<br />

INDEX BY BINARY_INTEGER;<br />

emp_tab EmpTabTyp;<br />

BEGIN<br />

/* Retrieve employee record. */<br />

SELECT * INTO emp_tab(7468) FROM emp WHERE empno = 7468;<br />

END;<br />

Defining <strong>SQL</strong> Types Equivalent to <strong>PL</strong>/<strong>SQL</strong> Collection Types<br />

To store nested tables <strong>and</strong> varrays inside database tables, you must also declare <strong>SQL</strong><br />

types using the CREATE TYPE statement. The <strong>SQL</strong> types can be used as columns or<br />

as attributes of <strong>SQL</strong> object types.<br />

You can declare equivalent types within <strong>PL</strong>/<strong>SQL</strong>, or use the <strong>SQL</strong> type name in a<br />

<strong>PL</strong>/<strong>SQL</strong> variable declaration.<br />

Nested Table Example<br />

The following <strong>SQL</strong>*Plus script shows how you might declare a nested table in <strong>SQL</strong>,<br />

<strong>and</strong> use it as an attribute of an object type:<br />

CREATE TYPE CourseList AS TABLE OF VARCHAR2(10) -- define type<br />

/<br />

CREATE TYPE Student AS OBJECT ( -- create object<br />

id_num INTEGER(4),<br />

name VARCHAR2(25),<br />

address VARCHAR2(35),<br />

status CHAR(2),<br />

courses CourseList) -- declare nested table as attribute<br />

/<br />

The identifier courses represents an entire nested table. Each element of courses<br />

will store the code name of a college course such as ’Math 1020’.<br />

Varray Example<br />

The script below creates a database column that stores varrays. Each varray element<br />

contains a VARCHAR2.<br />

-- Each project has a 16-character code name.<br />

-- We will store up to 50 projects at a time in a database column.<br />

CREATE TYPE ProjectList AS VARRAY(50) OF VARCHAR2(16);<br />

/<br />

<strong>PL</strong>/<strong>SQL</strong> Collections <strong>and</strong> Records 5-9

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!