Foreign Key constraint in Sql server - Free Asp.Net,MVC,AngularJs,Jquery,Javascript,Sql Server,WCF,Entity framework snippets and tutorial

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   


What do you think about this article?

If you found this article useful, please share and follow on Facebook, Twitter, Google Plus and other social media websites. To get free updates subscribe to newsletter. Please put your thoughts and feedback in comments section.

Share this

Share on FacebookTweet on TwitterPlus on Google+


EmoticonEmoticon