首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

怎么将一个表的自增字段重新从1开始(50分)

2012-07-29 
如何将一个表的自增字段重新从1开始(50分)?1、表sys_city中的Id自增字段出现了:1,2,3,6,8,9,我想把现有记录

如何将一个表的自增字段重新从1开始(50分)?
1、表sys_city中的Id自增字段出现了:1,2,3,6,8,9,我想把现有记录的自增字段从新更新成:1,2,3,4,5,6,7...
2、不要删除数据表的记录。
3、网上有一段代码很能解决现在的问题,关键的问题是:提示:不允许对系统目录进行即席更新。

SQL code
exec sp_configure 'allow updates',1reconfigure with overrideGOupdate syscolumns set colstat = 0 where id = object_id('dbo.Sys_City') and colstat = 1GOupdate   dbo.Sys_City set   ID=(select   count(1)   from   dbo.Sys_City   where   ID<=t.ID)   from   dbo.Sys_City   tGOdeclare @a int set @a=(select count(*) from dbo.Sys_City)DBCC CHECKIDENT (Sys_City, RESEED, @a)GOupdate syscolumns set colstat = 1 where id = object_id('dbo.Sys_City') and name = 'ID'GO  exec sp_configure 'allow updates',0reconfigure with override


提示出错为:
配置选项 'allow updates' 已从 1 更改为 1。请运行 RECONFIGURE 语句进行安装。
消息 259,级别 16,状态 1,第 2 行
不允许对系统目录进行即席更新。
消息 207,级别 16,状态 1,第 0 行
列名 'ID' 无效。
检查标识信息: 当前标识值 '185825733',当前列值 '52'。
DBCC 执行完毕。如果 DBCC 输出了错误信息,请与系统管理员联系。
消息 259,级别 16,状态 1,第 2 行
不允许对系统目录进行即席更新。
配置选项 'allow updates' 已从 1 更改为 0。请运行 RECONFIGURE 语句进行安装。

[解决办法]
SQL code
--不过多少列你要自已写,此处的col1,col2...是你的列if object_id('sys_city_copy') is not null drop table sys_city_copy  select col1,col2... into sys_city_copy from sys_city--如果需排序,此处加入; drop table sys_city;  select id=identity(int,1,1),col1,col2... into sys_city from sys_city_copy;go  --如果你不在意你自增列的位置,可以这样,不过此自增列就跑到最后去了,呵呵alter table sys_city drop column id;  alter table sys_city add id int identity(1,1) not null;  go
[解决办法]
先改为非递增,改字段内容,最后改回自动递增
[解决办法]
探讨

先改为非递增,改字段内容,最后改回自动递增

[解决办法]
如果表不大,那你就把非自增列insert到一个临时表(如果怕丢失就插入一个实体表)。然后truncate掉源表(truncate可以清空自增),然后更改你源表的自增间隔,再把临时表的数据插回去。然后drop掉临时表。
[解决办法]
简单的话

SQL code
--先取消ID增,表->设计->ID列IDENTITY属性选为NO,然后declare @id int=0 update tb set id=@id,@id=@id+1--最后 将ID再重新改为自增表->设计->ID列IDENTITY属性选为YES 即可 

热点排行