SQL: how to select the next id with id

There is one table T (id integer, primary key (id).
I want a parameterized query, which, given id i:
will return the next sequential identifier,
if I = the largest id in T, the query should return the smallest id in T (circular)

+3
source share
2 answers

You can select the smallest id by the value of @i (if any) and the smallest id, and then get the largest:

select max(id)
from (
  select top 1 id
  from T
  where id > @i
  order by id
  union all
  select top 1 id
  from T
  order by id
) x

Or perhaps:

select max(id)
from (
  select min(id) as id
  from T
  where id > @i
  union all
  select min(id)
  from T
) x
+6
source

This is similar to what you are looking for:

CREATE PROCEDURE dbo.ProcName
(
    @ID INTEGER
)
AS
SELECT TOP 1 id
FROM table
WHERE id > @ID
ORDER BY id
+1
source

Source: https://habr.com/ru/post/1742162/


All Articles