简体   繁体   English

如何强制 SQL Server 2008 R2 中的整个表的列唯一?

[英]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.我有一个带有Description字段的表。 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).我想确保没有两行具有相同的“描述”,但我无法将描述放入我的身份列(我的 ID 列是一个整数)。

Is it safe to set Description as a second primary key (in addition to my ID which is already a primary key)?Description设置为第二个主键是否安全(除了我已经是主键的 ID 之外)?

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)Description列上创建一个UNIQUE 约束(非常不寻常的事情,顺便说一句。例如,在Product Name上创建唯一索引而不是Product description更常见),或者如果您在Description列中有空值,则创建一个筛选索引(SQL Server 2008 及更高版本)

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.使用 Sql Server Management Studio 右键单击​​表并选择“设计”。 Then right click on a column and choose "Indexes/keys".然后右键单击一列并选择“索引/键”。 You will be prompted with the following window将提示您使用以下窗口

替代文字

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如果你想使用 DDL 脚本,那么使用这样的东西

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:如果您愿意,还有另一种使用 SSMS GUI 执行此操作的方法:

I've replaced the Description column with the name MyUniqueColumn for the sake of the example.为了示例起见,我已将Description列替换为名称MyUniqueColumn

  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.右键单击 SSMS 解决方案资源管理器中表下的“索引”,然后单击“新建索引...”(我知道您要创建约束,而不是索引,但这正是ADD CONSTRAINT SQL 脚本所做的。

在此处输入图片说明

  1. Give new index a name (eg "UQ_MyUniqueColumn"), check "Unique", and click "Add..."为新索引命名(例如“UQ_MyUniqueColumn”),选中“唯一”,然后单击“添加...”

在此处输入图片说明

  1. Check your column in the next window在下一个窗口中检查您的列

在此处输入图片说明

  1. Click OK in both windows在两个窗口中单击确定

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM