Udostępnij za pośrednictwem


How to: Create Primary Keys

Define a primary key to enforce uniqueness for values entered in specified columns that do not allow nulls. If you define a primary key for a table in your database, you can relate that table to other tables, thus reducing the need for redundant data. A table can have only one primary key.

Note

Some databases have different rules for primary key constraints. Consult your database documentation for details about how your database works with primary key constraints.

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 Visual Studio Settings.

To create a primary key

  1. In Table Designer, click the row selector for the database column you want to define as the primary key. If you want to select multiple columns, hold down the CTRL key while you click the row selectors for the other columns.

  2. Right-click the row selector for the column and select Set Primary Key. A primary key index, named "PK_" followed by the table name, is automatically created; you can find it on the Indexes/Keys dialog box.

Warning

If you want to redefine the primary key, any relationships to the existing primary key must be deleted before the new primary key can be created. A message will warn you that existing relationships will be automatically deleted as part of this process.

A primary key column is identified by a primary key symbol in its row selector.

If a primary key consists of more than one column, duplicate values are allowed in one column, but each combination of values from all the columns in the primary key must be unique.

If you define a compound key, the order of columns in the primary key matches the order of columns as shown in the table in your diagram. However, you can change the order of columns after the primary key is created. For more information, see How to: Modify Primary Keys.

See Also

Tasks

How to: Delete Primary Keys

How to: Change Relationship Properties

How to: Modify Primary Keys

Reference

Primary or Unique Key Properties

Concepts

Table Relationships (Visual Database Tools)

Other Resources

Working with Constraints

Working with Constraints