您的位置:首页 > 数据库

SQL中将某列改为自动增长类型

2008-10-23 21:03 281 查看
  如何在原ID列不是自动增长列设为 自动增长列,并保留原ID列数据的通用办法:

1) 建立 一中间表,只有Id 自增长类型,和一其他类型列?

Create table tz (ID counter,tmpI integer)--Access
     Create table tz (ID int identity ,tmpI int)--SQL Server

2) 获得原表的ID列的最大值,向中间表填入记录直到记录数大于原ID列的最大值

select max(ID) from oldTable

insert into tz( max(ID))

3)将中间表与原表左连接,取中间表ID列,原表其他列,插入一临时表tmp

select tz.id, MyTable.otherCol  into tmp

from tz left outer join MyTable on tz.id=MyTable.id

4)因为自动增长列是从1开始,若有指向小于1的记录要特殊处理:'用原ID列中不存在(不连续的)项代替'

select * from tmp

update tmp set parent=17  where parent=0

5) 删除空余的行

delete from tmp where name is null

6)删除原表,将临时表重命名为原表名

drop table MyTable   

EXEC   sp_rename   tmp,  MyTable
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐