当前位置: 代码迷 >> Sql Server >> 请问,SQL重新排号
  详细解决方案

请问,SQL重新排号

热度:54   发布时间:2016-04-24 09:54:34.0
请教,SQL重新排号
表中,有 int 型  pai   和字符串型的 spai 
现在表中数据有1千条。 有什么方法,让  pai 从 1001开始排列到1999

pai   spai
23     23
45     45
46     46
65     65
......

现在有什么方法让这些数据从1001开始排列到1999
例如:
pai      spai
1001   1001
1002   1002
1003   1003
1004   1004
......
------解决思路----------------------
如果可以清空的再插入的话, 试试这个

truncate table 原来的表

insert into 原来的表
 select number pai,cast(number as varchar) spai
  from master..spt_values where type='P' and number between 1001 and 1999
------解决思路----------------------

用row_number 生成行号 +1000  
然后update 掉原来的id ,
再把标识种子改成从1000开始,然后再插入就是从1000开始了。

------解决思路----------------------
楼主的表中的字段应该不止这两个。

select pai,spai,identity(int,1,1) as rId into #t from tablename order by pai,spai
update tablename set pai=1000+a.rId,spai=convert(varchar(10),(1000+a.rId))     from #t as a where pai=a.pai and spai=a.spai

------解决思路----------------------
引用:
楼主的表中的字段应该不止这两个。

select pai,spai,identity(int,1,1) as rId into #t from tablename order by pai,spai
update tablename set pai=1000+a.rId,spai=convert(varchar(10),(1000+a.rId))     from #t as a where pai=a.pai and spai=a.spai

稍微完善一下

select pai,spai,identity(int,1001,1) as rId into #t from tablename order by pai,spai
update tablename set pai=a.rId,spai=convert(varchar(10),a.rId)     from #t as a where pai=a.pai and spai=a.spai
  相关解决方案