Thursday, February 16, 2006

Foreign Key Reference for Composite Key

Example 1
---------

when you have a unique constraint on the column we can use it as a foreign key even though it is a part of a composite key

CREATE TABLE TEST
(
a INT UNIQUE,
b INT UNIQUE,
c VARCHAR2(1),
CONSTRAINT PK_test PRIMARY KEY (a, b )
)


CREATE TABLE test_child
(
child_a INT REFERENCES TEST(a),
child_b INT ,
child_c VARCHAR2(1)

)


Example 2
---------
the following example shows how to have composite foreign kye on child table referencing composite key on base table.

CREATE TABLE TEST
(
a INT,
b INT,
c VARCHAR2(1),
CONSTRAINT PK_test PRIMARY KEY (a, b )
)


CREATE TABLE TEST_CHILD
(
child_a INT ,
child_b INT ,
child_c VARCHAR2(1))

ALTER TABLE TEST_CHILD ADD CONSTRAINT fk_child_test FOREIGN KEY (child_a, child_b)
REFERENCES TEST(a,b)

Comments: Post a Comment

Subscribe to Post Comments [Atom]





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Comments [Atom]