Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create composite foreign key in sql server management studio 2012

I can successfully create composite primary key in sql server management studio 2012 by selecting two columns (OrderId, CompanyId) and right click and set as primary key. But i don't know how to create foreign key on two columns(OrderId, CompanyId) in other table by using sql server management studio 2012.

like image 356
user3004110 Avatar asked Jun 05 '14 12:06

user3004110


1 Answers

In Object Explorer, go to your table and select Keys > New Foreign Key from the context menu:

enter image description here

From the dialog box that pops up, click on the Add button to create a new foreign key:

enter image description here

Give it a meaningful name and then click on the ... button to open the Tables and Columns specification dialog box:

enter image description here

Fill in the necessary columns for the parent and the child tables, click OK and you're done!

Or much easier and more efficiently - use a T-SQL script!

ALTER TABLE dbo.OtherTable
ADD CONSTRAINT FK_OtherTable_ParentTable
FOREIGN KEY(OrderId, CompanyId) REFERENCES dbo.ParentTable(OrderId, CompanyId)
like image 80
marc_s Avatar answered Nov 08 '22 09:11

marc_s