• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

昨天有位学生问我“一个表已经建好了,能不能将里面的一个字段改为自动增长?”,“能,但没有必要去修改它,应该在建表的时候就设计好” 我说。 这时候他和另一位学生
讨论起来。他觉得可以,另一位试过说不行。因为他们不是我带班级的学生,他们也咨询了自己的老师,所以我没有再发表意见。

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

解答:
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

总结:在表设计界面修改最为简单。如果该列已有的数据中存,修改可能会引发异常,可以使用数据导入导出的方式解决。总之,不管使用何种方式,都需求提前对数据做好备份。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap