简体   繁体   中英

How to add constraint to SQL Server 2008 using constraint dialog?

How do you manually define a constraint in SQL Server 2008 dialog box? I want to add a constraint that when I add a new record if its already there don't add it. My table is structured so that

AdvCatJoinID is my primary key, CatID is the key from the Category table, and AliasID is the primary key from the alias table, I want the constraint to be that if the CatID and AliasID already exist in the table as a pair then don't add a new record (as it already exists), how to?

Thanks

Do you really need the AdvCatJoinID column? Usually for these association tables I just have a composite primary key on the 2 foreign key columns. That enforces the unique aspect.

Otherwise to do it in SSMS you need to go through the "Indexes/Keys" dialogue (NOT the constraints one) and configure a new Unique Index with both columns selected. You access this dialogue after right clicking the table and selecting "Design" then right clicking the table designer grid.

To create a unique constraint rather than unique index you would choose the option "Unique Key" but there is no practical difference netween the two.

Step 1:

In the SQL Server Object Explorer, find your database and table that you want to put the constraint on, and navigate to the Indexes subnode, and right-click, choose New Index :

在此输入图像描述

Step 2:

In the dialog box that pops up, define your unique index:

  • give it a name of your choosing
  • make sure the [ X ] Unique checkbox is checked
  • click on the [ Add ] button twice to add your two columns to the index

在此输入图像描述

When you've done those two steps, you now have a unique index on the (CatID, AliasID) combination and no pair of those two values can exist more than once in your table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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