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

I can successfully create a composite primary key in SQL Server 2012 Management Studio by selecting two columns (OrderId, CompanyId) and right-clicking and setting it as the primary key. But I do not know how to create a foreign key on two columns (OrderId, CompanyId) in another table using sql 2012 server management studio.

+6
source share
3 answers

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

enter image description here

In the dialog that appears, click the Add button to create a new foreign key:

enter image description here

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

enter image description here

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

Or much simpler and more efficient - use a T-SQL script!

 ALTER TABLE dbo.OtherTable ADD CONSTRAINT FK_OtherTable_ParentTable FOREIGN KEY(OrderId, CompanyId) REFERENCES dbo.ParentTable(OrderId, CompanyId) 
+12
source

If you open a submenu for a table in the table list in Studio Management, the Keys element appears. If you right-click on it, you will get New Foreign Key as an option. If you select this, the Foreign Relationships dialog box opens. In the (General) section, you will find Tables And Columns Specifications . If I open this, I can select multiple columns.

0
source

Add two separate foreign keys for each column.

-1
source

Source: https://habr.com/ru/post/970390/


All Articles