How to: Create Matching Foreign and Primary Keys

When you copy a column from one table to another table, the column name and many of the other properties you defined for that column in the original table are copied to the new location. You can copy column properties from a primary key column to a foreign key column if you want to relate the two columns. Related columns must have the same data type (or data types that can be related) and length.

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 copy primary key columns to foreign key columns

  1. In Server Explorer, right-click the table with primary key columns you want to copy and click Open Table Definition. Do the same for the table into which you want to copy the columns as foreign keys.

    The tables open in Table Designer.

  2. Click the tab for the table with the columns you want to copy.

  3. Select the primary key columns that you want to copy.

    Primary key columns are indicated by a key symbol in their row selector.

  4. From the Edit menu, click Copy.

  5. Click the tab for the table into which you want to copy the columns.

  6. Select the column you want to follow the inserted columns and from the Edit menu, click Paste.

  7. Right-click the foreign key table and click Relationships on the shortcut menu.

    The Foreign Key Relationships dialog box opens.

  8. Create a relationship between the primary key and foreign key columns.

See Also

Other Resources

Working with Keys

Working with Constraints

Working with Relationships