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
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
相关文章推荐
- SQL 2000创建表的时候设置某一字段为自动增长的类型
- 在SQL中插入临时表时使用自动增长的数据字段
- 如何写出一条SQL语句:取出表A中第31~40条记录(SQLServer,以自动增长的ID作为主键
- SQL大全(查询分析器快捷鍵,Sysproperties系统表,syscolumns系统表,union,表结构修改,临时表,加一个自动增长列,函数,游标,关联其它表修改,直接调用存储过程,T远程连接专用sql)
- Hibernate产生自动增长类型主键策略
- sql生成自动增长字段
- 写出一条Sql语句:取出表A中第31到第40记录(SQLServer,以自动增长的ID作为主键,注意:ID可能不是连续的。
- 让SQL自动增长的ID号从1开始
- SQL 实现从表中自动增长字段的最大值向上自动增长
- sql自动增长标识导致导入数据问题的解决方法
- Access建表SQL语句Create Table设置自动增长列的关键字AUTOINCREMENT使用方法
- SQL获取某表的索引或约束,并确定索引归属列,获取表中的自动增长列名。
- sql 查询一个表的数据插入到别一个表,ID自动增长
- mysql字段是自动增长类型结果却不是连续的
- sql自动增长标识(转载)
- 数据库中自动增长的字段类型
- 使用sql语句创建修改SQL Server标识列(即自动增长列)
- sql 自动增长标识
- 使用强类型DataSet增加数据并获取自动增长的ID
- 更改数据库结构,linqToSql并不会自动更改,必须手动修改为自动增长或另外在拖一次表