您的位置:首页 > 其它

最通用的分页存储过程

2010-04-26 20:21 393 查看
--/*-----存储过程 分页处理 孙伟 2005-03-28创建 -------*/
--/*----- 对数据进行了2分处理使查询前半部分数据与查询后半部分数据性能相同 -------*/
--/*-----存储过程 分页处理 2005-04-21修改 添加Distinct查询功能-------*/
--/*-----存储过程 分页处理 2005-05-18修改 多字段排序规则问题-------*/
--/*-----存储过程 分页处理 2005-06-15修改 多字段排序修改-------*/
ALTER PROCEDURE dbo.proc_ListPage
(
@tblName nvarchar(200), ----要显示的表或多个表的连接
@fldName nvarchar(500) = '*', ----要显示的字段列表
@pageSize int = 1, ----每页显示的记录个数
@page int = 10, ----要显示那一页的记录
@pageCount int = 1 output, ----查询结果分页后的总页数
@Counts int = 1 output, ----查询到的记录数
@fldSort nvarchar(200) = null, ----排序字段列表或条件
@Sort bit = 0, ----排序方法,0为升序,1为降序(如果是多字段排列Sort指代最后一个排序字段的排列顺序(最后一个排序字段不加排序标记)--程序传参如:' SortA Asc,SortB Desc,SortC ')
@strCondition nvarchar(1000) = null, ----查询条件,不需where
@ID nvarchar(150), ----主表的主键
@Dist bit = 0 ----是否添加查询字段的 DISTINCT 默认0不添加/1添加
)
AS
SET NOCOUNT ON
Declare @sqlTmp nvarchar(1000) ----存放动态生成的SQL语句
Declare @strTmp nvarchar(1000) ----存放取得查询结果总数的查询语句
declare @strID nvarchar(1000) ----存放取得查询开头或结尾ID的查询语句

Declare @strSortType nvarchar(10) ----数据排序规则A
Declare @strFSortType nvarchar(10) ----数据排序规则B

Declare @SqlSelect nvarchar(50) ----对含有DISTINCT的查询进行SQL构造
Declare @SqlCounts nvarchar(50) ----对含有DISTINCT的总数查询进行SQL构造

if @Dist = 0
begin
set @SqlSelect = 'select '
set @SqlCounts = 'Count(*)'
end
else
begin
set @SqlSelect = 'select distinct '
set @SqlCounts = 'Count(DISTINCT '+@ID+')'
end




if @Sort=0


begin


set @strFSortType=' ASC '


set @strSortType=' DESC '


end


else


begin


set @strFSortType=' DESC '


set @strSortType=' ASC '


end








--------生成查询语句--------


--此处@strTmp为取得查询结果数量的语句


if @strCondition is null or @strCondition='' --没有设置显示条件


begin


set @sqlTmp = @fldName + ' From ' + @tblName


set @strTmp = @SqlSelect+' @Counts='+@SqlCounts+' FROM '+@tblName


set @strID = ' From ' + @tblName


end


else


begin


set @sqlTmp = + @fldName + 'From ' + @tblName + ' where (1>0) ' + @strCondition


set @strTmp = @SqlSelect+' @Counts='+@SqlCounts+' FROM '+@tblName + ' where (1>0) ' + @strCondition


set @strID = ' From ' + @tblName + ' where (1>0) ' + @strCondition


end




----取得查询结果总数量-----


exec sp_executesql @strTmp,N'@Counts int out ',@Counts out


declare @tmpCounts int


if @Counts = 0


set @tmpCounts = 1


else


set @tmpCounts = @Counts




--取得分页总数


set @pageCount=(@tmpCounts+@pageSize-1)/@pageSize






/**//**当前页大于总页数 取最后一页**/


if @page>@pageCount


set @page=@pageCount




--/*-----数据分页2分处理-------*/


declare @pageIndex int --总数/页大小


declare @lastcount int --总数%页大小




set @pageIndex = @tmpCounts/@pageSize


set @lastcount = @tmpCounts%@pageSize


if @lastcount > 0


set @pageIndex = @pageIndex + 1


else


set @lastcount = @pagesize




--//***显示分页


if @strCondition is null or @strCondition='' --没有设置显示条件


begin


if @pageIndex<2 or @page<=@pageIndex / 2 + @pageIndex % 2 --前半部分数据处理


begin


set @strTmp=@SqlSelect+' top '+ CAST(@pageSize as VARCHAR(4))+' '+ @fldName+' from '+@tblName


+' where '+@ID+' not in('+ @SqlSelect+' top '+ CAST(@pageSize*(@page-1) as Varchar(20)) +' '+ @ID +' from '+@tblName


+' order by '+ @fldSort +' '+ @strFSortType+')'


+' order by '+ @fldSort +' '+ @strFSortType


end


else


begin


set @page = @pageIndex-@page+1 --后半部分数据处理


if @page <= 1 --最后一页数据显示


set @strTmp=@SqlSelect+' * from ('+@SqlSelect+' top '+ CAST(@lastcount as VARCHAR(4))+' '+ @fldName+' from '+@tblName


+' order by '+ @fldSort +' '+ @strSortType+') AS TempTB'+' order by '+ @fldSort +' '+ @strFSortType


else


set @strTmp=@SqlSelect+' * from ('+@SqlSelect+' top '+ CAST(@pageSize as VARCHAR(4))+' '+ @fldName+' from '+@tblName


+' where '+@ID+' not in('+ @SqlSelect+' top '+ CAST(@pageSize*(@page-2)+@lastcount as Varchar(20)) +' '+ @ID +' from '+@tblName


+' order by '+ @fldSort +' '+ @strSortType+')'




+' order by '+ @fldSort +' '+ @strSortType+') AS TempTB'+' order by '+ @fldSort +' '+ @strFSortType


end


end




else --有查询条件


begin


if @pageIndex<2 or @page<=@pageIndex / 2 + @pageIndex % 2 --前半部分数据处理


begin


set @strTmp=@SqlSelect+' top '+ CAST(@pageSize as VARCHAR(4))+' '+ @fldName +' from '+@tblName


+' where '+@ID+' not in('+ @SqlSelect+' top '+ CAST(@pageSize*(@page-1) as Varchar(20)) +' '+ @ID +' from '+@tblName


+' Where (1>0) ' + @strCondition + ' order by '+ @fldSort +' '+ @strFSortType+')'


+' ' + @strCondition + ' order by '+ @fldSort +' '+ @strFSortType


end


else


begin


set @page = @pageIndex-@page+1 --后半部分数据处理


if @page <= 1 --最后一页数据显示


set @strTmp=@SqlSelect+' * from ('+@SqlSelect+' top '+ CAST(@lastcount as VARCHAR(4))+' '+ @fldName+' from '+@tblName


+' where (1>0) '+ @strCondition +' order by '+ @fldSort +' '+ @strSortType+') AS TempTB'+' order by '+ @fldSort +' '+ @strFSortType


else


set @strTmp=@SqlSelect+' * from ('+@SqlSelect+' top '+ CAST(@pageSize as VARCHAR(4))+' '+ @fldName+' from '+@tblName


+' where '+@ID+' not in('+ @SqlSelect+' top '+ CAST(@pageSize*(@page-2)+@lastcount as Varchar(20)) +' '+ @ID +' from '+@tblName


+' where (1>0) '+ @strCondition +' order by '+ @fldSort +' '+ @strSortType+')'


+ @strCondition +' order by '+ @fldSort +' '+ @strSortType+') AS TempTB'+' order by '+ @fldSort +' '+ @strFSortType


end


end




------返回查询结果-----


exec sp_executesql @strTmp


--print @strTmp


SET NOCOUNT OFF由于项目使用的GUID为主键字段,这里使用了not in这样的查询
有兴趣的朋友可以在使用自增张int类型数据是换成 select top id ... where id > .....
这样的模式 进一步提高性能!

配用的一个方法,这个方法是针对这个存储过程写的,非常方便应用,已经千锤百炼拉,

//返回构建的Sqlparameter
private SqlParameter GetAllSqlParameter<T>(T t, string keyName)
{
SqlParameter para = null;

System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);

foreach (System.Reflection.PropertyInfo item in properties)
{
string name = item.Name;
object value = item.GetValue(t, null);
if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
{
if (name == keyName)
{
para = new SqlParameter("@" + name, ReplaceChar(value.ToString()));

}

}
}
return para;

}
#endregion

***********
/// <summary>
/// 这个方法分了两种情况:字段中是否有“,”号。
/// 有的用Or连接,否则用and
/// 两种情况中再去判断值中是否有“,”号
/// </summary>
/// <param name="listName">传入的参数</param>
/// <param name="o">传入的对象</param>
/// <param name="!"> 不等于</param>
/// <param name="{"> 小于等于</param>
/// <param name="}"> 大于等于</param>
/// <param name="+"> 这里是当一个字段里存入两个时间,中间用‘,’分开的情况</param>
/// <param name="="> 等于</param>
/// <returns></returns>
#region 用于分页处理模糊查询
public string GetParameter(string[] listName, object o)
{
string re = " ";

if (listName.Length == 0 || o == null)
{
return "";
}
for (int i = 0; i < listName.Length; i++)
{
string stringSen = " "; //当前值
string stringSenTemp = " ";
//首先检测是否有逗号,来生成or条件,例如车牌号
if (listName[i].Contains(","))
{
#region //以下是有逗号的情况(字段名里有“,”)
stringSenTemp = " and ( 1>1"; //主要是为了连接后面的or条件
string[] strKeyOr = listName[i].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

for (int j = 0; j < strKeyOr.Length; j++)
{
string KeyName = strKeyOr[j].Substring(0, strKeyOr[j].Length - 1);
string strOp = strKeyOr[j].Substring(strKeyOr[j].Length - 1);
string KeyValue = getProperties(o, KeyName);

//首先判断值是否为空
if (KeyValue != "")
{
KeyValue = ReplaceChar(KeyValue);

//再判断操作符
switch (strOp)
{
case "*":
stringSenTemp += " or " + KeyName + " like " + "'%" + KeyValue + "%' ";
break;
case "!":
stringSenTemp += " or " + KeyName + " <> " + "'" + KeyValue + "' ";
break;
case "{":
stringSenTemp += " or " + KeyName + " <= " + "'" + KeyValue + "' ";
break;
case "}":
stringSenTemp += " or " + KeyName + " >= " + "'" + KeyValue + "' ";
break;
case "+":
if (KeyValue.Contains(","))
{
string[] keys = KeyValue.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
//判断是否是日期
if (IsDate(keys[0]))
{
stringSenTemp += " or " + KeyName + " >= " + "'" + keys[0] + "' ";
}
if (IsDate(keys[1]))
{
if (!keys[1].Contains(":"))
{
keys[1] += " 23:59:59";
}
stringSenTemp += " or " + KeyName + " <= " + "'" + keys[1] + "' ";
}

}
break;
default:
stringSenTemp += " or " + KeyName + " " + strOp + " " + "'" + KeyValue + "' ";
break;
}

}
}

stringSen += stringSenTemp.Trim().Equals("and ( 1>1") ? " " : stringSenTemp + " ) ";
#endregion
}
else
{
#region //以下是没有逗号的情况
string KeyName = listName[i].Substring(0, listName[i].Length - 1);
string strOp = listName[i].Substring(listName[i].Length - 1);
string KeyValue = getProperties(o, KeyName);
//首先判断值是否为空
if (KeyValue != "")
{
KeyValue = ReplaceChar(KeyValue);
//再判断操作符
switch (strOp)
{
case "*":
stringSen += " and " + KeyName + " like " + "'%" + KeyValue + "%' ";
break;
case "!":
stringSen += " and " + KeyName + " <> " + "'" + KeyValue + "' ";
break;
case "{":
stringSen += " and " + KeyName + " <= " + "'" + KeyValue + "' ";
break;
case "}":
stringSen += " and " + KeyName + " >= " + "'" + KeyValue + "' ";
break;
case "+":
if (KeyValue.Contains(","))
{
string[] keys = KeyValue.Split(new string[] { "," }, StringSplitOptions.None);//
//判断是否是日期并判断是否有值
if (keys.Length > 0)
{
if (IsDate(keys[0]))//这里有问题,如果是就输一个时间,不知是大于还是小于
{
stringSen += " and " + KeyName + " >= " + "'" + keys[0] + "' ";
}

}
if (keys.Length > 1)
{
if (IsDate(keys[1]))
{
if (!keys[1].Contains(":"))
{
keys[1] += " 23:59:59";
}
stringSen += " and " + KeyName + " <= " + "'" + keys[1] + "' ";
}
}

}
break;
default:
stringSen += " and " + KeyName + " " + strOp + " " + "'" + KeyValue + "' ";
break;
}
}
#endregion
}
re += stringSen;
}
return re.Trim();
}
//危险字符处理

private string ReplaceChar(string text)
{
return text.Replace("'", "''");
}
public bool IsDate(string text)
{

try
{
DateTime dt = Convert.ToDateTime(text);
return true;
}
catch
{
return false;
}

}
/// <summary>
/// 把你传入的值和实体类匹配(这样就可一写一个通用的分页方法)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="keyName"></param>
/// <returns></returns>

private string getProperties<T>(T t, string keyName)
{
string tStr = string.Empty;
if (t == null)
{
return tStr;
}
System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);

if (properties.Length <= 0)
{
return tStr;
}
foreach (System.Reflection.PropertyInfo item in properties)
{
string name = item.Name;
object value = item.GetValue(t, null);
if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
{
if (name == keyName)
{
tStr = value.ToString();
return tStr;
}
//tStr += string.Format("{0}:{1},", name, value);
}
else
{
getProperties(value, keyName);
}
}
return tStr;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: