Whi*_*and 96 sql sql-server unique-constraint sql-server-2008
我有SQL Server 2008 R2,我想设置一个唯一的列.
似乎有两种方法可以做到这一点:"唯一索引"和"唯一约束".尽管大多数人都推荐使用唯一约束,但它们与我的理解并没有太大差别,因为您也会自动获得索引.
如何创建唯一约束?
ALTER TABLE Customer ADD CONSTRAINT U_Name UNIQUE(Name)
Run Code Online (Sandbox Code Playgroud)
有没有办法通过SQL Server Management Studio创建唯一约束?
Eri*_*ski 113
他们真的让你在谷仓里跑来跑去用GUI:
在开始之前,请确保您的列不违反唯一约束.
alter table location_key drop constraint pinky;
alter table your_table add constraint pinky unique(yourcolumn);
Run Code Online (Sandbox Code Playgroud)
更改立即生效:
Command(s) completed successfully.
Run Code Online (Sandbox Code Playgroud)
Ton*_* L. 15
这是通过GUI的另一种方式,即使它通过对象资源管理器中的索引(不是约束),它也能完成您的脚本所做的工作.
小智 8
一件未明确介绍的事情是,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
Run Code Online (Sandbox Code Playgroud)
如您所见,这里有一个新的约束和一个新的索引U_Name
| 归档时间: |
|
| 查看次数: |
157700 次 |
| 最近记录: |