您的位置:首页 > 其它

将一个表中个某一列修改为自动增长的方法

2014-09-18 00:00 225 查看
昨天有位学生问我“一个表已经建好了,能不能将里面的一个字段改为自动增长?”,“能,但没有必要去修改它,应该在建表的时候就设计好” 我说。 这时候他和另一位学生

讨论起来。他觉得可以,另一位试过说不行。因为他们不是我带班级的学生,他们也咨询了自己的老师,所以我没有再发表意见。
需求:

如何将一张表中个某一列修改为自动增长的。
解答:

1) 情景一:表中没有数据, 可以使用 drop column然后再add column
alter table 表名 drop column 列名

alter table表名 add列名 int identity(1,1)
2) 情景二:表中已经存在一部分数据
/**************** 准备环境********************/

--判断是否存在test表
if object_id(N'test',N'U') is not null
drop table test

--创建test表
create table test
(
id int not null,
name varchar(20) not null
)

--插入临时数据
insert into test values (1,'成龙')
insert into test values (3,'章子怡')
insert into test values (4,'刘若英')
insert into test values (8,'王菲')

select * from test
/**************** 实现更改自动增长列********************/

begin transaction

create table test_tmp
(
id int not null identity(1,1),
name varchar(20) not null
)
go

set identity_insert test_tmp on
go

if exists(select * from test)
exec(' insert into test_tmp(id, name ) select id, name from test with(holdlock tablockx)')
go

set identity_insert test_tmp off
go

drop table test
go

exec sp_rename N'test_tmp' ,N'test' , 'OBJECT'
go

commit

GO

/****************验证结果*****************/
insert into test values ('张曼')
select * from test

总结:在表设计界面修改最为简单。如果该列已有的数据中存,修改可能会引发异常,可以使用数据导入导出的方式解决。总之,不管使用何种方式,都需求提前对数据做好备份。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: