05.11.2015 Views

Apress.Expert.Oracle.Database.Architecture.9i.and.10g.Programming.Techniques.and.Solutions.Sep.2005

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

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

CHAPTER 10 ■ DATABASE TABLES 393<br />

ops$tkyte@ORA10G> insert into dept_<strong>and</strong>_emp<br />

2 select dept.*,<br />

3 CAST( multiset( select empno, ename, job, mgr, hiredate, sal, comm<br />

4 from SCOTT.EMP<br />

5 where emp.deptno = dept.deptno ) AS emp_tab_type )<br />

6 from SCOTT.DEPT<br />

7 /<br />

4 rows created.<br />

There are two things to notice here:<br />

• Only “four” rows were created. There are really only four rows in the DEPT_AND_EMP table.<br />

The 14 EMP rows don’t exist independently.<br />

• The syntax is getting pretty exotic. CAST <strong>and</strong> MULTISET is syntax most people have never<br />

used. You will find lots of exotic syntax when dealing with object-relational components<br />

in the database. The MULTISET keyword is used to tell <strong>Oracle</strong> the subquery is expected to<br />

return more than one row (subqueries in a SELECT list have previously been limited to<br />

returning one row). CAST is used to instruct <strong>Oracle</strong> to treat the returned set as a collection<br />

type—in this case, we CAST the MULTISET to be an EMP_TAB_TYPE. CAST is a general-purpose<br />

routine not limited to use in collections. For example, if we wanted to fetch the EMPNO<br />

column from EMP as a VARCHAR2(20) instead of a NUMBER(4) type, we may use the query<br />

SELECT CAST( EMPNO AS VARCHAR2(20) ) E FROM EMP.<br />

We’re now ready to query the data. Let’s see what one row might look like:<br />

ops$tkyte@ORA10G> select deptno, dname, loc, d.emps AS employees<br />

2 from dept_<strong>and</strong>_emp d<br />

3 where deptno = 10<br />

4 /<br />

DEPTNO DNAME LOC EMPLOYEES(EMPNO, ENAME, JOB,<br />

---------- -------------- ------------- ----------------------------<br />

10 ACCOUNTING NEW YORK EMP_TAB_TYPE(EMP_TYPE(7782,<br />

'CLARK', 'MANAGER', 7839, '0<br />

9-JUN-81', 2450, NULL), EMP_<br />

TYPE(7839, 'KING', 'PRESIDEN<br />

T', NULL, '17-NOV-81', 5000,<br />

NULL), EMP_TYPE(7934, 'MILL<br />

ER', 'CLERK', 7782, '23-JAN-<br />

82', 1300, NULL))<br />

All of the data is there, in a single column. Most applications, unless they are specifically<br />

written for the object-relational features, will not be able to deal with this particular column.<br />

For example, ODBC doesn’t have a way to deal with a nested table (JDBC, OCI, Pro*C, PL/SQL,<br />

<strong>and</strong> most other APIs <strong>and</strong> languages do). For those cases, <strong>Oracle</strong> provides a way to un-nest a<br />

collection <strong>and</strong> treat it much like a relational table:

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

Saved successfully!

Ooh no, something went wrong!