首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 與 Access 分頁類實作:NOT IN 子查詢分頁法

     編輯:關於ASP.NET

針對 Access 資料庫不支援 ROW_NUMBER()、OFFSET/FETCH 的特性,實作基於 NOT IN 子查詢的通用分頁類,支援條件篩選、排序與頁碼跳轉。

完整原始碼

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace pager
{
    public class Pager
    {
        public static string GetPager(string strWhere, int pagesize, int pageindex, string orderCol, string TableName)
        {
            if (pageindex == 1)
            {
                return "select top " + pagesize + " * from " + TableName + " order by " + orderCol + " DESC";
            }
            else
            {
                StringBuilder strSql = new StringBuilder();
                strSql.AppendFormat("select top {0} * from {1} ", pagesize, TableName);
                strSql.AppendFormat(" where {1} not in (select top {0} id from {2} ", pagesize * (pageindex - 1), orderCol, TableName);
                if (strWhere.Trim() != "")
                {
                    strSql.AppendFormat(" where {0} order by {1} DESC) and {0}", strWhere, orderCol);
                }
                else
                {
                    strSql.AppendFormat(" order by {0} DESC) ", orderCol);
                }
                strSql.AppendFormat(" order by {0} DESC", orderCol);
                return strSql.ToString();
            }
        }
    }
}

SQL 生成邏輯解析

  • 第 1 頁:SELECT TOP N * FROM Table ORDER BY Col DESC
  • 第 N 頁 (N>1):SELECT TOP N * FROM Table WHERE Col NOT IN (SELECT TOP (N-1)*PageSize Col FROM Table [WHERE ...] ORDER BY Col DESC) [WHERE ...] ORDER BY Col DESC

適用場景與限制

  • 適用:Access、SQL Server 2000/2005 早期版本、小資料量(< 10 萬筆)
  • 效能隱憂:NOT IN 子查詢在大資料量下效能急劇下降,子查詢需掃描前 N 頁資料
  • orderCol 必須唯一(建議用 PK),否則分頁邊界會有資料遺漏或重複
  • 動態 SQL 拼接存在注入風險,生產環境建議改用參數化查詢或預存程序

現代替代方案

  • SQL Server 2012+:OFFSET @PageSize * (@PageIndex-1) ROWS FETCH NEXT @PageSize ROWS ONLY
  • SQL Server 2005-2008:ROW_NUMBER() OVER (ORDER BY Col) AS RowNum 包裝 CTE
  • Entity Framework / Dapper:.Skip().Take() LINQ 轉譯最佳化分頁
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved