关于用sql生成自增列问题(不是字段自增)~~

michaelpeng7799 2003-09-13 12:31:50
不能改字段,要在select语句中实现第一列是自增的,也就是原字段不变,只是在查询结果中加一列自增列。用select来做。

多谢!!
...全文
445 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
zjcxc 元老 2003-09-13
  • 打赏
  • 举报
回复
有主键的可以直接用:

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


没有主键的需要用临时表:
select 自增列=identity(int,1,1),* into #tb from 表
select * from #tb
drop table #tb
pengdali 2003-09-13
  • 打赏
  • 举报
回复
select (select sum(1) from 你的表 where 你的自增字段<=a.你的自增字段) num,* from 你的自增字段 a
P1mm 2003-09-13
  • 打赏
  • 举报
回复
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 a
order by col1,col2,...
P1mm 2003-09-13
  • 打赏
  • 举报
回复
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,...排同一个序号,如果要不同序号,只能用楼上的方法


txlicenhe 2003-09-13
  • 打赏
  • 举报
回复
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

34,875

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧