How to: Create Relationships Between Tables
You create a relationship between two tables when you want to associate rows of one table with rows of another. For more information about relationships, see Types of Table Relationships.
Note
A new version of Table Designer appears for databases in the SQL Server 2012 format. This topic describes the old version of Table Designer, which you use with databases in earlier formats of SQL Server.
In the new version, you can change a table definition through a graphical interface or directly in a script pane. If you use the graphical interface, the table’s definition is automatically updated in the script pane. To apply the SQL code in the script pane, choose the Update button. For more information about the new version, see How to: Create Database Objects Using Table Designer.
Note
Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Customizing Development Settings in Visual Studio.
To create a foreign key relationship in Table Designer
In Server Explorer, right-click the table that will be on the foreign-key side of the relationship and click Open Table Definition.
The table opens in Table Designer.
From the Table Designer menu, click Relationships.
In the Foreign-key Relationships dialog box, click Add.
The relationship appears in the Selected Relationship list with a system-provided name in the format FK_<tablename>_<tablename>, where tablename is the name of the foreign key table.
Click the relationship in the Selected Relationship list.
Click Tables and Columns Specification in the grid to the right and click the ellipses (…) to the right of the property.
In the Tables and Columns dialog box, in the Primary Key drop-down list, choose the table that will be on the primary-key side of the relationship.
In the grid beneath, choose the columns contributing to the table's primary key. In the adjacent grid cell to the left of each column, choose the corresponding foreign-key column of the foreign-key table.
Table Designer suggests a name for the relationship. To change this name, edit the contents of the Relationship Name text box.
Choose OK to create the relationship.
Note
The columns you choose for the foreign key must have the same data type of the primary columns they correspond to. There must be an equal number of columns in each of the keys. For example, if the primary key of the table on the primary side of the relationship is made up of two columns, you will need to match each of those columns with a column in the table for the foreign key side of the relationship.
See Also
Reference
Foreign Key Relationships Dialog Box