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.

392<br />

CHAPTER 10 ■ DATABASE TABLES<br />

7 hiredate date,<br />

8 sal number(7, 2),<br />

9 comm number(7, 2)<br />

10 );<br />

11 /<br />

Type created.<br />

ops$tkyte@ORA10GR1> create or replace type emp_tab_type<br />

2 as table of emp_type<br />

3 /<br />

Type created.<br />

To create a table with a nested table, we need a nested table type. The preceding code creates<br />

a complex object type, EMP_TYPE, <strong>and</strong> a nested table type of that, EMP_TAB_TYPE. In PL/SQL,<br />

this will be treated much like an array would. In SQL, it will cause a physical nested table to be<br />

created. Here is the simple CREATE TABLE statement that uses it:<br />

ops$tkyte@ORA10G> create table dept_<strong>and</strong>_emp<br />

2 (deptno number(2) primary key,<br />

3 dname varchar2(14),<br />

4 loc varchar2(13),<br />

5 emps emp_tab_type<br />

6 )<br />

7 nested table emps store as emps_nt;<br />

Table created.<br />

ops$tkyte@ORA10G> alter table emps_nt add constraint<br />

2 emps_empno_unique unique(empno)<br />

3 /<br />

Table altered.<br />

The important part of this CREATE TABLE is the inclusion of the column EMPS of EMP_TAB_<br />

TYPE <strong>and</strong> the corresponding NESTED TABLE EMPS STORE AS EMPS_NT. This created a real physical<br />

table, EMPS_NT, separate from <strong>and</strong> in addition to the table DEPT_AND_EMP. We add a constraint<br />

on the EMPNO column directly on the nested table to make the EMPNO unique as it was in our<br />

original relational model. We cannot implement our full data model; however, there is the<br />

self-referencing constraint:<br />

ops$tkyte@ORA10G> alter table emps_nt add constraint mgr_fk<br />

2 foreign key(mgr) references emps_nt(empno);<br />

alter table emps_nt add constraint mgr_fk<br />

*<br />

ERROR at line 1:<br />

ORA-30730: referential constraint not allowed on nested table column<br />

This will simply not work. Nested tables do not support referential integrity constraints,<br />

as they cannot reference any other table—even themselves. So, we’ll just skip that for now.<br />

Next, we’ll populate this table with the existing EMP <strong>and</strong> DEPT data:

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

Saved successfully!

Ooh no, something went wrong!