Wednesday, January 6, 2010

Creating table in a database by refercencing foregin key

We can create foregin key by referencing primary key.
Before referencing a column the table must exist with that column name with same datatype and size.

Syntax:
create table table_name(column_name datatype(size),column_name1 datatype(size),column_name2 datatype(size) REFERENCES reference_table_name(column_name,..n);

Example:
create table dept(dept_id char(10) PRIMARY KEY,dept_name char(30),dept_year char(10));

create table sem(sem_id char(10) PRIMARY KEY,sem_name char(30),dept_id char(10) REFERENCES dept (dept_id));

In this example am creating a table name named 'dept' with primary key as 'dept_id', then i have created a table named 'sem' which has its column name as 'dept_id' references the table dept.

No comments:

Post a Comment