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 wh开发者_C百科en 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
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.
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.
精彩评论