-- 관계형 문법
CREATE TABLE dept
( deptno NUMBER(2) PRIMARY KEY
, dname VARCHAR2(14)
, loc VARCHAR2(13)
)
;
CREATE TABLE emp
( empno NUMBER(4) PRIMARY KEY
, ename VARCHAR2(10)
, job VARCHAR2(9)
, mgr NUMBER(4) REFERENCES emp(empno)
, hiredate DATE
, sal NUMBER(7, 2)
, comm NUMBER(7, 2)
, deptno NUMBER(2) REFERENCES dept(deptno)
)
;
-- 중첩테이블 문법
CREATE OR REPLACE TYPE emp_type
AS OBJECT
( empno NUMBER(4)
, ename VARCHAR2(10)
, job VARCHAR2(9)
, mgr NUMBER(4)
, hiredate DATE
, sal NUMBER(7, 2)
, comm NUMBER(7, 2)
)
/
CREATE OR REPLACE TYPE emp_tab_type
AS TABLE OF emp_type
/
CREATE TABLE dept_and_emp
( deptno NUMBER(2) PRIMARY KEY
, dname VARCHAR2(14)
, loc VARCHAR2(13)
, emps emp_tab_type
)
NESTED TABLE emps STORE AS emps_nt
;
ALTER TABLE emps_nt ADD CONSTRAINT emps_empno_unique UNIQUE(empno);
-- 중첩테이블 데이터 삽입
INSERT INTO dept_and_emp
SELECT dept.*
, CAST(MULTISET(SELECT empno, ename, job, mgr, hiredate, sal, comm
FROM emp
WHERE emp.deptno = dept.deptno
) AS emp_tab_type)
FROM dept
;
-- 중첩테이블 조회
SELECT deptno, emps
FROM dept_and_emp
WHERE deptno = 10
;
DEPTNO | EMPS |
---|---|
10 | SCOTT.EMP_TYPE (SCOTT.EMP_TYPE(7782,CLARK,MANAGER,7839,1981-06-09 00:00:00.0,2450,null) ,SCOTT.EMP_TYPE(7839,KING,PRESIDENT,null,1981-11-17 00:00:00.0,5000,null) ,SCOTT.EMP_TYPE(7934,MILLER,CLERK,7782,1982-01-23 00:00:00.0,1300,null)) |
-- 중첩테이블을 풀어내는 방법
SELECT d.deptno, e.empno, e.ename
FROM dept_and_emp d
, TABLE(emps) e
WHERE d.deptno = 10
;
DEPTNO | EMPNO | ENAME |
---|---|---|
10 | 7782 | CLARK |
10 | 7839 | KING |
10 | 7934 | MILLER |