Basf_EProject/EProject/BLL/PagingHelper.cs

49 lines
1.9 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace BLL
{
public static class PagingHelper
{
/// <summary>
/// 获取分页SQL语句默认ROW_NUMBER为关健字所有表不允许使用该字段名
/// </summary>
/// <param name="_recordCount">记录总数</param>
/// <param name="_pageSize">每页记录数</param>
/// <param name="_pageIndex">当前页数</param>
/// <param name="_safeSql">SQL查询语句</param>
/// <param name="_orderField">排序字段,多个则用“,”隔开</param>
/// <returns>分页SQL语句</returns>
public static DataTable CreatePage(int _pageSize, int _pageIndex, string _safeSql, string _orderField, IDataParameter[] parameters, out int RecordCount)
{
//拼接SQL字符串加上ROW_NUMBER函数进行分页
StringBuilder newSafeSql = new StringBuilder();
newSafeSql.AppendFormat("SELECT ROW_NUMBER() OVER(ORDER BY {0}) as RowIndex,", _orderField);
newSafeSql.Append(_safeSql.Substring(_safeSql.ToUpper().IndexOf("SELECT") + 6));
//拼接成最终的SQL语句
StringBuilder sbSql = new StringBuilder();
sbSql.Append("SELECT * FROM (");
sbSql.Append(newSafeSql.ToString());
sbSql.Append(") AS T");
sbSql.AppendFormat(" WHERE RowIndex > {0} and RowIndex<={1}", ((_pageIndex - 1) * _pageSize), _pageIndex * _pageSize);
sbSql.Append(" ");
sbSql.AppendFormat(" SELECT COUNT(1) AS RecordCount FROM ({0}) AS T ", _safeSql);
//return sbSql.ToString();
DataSet ds = SQLHelper.RunSqlStrings(sbSql.ToString(), parameters);
DataTable table = ds.Tables[0];
RecordCount = int.Parse(ds.Tables[1].Rows[0]["RecordCount"].ToString());
return table;
}
}
}