表x字段a,b读取表,加个id字段,从1开始编号,如何写?select ?? as id,a,b from x结果id  a  b
1   x  x
2   x  x
3   x  x
.
.
.

解决方案 »

  1.   

    select ROW_NUMBER() over(order by getdate) as id,a,b from x
      

  2.   


    --sql2005select 
    row_number()over(order by getdate()) as id,
    a,b from x
      

  3.   


    --sql 2000用临时表select id = identity(int,1,1) ,* into tmp from tbselect * from tmp
      

  4.   

    getdate()函数写错了,呵呵,还可以给表再加一个自动编号列:
    create table temp
    (
    aa varchar(1)
    )
    insert into temp
    select 'a' union all
    select 'b'alter table temp
    add id int identityselect * from temp
      

  5.   

    --2000
    --a:没有主键的情形:
       Select identity(int,1,1) as iid,* into #tmp from TableName
       Select * from #tmp
       Drop table #tmp
    --b:有主键的情形:
       Select (Select sum(1) from TableName where KeyField <= a.KeyField) as iid,* from TableName a order by iid
      

  6.   

    select 
    row_number()over(order by getdate()) as id,a,b from x
    --2005
    select identity(int,1,1) as id,*into #t from x
    select * from #t
    --2000
      

  7.   

    不明白楼主此做法的意义? 
    不同的排序(order by)条件,会有不同的结果.