sql server 2012 - TSQL get the Prev and Next ID on a list -


let's have table sales

  • saleid int
  • userid int
  • field1 varchar(10)
  • created datetime

and right have loaded , viewing record saleid = 23

what's right way find out, using stored procedure, what's previous , next salesid value off current saleid = 23, belongs me (userid = 1)?

i

select top 1 *  sales  saleid > 23 , userid = 1    

and same saleid < 23 that's 2 sql calls.

is there better way?

i'm using sql server 2012.

you can previous/next saleid (or other field) using lag() , lead() functions introduced in sql server 2012.

for example:

select *,    lag(saleid) on (partition userid order saleid) prev,   lead(saleid) on (partition userid order saleid) next sales s 

sqlfiddle


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

inno setup - TLabel or TNewStaticText - change .Font.Style on Focus like Cursor changes with .Cursor -