Selecting previous and next row using sp

Posted by davor on Stack Overflow See other posts from Stack Overflow or by davor
Published on 2011-11-23T17:12:54Z Indexed on 2011/11/23 17:51 UTC
Read the original article Hit count: 176

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about sql-server

Related posts about tsql