豆浆怎么做好吃:SQL语句如何返回某条记录在记录集中的第几条

来源:百度文库 编辑:高考问答 时间:2024/05/06 12:40:57
SQL语句如何返回某条记录在记录集中的第几条

比如有条记录的ID是5,记录集为select * from table where ID in (1,2,5,8,10) 那么ID为5的记录在这个记录集中应该是3,请问能否用一条sql语句来实现呢:
基本样式应该是
select $$$$$$ from
(select * from table where ID in (1,2,5,8,10))
where ID=5
就是标记 $$$$ 的地方应该怎么写呢?
含苞的方法 我试了可以,也写在了存储过程里面了,但循环的方法总觉得不太理想,有没有快速简单的方法呢?

沉默用户 你是拿我举的这个例子来说得 ,而我给出的记录集只是说测试用的,不一定就是ID的顺序排列的。

只能用Fetch来循环读取 把它放在存储过程里:
declare @cur_pos int
declare mycursor cursor for
select id from bbsmenu order by ID asc -查询条件
declare @col1 char(10)
select @cur_pos=1
open mycursor
fetch next from mycursor into:@col1
while @@fetch_status<>-1
begin
if @col1=1
begin
select @cur_pos
CLOSE mycursor
DEALLOCATE mycursor
return
end
select @cur_pos=@cur_pos+1
fetch next from mycursor into:@col1
end
CLOSE mycursor
DEALLOCATE mycursor.

sql好像没有提供这样的功能(也许本人不知道,知道的请教教我)

只能用Fetch来循环读取 把它放在存储过程里就OK拉

declare @cur_pos int
declare mycursor cursor for
select id from bbsmenu order by ID asc -查询条件
declare @col1 char(10)

select @cur_pos=1
open mycursor
fetch next from mycursor into:@col1
while @@fetch_status<>-1
begin
if @col1=1
begin
select @cur_pos
CLOSE mycursor
DEALLOCATE mycursor
return
end
select @cur_pos=@cur_pos+1
fetch next from mycursor into:@col1
end
CLOSE mycursor
DEALLOCATE mycursor

select count(*)+1
from
(select id from table where ID in (1,2,5,8,10)) as a
where ID<5

同理,如果想看8是第几个就把where 条件改成where id<8
这条语句只针对where 条件中指定的ID在子查询"select id from table where ID in (1,2,5,8,10) "的记录集中才是正确的,这应该满足楼主的需要。

该天有空告诉你