[英]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
。
ADD CONSTRAINT
SQL script does.ADD CONSTRAINT
SQL 脚本所做的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.