索引约束

11:17 2012-11-26 索引约束
--sqlserver中在非空列上作主键,默认会在相应列上创建一个唯一、聚集索引
--clustered index is in same filegroup with data.Pkey is not always clustered.

1 exec sp_helpconstraint table--获取表中约束(默认值,主键)
2 exec sp_helpindex table--获取表中索引
3 exec sp_autostats '表名 ' --查看一个表的索引的统计信息有上次修改的时间

下面通过一个例子查看,首先添加主键约束

1 create table pkuniquetest(id int not null,name varchar(6) not null)
2 --添加主键约束会自动创建聚集索引
3 alter table pkuniquetest add constraint pk_pktest_id primary key clustered(id )
4 sp_helpindex pkuniquetest
5 select name,id,xtype,parent_obj from sysobjects where id=object_id('pkuniquetest') or
6 parent_obj= object_id('pkuniquetest' )


--添加唯一约束

1 --删除主键,一并删除同名聚集索引
2 alter table pkuniquetest drop constraint pk_pktest_id
3 --添加唯一约束会自动创建非聚集索引  
4 alter table pkuniquetest add constraint unique_pktest_name unique(name) 


创建唯一索引

1 --删除唯一约束,一并删除同名非聚集索引
2 alter table pkuniquetest drop constraint unique_pktest_name 
3 --创建唯一索引
4 create unique nonclustered index index_pktest_name on pkuniquetest(name)


--删除唯一索引、测试表

1 --删除唯一索引、测试表
2 drop index pkuniquetest.index_pktest_name 
3 drop table pkuniquetest

若index_description含有unique key或sysobjects中xtype=UQ则其是唯一约束,创建表时不能单纯的只创建唯一索引
在生成建表语句的时候可以参考X:\X\X\获取建表索引语句.txt中PK得到相应的unique字段,将最后的primary key()换成unique()
同时注意获取索引部分where后面的条件
16:41 2013-10-24
--主键约束不允许出现NULL值。任何索引条目的索引键都不允许包含NULL。
--唯一约束允许包含NULL值,但唯一约束把两个NULL值当作重复值

 1 USE test
 2 CREATE TABLE testindex(a int,b int)
 3 --在列a 上添加唯一约束
 4 ALTER TABLE testindex ADD CONSTRAINT UNIQUE_A UNIQUE(a)
 5 --查看索引情况
 6 sp_helpindex testindex
 7 --插入测试数据
 8 INSERT INTO testindex(a) VALUES(12),(13),(NULL)
 9 --再次插入数据,终止违反了UNIQUE KEY约束,重复键值为(<NULL>)
10 INSERT INTO testindex(a) VALUES(NULL)--插入出错
11 --在列b上创建唯一过滤索引
12 CREATE UNIQUE INDEX index_b ON testindex(b) WHERE b IS NOT NULL
13 --插入测试数据
14 INSERT INTO testindex(a,b) VALUES (15,NULL)
15 INSERT INTO testindex(a,b) VALUES(16,1),(17,NULL)--插入正常
16 SELECT * FROM testindex
17 --删除测试表
18 DROP TABLE testindex
View Code
posted @ 2014-02-28 12:31  Uest  阅读(791)  评论(0编辑  收藏  举报