How to create Composite Unique Constraint in SQL S

2019-02-21 14:32发布

问题:

Preferably I would like to know how to do it using the SQL Server Management Studio interface but that isn't completely necessary. If you simply have a script to add one after a table is made that would be fine.

回答1:

In SQL Server Management Studio

  • goto the Object Explorer
  • pick your table and open its designer (can't remember what it was called in 2005 - Modify Table or something?)
  • in the table designer, pick the "Manage Indexes and Keys" icons from the toolbar (the table with the little key)
  • in there, add a new index and give it a name, click it's "Unique" setting

alt text http://i35.tinypic.com/s61t7d.png

  • open the list of columns in the index definition and add your columns you want to thave in the index

alt text http://i34.tinypic.com/nysqjd.png

That's it! :)



回答2:

Try this:

ALTER TABLE dbo.YourTableName 
ADD CONSTRAINT
ConstraintName UNIQUE NONCLUSTERED
(
    Column01,
    Column02,
    Column03
)

I use business names for constraints so that if it is violated and an exception bubbles up, I get "Only one Dept per Employee violation" in my error message rather than "ConstraintXXX violation".