您现在的位置: 万盛学电脑网 >> 程序编程 >> 数据库 >> 数据库综合 >> 正文

如何将一个表中个某一列修改为自动增长

作者:佚名    责任编辑:admin    更新时间:2022-06-22

这是一篇关于将一个表中个某一列修改为自动增长的方法,下面就让我们一起来学习吧!

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

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

需求:

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

解答:

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

alter table 表名 drop column 列名

alter table表名 add列名 int identity(1,1)

2) 情景二:表中已经存在一部分数据

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

/**************** 准备环境********************/

--判断是否存在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

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

以上就是精品为大家提供的关于将一个表中个某一列修改为自动增长方法,希望对大家有所帮助!