日期:2014-05-17 浏览次数:20558 次
/* 自增列的基本操作[為已存在的列按自增值更新] */
--表
if object_id('t') is not null
drop table t
go
create table t( id int, col nvarchar(20) )
go
--測試數據
insert t
select null,'test1' union all
select null,'test2' union all
select null,'test2' union all
select null,'test1' go
--第一種:按指定順序設置id(但只能更新原有数据,設置不了自增,不算)
update t
set id=t1.rn
from (select row_number() over(order by col) rn,col from t)t1
where t.col=t1.col;
go
select * from t order by col;
go
--第二種:根據數據庫實際存儲數據設置自增id
alter table t drop column id;
alter table t add id int identity(1,1) not null;
go
select * from t;
go
--第三種:根據自已設置的順序設置自增id
if object_id('t_copy') is not null
drop table t_copy
select col into t_copy from t order by col;
truncate table t;
alter table t drop column id;
alter table t add id int identity(1,1) not null;
insert into t(col) select col from t_copy;
go
select * from t order by col;
go
--第四種:根據自已設置的順序設置自增id,且保持原列順序
if object_id('t_copy') is not null
drop table t_copy
select col into t_copy from t order by col;
drop table t;
select id=identity(int,1,1),col into t from t_copy;
go
select * from t order by col;
go
/* 如果经常增删数据记录的话,自增ID列没多大意义,可以将ID列设置为uniqueidentifier, 建新列DateTime记录插入时间以便排序