I want to select previous and next row from table based on current id. I send current id to stored procedure and use this query:
-- previous
select top 1 id from table where id < @currentId order by id desc
-- next
select top 1 id from table where id < @currentId order by id asc
The problem is when I send currentId which is the last id in the table and want to select next row. Then is nothing selected. Same problem for previous row, when I send currentId which is first id in table
Is it possible to solve this in sql without additional queries?
Edit – just realized you always want two rows to be returned, re-working…
Updated code:
Original Post below, before I realized what exactly you wanted
You were really close, you needed the
UNIONoperator and one small syntax change to your query.This will return 1 row when the ID you pass it is the first row or last row, 2 rows otherwise.
Test code: