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

两盒软妹~` 提交于 2019-12-10 04:19:29

问题


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.


回答1:


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

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

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

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)



回答2:


If you open the submenu for a table in the table list in Management Studio, there is an item Keys. If you right-click this, you get New Foreign Key as option. If you select this, the Foreign Key Relationships dialogue opens. In the section (General), you will find Tables And Columns Specifications. If i open this, i can select multiple columns.




回答3:


Add two separate foreign keys for each column.



来源:https://stackoverflow.com/questions/24059880/how-to-create-composite-foreign-key-in-sql-server-management-studio-2012

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!