如何在SQL Server中查找下一个更大/相等的文本

时间:2016-12-06 08:45:30

标签: sql sql-server-2014

我有一张这样的表

 id   |     name   
------+-----------
 1    |     aaa
 5    |     aaa
 2    |     bbb
 4    |     bbb
 10   |     bbb
 7    |     ccc
 9    |     ccc

在我的Windows窗体应用中,我需要“找到下一个”按钮

  • 首先找到id为
  • 的“aaa”
  • 然后找到id为
  • 的“aaa”
  • 然后找到id为2的“bbb”

我使用此查询

select  
    min(name)  
from 
    table 
where 
    [name] >='@name' 

但它总是返回“aaa”

select  
    min(name)  
from 
    table 
where 
   [name] >'@name'

这不会返回其他ID

3 个答案:

答案 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确保没有更多的行可以获取。