国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發(fā) > 綜合 > 正文

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

2024-07-21 02:49:14
字體:
供稿:網(wǎng)友
如何將一個表中個某一列修改為自動增長的

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

討論起來。他覺得可以,另一位試過說不行。因為他們不是我?guī)О嗉壍膶W生,他們也咨詢了自己的老師,所以我沒有再發(fā)表意見。

需求:

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

解答:

1) 情景一:表中沒有數(shù)據(jù), 可以使用 dropcolumn然后再addcolumn

alter table 表名 drop column列名

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

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

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

--判斷是否存在test表

if object_id(N'test',N'U') is not null

drop tabletest

--創(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 intnot 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 testwith(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ù)據(jù)中存,修改可能會引發(fā)異常,可以使用數(shù)據(jù)導入導出的方式解決。總之,不管使用何種方式,都需求提前對數(shù)據(jù)做好備份。


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 江源县| 信宜市| 苍溪县| 天水市| 芜湖市| 盐池县| 汕尾市| 勐海县| 香格里拉县| 鹰潭市| 湖口县| 永嘉县| 巴林左旗| 海伦市| 溧阳市| 易门县| 揭阳市| 华池县| 行唐县| 东兰县| 堆龙德庆县| 肇州县| 四平市| 武宣县| 霍山县| 彭泽县| 清镇市| 德格县| 关岭| 开鲁县| 邳州市| 宽城| 宜昌市| 珲春市| 肇源县| 额济纳旗| 南岸区| 木兰县| 宁安市| 砀山县| 黔东|