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

时间:2017-01-22 16:48:35

标签: sql-server sql-server-2000

对于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
};

3 个答案:

答案 0 :(得分:4)

在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.多年来一直不支持它。 (如果您真的想使用不支持的软件,可以将上述内容修改为子查询。)

答案 1 :(得分:1)

如果某人无法升级...对于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

答案 2 :(得分:0)

这对我有用

"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 + ""