Search code examples
sqlsql-server-2014

How to find next bigger / equal text in SQL Server


I have a table like this

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

In my Windows Forms app, I need to "find next" button

  • first find "aaa" with id 1
  • then find "aaa" with id 5
  • and then find "bbb" with id 2

I use this query

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

but it always returns "aaa"

and

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

this does not return other id's


Solution

  • select      top 1
                [name],[id]
    
    from        [table] 
    
    where       (   [name]  = @name 
                and [id]    > @id
                )
            or  [name] > @name 
    
    order by    [name],[id]
    

    or

    lead looks on the next row when the rows are ordered by the order by expressions within the over clause.

    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