SQL Server 2000 到 2008 的超前和滞后替代方案应该是什么

What should be the alternative for lead and lag for SQL Server 2000 to 2008

对于 SQL Server 2000 到 2008,leadlag 的替代方案是什么?我正在尝试获取给定发票编号的上一个和下一个发票编号, 即 5

SqlDataAdapter invoiceAdptr = new SqlDataAdapter(@"
                 select t.prev_invNo, t.InvNo, t.next_invNo
                 from (select 
                           lag(InvNo) over (order by id) as prev_invNo,
                           InvNo,
                           lead(InvNo) over (order by id) as next_invNo
                       from Invoice1) t
                 where t.InvNo = " + invoiceNumber + "", con);

DataTable invoiceDataTable = new DataTable();
invoiceAdptr.Fill(invoiceDataTable);

var invoices = new Invoices()
{
    PreviousInvoice = Convert.ToString(invoiceDataTable.Rows[0]["prev_invNo"]),
    NextInvoice = Convert.ToString(invoiceDataTable.Rows[0]["next_invNo"]),
    CurrentInvoice = invoiceNumber
};

在 SQL 2005-2008 中使用 outer apply

select ilag.InvNo as prev_invNo,
       InvNo,
       ilead.InvNo as next_invNo
from Invoice1 i outer apply
     (select top 1 i2.*
      from Invoice1 i2
      where i2.id < i.id
      order by id2.id desc
     ) ilag outer apply
     (select top 1 i2.*
      from Invoice1 i2
      where i2.id > i.id
      order by id2.id asc
     ) ilead 
where t.InvNo = " + invoiceNumber + "";

请注意,不再需要子查询。但是,这通常比 lag()lead() 函数效率低得多。

不要使用 SQL Server 2000。多年来一直不受支持。 (如果确实要使用不受支持的软件,可以将上面的修改为子查询。)

如果有人无法升级...对于 Sql Server 2000,您可以使用子查询:

select
      InvNo
    , prev_invNo = (
        select top 1 invNo 
        from invoices p 
        where p.id < i.id 
        order by id desc
        )
    , next_invNo = (
        select top 1 invNo 
        from invoices n 
        where n.id > i.id 
        order by id asc
        )
  from Invoice1 as i

这对我有用

"WITH CTE AS(
                       SELECT rownum = ROW_NUMBER() OVER(ORDER BY p.InvNo),
                       p.InvNo FROM Invoice1 p
                     )
                   SELECT
                   prev.InvNo prev_invNo,
                       CTE.InvNo,
                       nex.InvNo next_invNo
                   FROM CTE
                   LEFT JOIN CTE prev ON prev.rownum = CTE.rownum - 1
                   LEFT JOIN CTE nex ON nex.rownum = CTE.rownum + 1
                   where CTE.InvNo = " + invoiceNumber + ""