C#中構建一個分頁的應用
1、SQL分頁語法
SELECT * FROM(
SELECT ROW_NUMBER() OVER(ORDER BY 排序條件) AS RowNumber,* FROM 表
WHERE 條件
) TEMP_TABLE WHERE RowNumber BETWEEN (pageIndex - 1) * pageSize + 1 AND pageIndex * pageSize
2、後臺方法
/// <summary> /// 表名 /// </summary> private const string _tableNane = "StockIC"; /// <summary> /// 獲取庫存列表 /// </summary> public List<StockIcResult> GetStockIcList(StockIcParam param) { List<StockIcResult> list = new List<StockIcResult>(); string sql = "WITH [temptablefor{0}] AS"; sql += " (SELECT *,ROW_NUMBER() OVER (ORDER BY {1}) AS RowNumber FROM [{0}] WHERE 1=1 {2})"; sql += " SELECT * FROM [temptablefor{0}] WHERE RowNumber BETWEEN {3} AND {4}"; StringBuilder sqlCondition = new StringBuilder(); List<SqlParameter> sqlParams = new List<SqlParameter>(); //型號 if (!String.IsNullOrEmpty(param.Model)) { sqlCondition.AppendFormat(" AND Model LIKE '%{0}%'", param.Model); } //開始時間 if (param.BeginTime.HasValue) { sqlCondition.Append(" AND CreateTime >= @BeginTime"); sqlParams.Add(new SqlParameter("@BeginTime", param.BeginTime.Value)); } //結束時間 if (param.EndTime.HasValue) { sqlCondition.Append(" AND CreateTime < @EndTime"); sqlParams.Add(new SqlParameter("@EndTime", param.EndTime.Value.AddDays(1))); } //排序 if (String.IsNullOrWhiteSpace(param.OrderBy)) { param.OrderBy = " CreateTime DESC"; } //分頁 Int64 startNumber = (param.PageIndex - 1) * param.PageSize + 1; Int64 endNumber = param.PageIndex * param.PageSize; //拼裝SQL sql = String.Format(sql, _tableNane, param.OrderBy, sqlCondition, startNumber, endNumber); //執行SQL語句 DataSet dataSet = DBHelper.GetReader(sql.ToString(), sqlParams.ToArray()); list = TranToList(dataSet); return list; }
注意:DBHelper.GetReader()方法、TranToList()方法等請自己完善。
一些計算方法
//分頁
Int64 startNumber = (param.PageIndex - 1) * param.PageSize + 1;
Int64 endNumber = param.PageIndex * param.PageSize;
//總頁數 = (資料總數 + 分頁大小 -1) / 分頁大小
TotalPage = (TotalCount + PageSize - 1) / PageSize;