Dire che ho queste righe,Come ottenere valore precedente e successiva della riga efficientemente in SQL Server
InstrumentID
547
698
708
InstrumentID non viene generato automaticamente colonna.
Dire se passo il parametro nella procedura come 698, dovrei ottenere il valore precedente come 547 e il valore successivo come 708. Come faccio a farlo in modo efficiente in SQL?
Ho questa procedura ma non è efficiente (e non è corretta).
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
Come sarà la sua condizione di * RowNumber = ( SELEZIONA RowNumber - 1 FROM WHERE normale normal.InstrumentID = @InstrumentID ) * risultato in 3 righe? Inoltre non hai ancora memorizzato nelle variabili OUT? – Jack
Mi dispiace, l'ho perso, ho aggiornato la risposta e ho anche aggiunto l'uso dei parametri OUT –