简体   繁体   English

如何在sql server management studio 2012中创建复合外键

[英]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. 我可以通过选择两列(OrderId,CompanyId)并右键单击并设置为主键,在sql server management studio 2012中成功创建复合主键。 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. 但我不知道如何使用sql server management studio 2012在其他表中的两列(OrderId,CompanyId)上创建外键。

In Object Explorer, go to your table and select Keys > New Foreign Key from the context menu: 在对象资源管理器中,转到表并从上下文菜单中选择“ Keys > New Foreign Key ”:

在此输入图像描述

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: 为其指定一个有意义的名称,然后单击“ ...”按钮以打开“ Tables and Columns specification对话框:

在此输入图像描述

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! 或者更容易和更有效 - 使用T-SQL脚本!

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

If you open the submenu for a table in the table list in Management Studio, there is an item Keys . 如果在Management Studio的表列表中打开表的子菜单,则会有一个项目Keys If you right-click this, you get New Foreign Key as option. 如果右键单击此选项,则会选择“ New Foreign Key ”。 If you select this, the Foreign Key Relationships dialogue opens. 如果选择此选项,将打开“外键关系”对话框。 In the section (General), you will find Tables And Columns Specifications . 在(常规)部分中,您将找到“ Tables And Columns Specifications If i open this, i can select multiple columns. 如果我打开它,我可以选择多个列。

为每列添加两个单独的外键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM