sql中如何对查询结果进行倒序遍历,并执行不同操作

引言

sql 中常见的遍历功能需要用到游标

正序遍历:

游标通常只能正序遍历,也即常见的如下for循环正序遍历:

for(int i = 0;i < list.length;i++)
{
	//正序遍历的形象展示
}
declare xx_cursor cursor for (select userId from User)
open xx_cursor

declare @id int

fetch next from xx_cursor into @id
while @@FETCH_STATUS = 0
begin
//在这里编写要操作的代码
fetch next from xx_cursor into @id
end
close xx_cursor
deallocate xx_cursor

倒序遍历:

在已知查询结果集并且无法改变结果集顺序的情况下,从最后一条数据开始倒序遍历;核心在于首先获取已知数据集的全部数量,然后借助fetch absolute x from xx_cursor into @id功能来获取固定x行的数据;

for(int i = list.length -1;i >= 0;i--)
{
	//倒序遍历的形象展示
}
declare @count int
select @count = count(*) from User//
		
declare xx_cursor scroll cursor for (select userId from User)
open xx_cursor

declare @id int

fetch absolute @count from xx_cursor into @id
while @count > 0
begin
//在这里编写要操作的代码
if(@count - 1 > 0)
	begin
		set @count = @count - 1
		fetch absolute @count from xx_cursor into @id
	end
else
	begin
		break
	end
end
close xx_cursor
deallocate xx_cursor