MD TAHMID HOSSAIN MD TAHMID HOSSAIN - 1 month ago 9
SQL Question

how to find next element in sql server

i have this SQL

it produces output like below


A
B
C
D
......
......
ZZZZ


lets say the user has given me "AZ". i want to return him "BA".
how to do that ?

Thank you

Answer

With SQL Server 2014 you are on the lucky side. There is LEAD

Add this to your last select

SELECT *
       ,LEAD(ALPHA) OVER(ORDER BY (SELECT NULL)) AS NextAlpha
 FROM T AS T1

And be aware, that the ORDER BY (SELECT NULL) would work with this kind of query only, you should rather use a decent sort criterium.