How to make "No Duplicates" column in SQL Server 2008?
I have a simple table in my SQL Server database. This table contains two columns: ID int, Name nvarchar(50)
. The ID
column is the primary key for my table.
I want the开发者_运维知识库 "Name
" column to be "(No Duplicates)
", like in Microsoft Access, But this column isn't the primary column. How could I do this?
Add a unique constraint for that column:
ALTER TABLE Foo ADD CONSTRAINT UQ_Name UNIQUE (Name)
To add it through SQL Management Studio UI:
- Open SQL Server Management Studio.
- Expand the Tables folder of the database where you wish to create the constraint.
- Right-click the table where you wish to add the constraint and click Design.
- In Table Designer, click on Indexes/Keys.
- Click Add.
- Choose Unique Key in the Type drop-down list.
To handle a situation where a unique constraint violation occurs, see for error 2601.
This can also be done another way with the SSMS GUI if you prefer:
- Right click "Indexes" under your table in the SSMS Solution Explorer and click "New Index..." (I know you are looking to create a contstraint, not an index, but this is exactly what the
ADD CONSTRAINT
SQL script does.
- Give new index a name (e.g. "UQ_MyUniqueColumn"), check "Unique", and click "Add..."
- Check your column in the next window
- Click OK in both windows
You are looking for the UNIQUE constraint.
精彩评论