如何在Select语句中增加自增字段

不能改字段,要在select语句中实现第一列是自增的,也就是原字段不变,只是在查询结果中加一列自增列。用select来做。
1:
select identity(int,1,1) as iid,* into #tmp from 表
select * from #tmp
2: 如果有关键字段
select (select sum(1) where keyfield <= a.keyfield) as iid,* from 表 a

  • select
    1+isnull((select count(*) from tablename
    where col1<a.col1
    or (col1=a.col1 and col2<a.col2)
    or (col1=a.col1 and col2=a.col2 and col3<a.col3)
    ...
    ),0) as 序号
    ,*
    from tablename
    order by col1,col2,...

    注意:col1,col2,...排同一个序号,如果要不同序号,只能用楼上的方法

    select (select sum(1) from 你的表 where 你的自增字段<=a.你的自增字段) num,* from 你的自增字段 a

    有主键的可以直接用:

    select 自增列=(select sum(1) from 表 where 主键<=a.主键),* from 表 a


    没有主键的需要用临时表:
    select 自增列=identity(int,1,1),* into #tb from 表
    select * from #tb
    drop table #tb

  • posted @ 2008-11-14 08:51  余魁  阅读(1402)  评论(0编辑  收藏  举报