欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

將一個表中個某一列修改為自動增長的方法

 更新時間:2014年09月18日 17:36:58   投稿:whsnow  
如果表中沒有數(shù)據(jù)可以使用 drop column然后再add column,如果存在一部分?jǐn)?shù)據(jù)可以使用本文提供的第二種解決方法

昨天有位學(xué)生問我“一個表已經(jīng)建好了,能不能將里面的一個字段改為自動增長?”,“能,但沒有必要去修改它,應(yīng)該在建表的時候就設(shè)計好” 我說。 這時候他和另一位學(xué)生
討論起來。他覺得可以,另一位試過說不行。因為他們不是我?guī)О嗉壍膶W(xué)生,他們也咨詢了自己的老師,所以我沒有再發(fā)表意見。

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

解答:
1) 情景一:表中沒有數(shù)據(jù), 可以使用 drop column然后再add column

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

2) 情景二:表中已經(jīng)存在一部分?jǐn)?shù)據(jù)

/**************** 準(zhǔn)備環(huán)境********************/

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

--創(chuàng)建test表
create table test
(
id int not null,
name varchar(20) not null
)

--插入臨時數(shù)據(jù)
insert into test values (1,'成龍')
insert into test values (3,'章子怡')
insert into test values (4,'劉若英')
insert into test values (8,'王菲')

select * from test



/**************** 實現(xiàn)更改自動增長列********************/

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

/****************驗證結(jié)果*****************/
insert into test values ('張曼')
select * from test

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

相關(guān)文章

最新評論