Say I have these lines,
Instrumentmentid
547 698 708
InstrumentID is not an auto-generated column.
Say, if I pass the parameter in the procedure as 698, I should get the previous value as 547, and the next value - 708. How to do this efficiently in SQL?
I have this procedure, but it is not effective (and not correct).
Alter PROCEDURE GetNextAndPreviousInsturmentID ( @InstrumentID varchar(14), @PreviousInstrumentID varchar(14) OUT, @NextInstrumentID varchar(14) OUT ) AS BEGIN Declare @RowNum int = 0 Select @RowNum = ROW_NUMBER() Over (Order by Cast(@InstrumentID as decimal(18))) From Documents Where InstrumentID = @InstrumentID ;With normal As ( Select ROW_NUMBER() Over (Order by Cast(@InstrumentID as decimal(18))) as RowNum, Cast(InstrumentID as decimal(18)) as InstrumentID From Documents ) Select @PreviousInstrumentID = InstrumentID From normal Where RowNum = @RowNum - 1 Select @NextInstrumentID = InstrumentID From normal Where RowNum = @RowNum + 1 END GO
source share