我有一张这样的表
id | name
------+-----------
1 | aaa
5 | aaa
2 | bbb
4 | bbb
10 | bbb
7 | ccc
9 | ccc
在我的Windows窗体应用中,我需要“找到下一个”按钮
我使用此查询
select
min(name)
from
table
where
[name] >='@name'
但它总是返回“aaa”
和
select
min(name)
from
table
where
[name] >'@name'
这不会返回其他ID
答案 0 :(得分:1)
select top 1
[name],[id]
from [table]
where ( [name] = @name
and [id] > @id
)
or [name] > @name
order by [name],[id]
或
当lead
子句中的order by
表达式对行进行排序时, over
会查看下一行。
select [name],[next_id] as [id]
from (select [id],[name],lead([id]) over (order by [name],@id) as [next_id]
from [table]
) t
where [name] = @name
and [id] = @id
答案 1 :(得分:1)
您可以排序记录,然后点击每个按钮,只需阅读下一条记录:
select name,
id
from Table
order by name,
id
答案 2 :(得分:1)
好吧,我认为这就是你想要的:
create table TestTable(id int, name nvarchar(max))
GO
insert into TestTable
values
(1, 'aaa'),
(5, 'aaa'),
(2, 'bbb'),
(4, 'bbb'),
(10, 'bbb'),
(7, 'ccc'),
(9, 'ccc')
GO
create function dbo.FindNext(@lastResultOrdinal int) returns nvarchar(max)
as begin
return (select name from TestTable order by name, id offset @lastResultOrdinal rows fetch next 1 rows only)
end
GO
create function dbo.LastOrdinalWasLast(@lastResultOrdinal int) returns bit
as begin
if ((select count(id) from TestTable) = @lastResultOrdinal)
return 1
return 0
end
GO
--Fetching First Result:
select dbo.FindNext(0)
select dbo.LastOrdinalWasLast(1)
--Fetching Last Result:
select dbo.FindNext(6)
select dbo.LastOrdinalWasLast(7)
dbo.FindNext
函数应该做的工作给它当前行的序数(从零开始的索引+ 1);而dbo.LastOrdinalWasLast
确保没有更多的行可以获取。