![](/img/trans.png)
[英]How can I force a column to be unique for an entire table in SQL Server 2008 R2?
[英]How can I create a unique constraint on my column (SQL Server 2008 R2)?
我有 SQL Server 2008 R2,我想设置一个唯一的列。
似乎有两种方法可以做到这一点:“唯一索引”和“唯一约束”。 它们与我的理解没有太大区别,尽管大多数人推荐使用唯一约束,因为您还可以自动获得索引。
如何创建唯一约束?
ALTER TABLE Customer ADD CONSTRAINT U_Name UNIQUE(Name)
有没有办法通过 SQL Server Management Studio 创建唯一约束?
他们真的让你在谷仓里跑来跑去用 GUI 来做:
在开始之前,请确保您的列没有违反唯一约束。
alter table location_key drop constraint pinky;
alter table your_table add constraint pinky unique(yourcolumn);
更改立即生效:
Command(s) completed successfully.
要通过 GUI 创建这些约束,您需要“索引和键”对话框而不是检查约束。
但在你的情况下,你只需要运行你已经拥有的代码段。 根本不需要进入表情对话。
没有明确说明的一件事是 microsoft sql 在后台为添加的约束创建唯一索引
create table Customer ( id int primary key identity (1,1) , name nvarchar(128) )
--Commands completed successfully.
sp_help Customer
---> index
--index_name index_description index_keys
--PK__Customer__3213E83FCC4A1DFA clustered, unique, primary key located on PRIMARY id
---> constraint
--constraint_type constraint_name delete_action update_action status_enabled status_for_replication constraint_keys
--PRIMARY KEY (clustered) PK__Customer__3213E83FCC4A1DFA (n/a) (n/a) (n/a) (n/a) id
---- now adding the unique constraint
ALTER TABLE Customer ADD CONSTRAINT U_Name UNIQUE(Name)
-- Commands completed successfully.
sp_help Customer
---> index
---index_name index_description index_keys
---PK__Customer__3213E83FCC4A1DFA clustered, unique, primary key located on PRIMARY id
---U_Name nonclustered, unique, unique key located on PRIMARY name
---> constraint
---constraint_type constraint_name delete_action update_action status_enabled status_for_replication constraint_keys
---PRIMARY KEY (clustered) PK__Customer__3213E83FCC4A1DFA (n/a) (n/a) (n/a) (n/a) id
---UNIQUE (non-clustered) U_Name (n/a) (n/a) (n/a) (n/a) name
如您所见,有一个新约束和一个新索引U_Name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.