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

Why can rails not find a route created by a helper? -

javascript - jquery or ashx not working -

opencv - DataType<cv::detail::deriv_type>::depth what is it used for -