Saturday, May 16, 2015

Foreign Key constraint in Sql server

Introduction: In this article today ia m going to explain foreign Key constraint in sql server

Description:
A foreign key Constraint is used to link two tables together. A Foreign key in one table refers to primary key of another table.  It can accept multiple null and duplicate values.

Example:
Create a table with foreign key constraint:
Create table Customers
(
CustomerId int Primary key,
Name varchar(50),
Address Varchar(150),
Phone_Number int
)

Create Table Orders
(
OrderId int Primary key,
OrderNumber int not null,
Customer_Id_Fk int,
constraint Customer_Id_Fk FOREIGN KEY (Customer_Id_Fk) REFERENCES Customers(CustomerId)
)
In this example I have create a two tables, one Customers which have the customers information and another Orders which have stored the detail of order placed by cuntomers. Customer_Id_Fk of  Orders table is forgien key  linked to  CustomerId of Customers table.

Alter a table with foreign key constraint:
ALTER TABLE Orders
add constraint Customer_Id_Fk FOREIGN KEY (Customer_Id_Fk) REFERENCES Customers(CustomerId)

Drop a table with foreign key constraint:
ALTER TABLE Orders

DROP constraint Customer_Id_Fk   


No comments:

Post a Comment