日期:2014-05-18  浏览次数:20488 次

插入顺序问题
执行下列语句后,为什么第一个字段(主键)并不是按1 2 3 4排列? 
INSERT INTO area_info_tab(area_id,area_name) VALUES(1, '北京 '); 
INSERT INTO area_info_tab(area_id,area_name) VALUES(2, '上海 '); 
INSERT INTO area_info_tab(area_id,area_name) VALUES(3, '天津 '); 
INSERT INTO area_info_tab(area_id,area_name) VALUES(4, '重庆 ');

怎样才能按1 2 3 4的顺序来排列呢?



------解决方案--------------------
SQL code
--1、普通聚集(CLUSTERED)索引
create table T1 (id int not null,area varchar(20) not null)
insert T1 select 4,'重庆'
insert T1 select 2,'上海'
create CLUSTERED index IX_T1_id on T1(id) --加聚集索引
insert T1 select 1,'北京'
insert T1 select 3,'天津'
select * from T1
drop table T1

--2、唯一性约束:CLUSTERED
create table T2 (id int not null,area varchar(20) not null)
insert T2 select 4,'重庆'
insert T2 select 2,'上海'
alter table T2 add constraint IX_Test_id unique CLUSTERED (id) --加CLUSTERED唯一性约束
insert T2 select 1,'北京'
insert T2 select 3,'天津'
select * from T2
drop table T2

--3、主键约束:CLUSTERED
create table T3 (id int not null,area varchar(20) not null)
insert T3 select 4,'重庆'
insert T3 select 2,'上海'
alter table T3 add constraint PK_Test_id primary key CLUSTERED (id) --加CLUSTERED主键约束
insert T3 select 1,'北京'
insert T3 select 3,'天津'
select * from T3
drop table T3