如何將一個表中個某一列修改為自動增長的


    昨天有位學生問我“一個表已經建好了,能不能將里面的一個字段改為自動增長?”,“能,但沒有必要去修改它,應該在建表的時候就設計好” 我說。 這時候他和另一位學生

討論起來。他覺得可以,另一位試過說不行。因為他們不是我帶班級的學生,他們也咨詢了自己的老師,所以我沒有再發表意見。

 

需求:

如何將一張表中個某一列修改為自動增長的。

 

解答:

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

 

 

總結:在表設計界面修改最為簡單。如果該列已有的數據中存,修改可能會引發異常,可以使用數據導入導出的方式解決。總之,不管使用何種方式,都需求提前對數據做好備份。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM