views:

21012

answers:

8

How do I create a unique constraint on an existing table in SQL Server 2005?

I am looking for both the TSQL and how to do it in the Database Diagram.

+4  A: 
ALTER TABLE dbo.<tablename> ADD CONSTRAINT
            <namingconventionconstraint> UNIQUE NONCLUSTERED
    (
                <columnname>
    ) ON [PRIMARY]
bosnic
A: 

You are looking for something like the following

ALTER TABLE dbo.doc_exz
ADD CONSTRAINT col_b_def
UNIQUE column_b

MSDN Docs

Thunder3
+1  A: 

In the management studio diagram choose the table, right click to add new column if desired, right-click on the column and choose "Check Constraints", there you can add one.

Gibbons
+2  A: 

I also found you can do this via, the database diagrams.

By right clicking the table and selecting Indexes/Keys...

Click the 'Add' button, and change the columns to the column(s) you wish make unique.

Change Is Unique to Yes.

Click close and save the diagram, and it will add it to the table.

David Basarab
A: 

ALTER TABLE [TableName] ADD CONSTRAINT [constraintName] UNIQUE ([columns])

WildJoe
+18  A: 

The SQL command is:

ALTER TABLE <tablename> ADD CONSTRAINT
            <constraintname> UNIQUE NONCLUSTERED
    (
                <columnname>
    )

See the full syntax here.

If you want to do it from a Database Diagram:

  • right-click on the table and select 'Indexes/Keys'
  • click the Add button to add a new index
  • enter the necessary info in the Properties on the right hand side:
    • the columns you want (click the ellipsis button to select)
    • set Is Unique to Yes
    • give it an appropriate name
Rory
+1  A: 

Warning: Only one null row can be in the column you've set to be unique.

You can do this with a filtered index in SQL 2008:

CREATE UNIQUE NONCLUSTERED INDEX idx_col1 ON dbo.MyTable(col1) WHERE col1 IS NOT NULL;

See http://stackoverflow.com/questions/377798/field-value-must-be-unique-unless-it-is-null for a range of answers.

Squirrel
+1  A: 

In SQL Server Management Studio Express:

  • Right-click table, choose Modify
  • Right-click field, choose Indexes/Keys...
  • Click Add
  • For Columns, select the field name you want to be unique.
  • For Type, choose Unique Key.
  • Click Close, Save the table.
James Lawruk