日期:2012-03-14  浏览次数:20420 次

DataGrid连接Access的快速分页法(4)——动态生成SQL语句
using System;
using System.Text;
namespace Paging
{
/// <summary>
/// FastPaging 的摘要说明。
/// </summary>
public class FastPaging {

private FastPaging() {
}

/// <summary>
/// 获取根据指定字段排序并分页查询的 SELECT 语句。
/// </summary>
/// <param name="pageSize">每页要显示的记录的数目。</param>
/// <param name="pageIndex">要显示的页的索引。</param>
/// <param name="recordCount">数据表中的记录总数。</param>
/// <param name="tableName">要查询的数据表。</param>
/// <param name="queryFields">要查询的字段。</param>
/// <param name="primaryKey">主键字段。</param>
/// <param name="ascending">是否为升序排列。</param>
/// <param name="condition">查询的筛选条件。</param>
/// <returns>返回排序并分页查询的 SELECT 语句。</returns>
public static String Paging(
int pageSize,
int pageIndex,
int recordCount,
String tableName,
String queryFields,
String primaryKey,
bool ascending,
String condition )
{
#region 实现

StringBuilder sb = new StringBuilder();
int pageCount = GetPageCount(recordCount,pageSize); //分页的总数
int middleIndex = GetMidPageIndex(pageCount); //中间页的索引
int firstIndex = 0; //第一页的索引
int lastIndex = pageCount - 1; //最后一页的索引

#region @PageIndex <= @FirstIndex
if (pageIndex <= firstIndex) {
sb.Append("SELECT TOP ").Append(pageSize).Append(" ").Append(queryFields)
.Append(" FROM ").Append(tableName);

if (condition != String.Empty)
sb.Append(" WHERE ").Append(condition);

sb.Append(" ORDER BY ").Append(primaryKey).Append(" ")
.Append(GetSortType(ascending));
}
#endregion

#region @FirstIndex < @PageIndex <= @MiddleIndex
else if (pageIndex > firstIndex && pageIndex <= middleIndex) {
sb.Append("SELECT TOP ").Append(pageSize).Append(" ").Append(queryFields)
.Append(" FROM ").Append(tableName)
.Append(" WHERE ").Append(primaryKey);

if (ascending)
sb.Append(" > (").Append(" SELECT MAX(");
else
sb.Append(" < (").Append(" SELECT MIN(");

sb.Append(primaryKey).Append(") FROM ( SELECT TOP ")
.Append(pageSize*pageIndex).Append(" ").Append(primaryKey)
.Append(" FROM ").Append(tableName);

if (condition != String.Empty)
sb.Append(" WHERE ").Append(condition);

sb.Append(" ORDER BY ").Append(primaryKey).Append(" ")
.Append(GetSortType(ascending))
.Append(" ) TableA )");

if (condition != String.Empty)
sb.Append(" AND ").Append(condition);

sb.Append(" ORDER BY ").Append(primaryKey).Append(" ")<