6

假设我有这些行,

仪器ID

547
698
708

InstrumentID 不是自动生成的列。

假设我将过程中的参数作为 698 传递,我应该将前一个值作为 547 并将下一个值作为 708。如何在 SQL 中有效地执行此操作?

我有这个程序,但效率不高(也不正确)。

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
4

5 回答 5

12

这是一个更简单的解决方案,但它仍然更有效

SELECT P.PreviousID, N.NextID
FROM
(SELECT  MAX(D.InstrumentID) PreviousID
FROM Documents D
WHERE InstrumentID < @InstrumentID) P
CROSS JOIN
(SELECT  MIN(D.InstrumentID) NextID
FROM Documents D
WHERE InstrumentID > @InstrumentID) N
于 2013-02-19T08:21:07.773 回答
2

尝试这个:

Alter PROCEDURE GetNextAndPreviousInsturmentID
(
    @InstrumentID   varchar(14),
    @PreviousInstrumentID   varchar(14) OUT,
    @NextInstrumentID   varchar(14) OUT
)
AS
BEGIN

    Declare @Ids TABLE(Id varchar(14))

    ;With normal As
    (   
        --Numerate our rows
        Select ROW_NUMBER() Over (Order by Cast(Documents.InstrumentID as decimal(18)) as RowNumber,
               Documents.InstrumentID
        From Documents 

    )
    --Insert three rows from our table with our id and previos/next id
    INSERT INTO @Ids(Id)
    SELECT TOP(3) normal.InstrumentID
    FROM normal
    WHERE RowNumber >=
        (
            SELECT RowNumber - 1
            FROM normal
            WHERE normal.InstrumentID = @InstrumentID
        )
    ORDER BY normal.RowNumber
    --select next and previos ids

    SELECT @PreviousInstrumentID = Min(CAST(Id as decimal(18))),
           @NextInstrumentID = MAX(CAST(Id as decimal(18)))
    FROM @Ids
END
GO

在 MS SQL 2012 中,我们有新的窗口函数,如 FIRST_VALUE 和 LAST_VALUE,不幸的是在 sql 2008 中这些函数丢失了。

于 2013-02-19T07:17:03.847 回答
0
WITH CTE AS (
  SELECT rownum = ROW_NUMBER() OVER (ORDER BY p.LogDate), p.LogDate
  FROM DeviceLogs p
)
SELECT prev.logdate PreviousValue, CTE.logdate, nex.logdate NextValue
FROM CTE
LEFT JOIN CTE prev ON prev.rownum = CTE.rownum - 1
LEFT JOIN CTE nex ON nex.rownum = CTE.rownum + 1

GO
于 2015-01-17T12:05:24.990 回答
-1

嗨,我认为这会更有效率:

选择下一步:

select top 1 ID from mytable
where ID >'698'
order by ID asc

选择上一个:

select top 1 ID from mytable
where ID <'698'
order by ID desc
于 2014-07-05T11:29:46.050 回答
-1

选择

LAG(InstrumentID) OVER (ORDER BY InstrumentID) PreviousValue,
InstrumentID, 
LEAD(InstrumentID) OVER (ORDER BY InstrumentID) NextValue
from documents
于 2016-09-21T14:24:45.593 回答