我以前是按时间先后录入的数据,现在想新增一个字段按主题排序来自动添加编号(从1开始)
例如:
原始记录:
ID    Title    
1      1
2      5
3      2
新增字段后变成
ID    Title   NewId
1      1       1
2      5       3
3      2       2
然后在删除以前的id把新的NewId设置成为主键
(备注:这个有自己的用出,请各位帮帮忙哦)

解决方案 »

  1.   

    --這個?
    select newid=identity(int,1,1) ,*  into #t from T
      

  2.   

    select newid=identity(int,1,1) ,*  into #t from T order by title
      

  3.   

    ----创建测试数据
    declare @t table(id int,Title int,NewId int)
    insert @t
    select 1,1,NULL union all
    select 2,5,NULL union all
    select 3,2,NULL
    ----生成NewId
    select idd = identity(int,1,1), * into #tmp from @t order by Title
    ----更新NewId
    update a set NewId = b.idd from @t a inner join #tmp b on a.Title = b.Title
    ----查看NewId
    select * from @t
    drop table #tmp