香港云主机最佳企业级服务商!

ADSL拨号VPS包含了中国大陆(联通,移动,电信,)

中国香港,国外拨号VPS。

当前位置:云主机 > MSSQL >

电信ADSL拨号VPS
联通ADSL拨号VPS
移动ADSL拨号VPS

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


时间:2020-10-31 14:27 作者:admin


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

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

解答:
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 nulldrop 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 transactioncreate table test_tmp(id int not null identity(1,1),name varchar(20) not null)goset identity_insert test_tmp ongoif exists(select * from test)exec(' insert into test_tmp(id, name ) select id, name from test with(holdlock tablockx)')goset identity_insert test_tmp offgodrop table testgoexec sp_rename N'test_tmp' ,N'test' , 'OBJECT'gocommitGO/****************验证结果*****************/insert into test values ('张曼')select * from test

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

(责任编辑:admin)






帮助中心
会员注册
找回密码
新闻中心
快捷通道
域名登录面板
虚机登录面板
云主机登录面板
关于我们
关于我们
联系我们
联系方式

售前咨询:17830004266(重庆移动)

企业QQ:383546523

《中华人民共和国工业和信息化部》 编号:ICP备00012341号

Copyright © 2002 -2018 香港云主机 版权所有
声明:香港云主机品牌标志、品牌吉祥物均已注册商标,版权所有,窃用必究

云官方微信

在线客服

  • 企业QQ: 点击这里给我发消息
  • 技术支持:383546523

  • 公司总台电话:17830004266(重庆移动)
  • 售前咨询热线:17830004266(重庆移动)