开发者

How can I force a column to be unique for an entire table in SQL Server 2008 R2?

I have a table with a Description field. I want to ensure that no two rows have the same "Description," but I can't make Description into my identity column (my ID column is an int).

Is开发者_StackOverflow社区 it safe to set Description as a second primary key (in addition to my ID which is already a primary key)?


There is no such thing as a 'secondary primary key'. There is one primary key per table.

Create a UNIQUE constraint on the Description column (highly unusual thing to do, BTW. For example, It is more usual to create a unique index on Product Name rather than a Product description) or if you have null values in the Description column create a Filtered index (SQL Server 2008 onwards)

ALTER TABLE dbo.yourTable
   ADD CONSTRAINT UQ_yourTable_Description UNIQUE ([Description]);


Add a Unique index to the Description column.

Using Sql Server Management Studio right click on the table and choose Design. Then right click on a column and choose "Indexes/keys". You will be prompted with the following window

How can I force a column to be unique for an entire table in SQL Server 2008 R2?

Click on Add on the bottom left and then specify properties for your index. If you want to use a DDL script then use something like this

CREATE UNIQUE NONCLUSTERED INDEX [IX_INDEXNAME] ON [dbo].[TABLENAME] 
(
    [Description] ASC
)
WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO


There is another way to do this with the SSMS GUI if you prefer:

I've replaced the Description column with the name MyUniqueColumn for the sake of the example.

  1. 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.

How can I force a column to be unique for an entire table in SQL Server 2008 R2?

  1. Give new index a name (e.g. "UQ_MyUniqueColumn"), check "Unique", and click "Add..."

How can I force a column to be unique for an entire table in SQL Server 2008 R2?

  1. Check your column in the next window

How can I force a column to be unique for an entire table in SQL Server 2008 R2?

  1. Click OK in both windows
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜