Tuesday, 10 April 2012

Foreign Key in SQL Server

2.       What is a Foreign key ?
 Ans: A Foreign key in one table points to a primary key or unique key on another  table. Foreign Keys prevent actions that would change rows with foreign key values when there is no primary keys with that value. They are used to enforce referential integrity. In simple words, a Foreign key is a field which has corresponding primary key field.

The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.


The FOREIGN KEY constraint also prevents that invalid data form being inserted into the foreign key column, because it has to be one of the values contained in the table it points to.

Example:

A.      Create a Foreign key:

CREATE TABLE Class
(
C_Id int NOT NULL,
Name int NOT NULL,
S_Id int,
PRIMARY KEY (S_Id),
CONSTRAINT fk_Class FOREIGN KEY (S_Id)
REFERENCES Student(S_Id)
)


B.   Alter table and create Foreign Key:

ALTER TABLE Class
ADD CONSTRAINT fk_PerClass
FOREIGN KEY (S_Id)
REFERENCES Student(S_Id)

C.   Drop Foreign Key:

ALTER TABLE Class
DROP CONSTRAINT fk_PerClass


Thanks For Reading..!!

Default Programmer

No comments:

Post a Comment