测试了下,1200000条数据,查询不到1分钟,而使用传统的查询方法,要好几分钟
/*分页存储过程
descript:分页存储过程
author:blue.dream
date:2004-8-18 21:01
*/
create procedure listpage(
@tblname nvarchar(200), ----要显示的表或多个表的连接
@fldname nvarchar(200) = '*', ----要显示的字段列表
@pagesize int = 10, ----每页显示的记录个数
@page int = 1, ----要显示那一页的记录
@pagecount int = 1 output, ----查询结果分页后的总页数
@counts int = 1 output, ----查询到的记录数
@id nvarchar(50), ----主表的主键
@fldsort nvarchar(100) = null, ----排序字段列表或条件
@sort bit = 0, ----排序方法,0为升序,1为降序
@strcondition nvarchar(200) = null ----查询条件,不需where
)
as
set nocount on
declare @sqltmp nvarchar(1000) ----存放动态生成的sql语句
declare @strtmp nvarchar(1000) ----存放取得查询结果总数的查询语句
declare @strid nvarchar(1000) ----存放取得查询开头或结尾id的查询语句
declare @sqlsort nvarchar(200) ----存放临时生成的排序条件
declare @intcounts int ----要移动的记录数
declare @beginid int ----开始的id
declare @endid int ----结束的id
--------首先生成排序方法---------
if @sort=0 --升序
begin
if not(@fldsort is null)
set @sqlsort = ' order by ' + @fldsort
else
set @sqlsort = ' order by ' + @id
end
else --降序
begin
if not(@fldsort is null)
set @sqlsort = ' order by ' + @fldsort + ' desc'
else
set @sqlsort = ' order by ' + @id + ' desc '
end
--------生成查询语句--------
--此处@strtmp为取得查询结果数量的语句
if @strcondition is null --没有设置显示条件
begin
set @sqltmp = @fldname + ' from ' + @tblname
set @strtmp = 'select @counts=count(' + @id + ') from '[email protected]
set @strid = ' from ' + @tblname
end
else
begin
set @sqltmp = + @fldname + 'from ' + @tblname + ' where ' + @strcondition
set @strtmp = 'select @counts=count(' + @id + ') from '[email protected] + ' where ' + @strcondition
set @strid = ' from ' + @tblname + ' where ' + @strcondition
end
----取得查询结果总数量-----
exec sp_executesql @strtmp,n'@counts int out ',@counts out
--取得分页总数
if @counts <= @pagesize
set @pagecount = 1
else
set @pagecount = (@counts / @pagesize) + 1
--计算要移动的记录数
if @page = 1
set @intcounts = @pagesize
else
begin
set @intcounts = (@page-1) * @pagesize + 1
end
-----取得分页后此页的第一条记录的id
set @strid = 'select @beginid=' + @id + ' ' + @strid
set @intcounts = @intcounts - @pagesize + 1
set rowcount @intcounts
exec sp_executesql @strid,n'@beginid int out ',@beginid out
-----取得分页后此页的最后一条记录的id
set @intcounts = @intcounts + @pagesize - 1
print @intcounts
set rowcount @intcounts
exec sp_executesql @strid,n'@beginid int out ',@endid out
------恢复系统设置-----
set rowcount 0
set nocount on
------返回查询结果-----
if @strcondition is null
set @strtmp = 'select ' + @sqltmp + ' where ' + @id + ' between ' + str(@beginid) + ' and ' + str(@endid)
else
set @strtmp = 'select ' + @sqltmp + ' where ' + @id +' (between ' + str(@beginid) + ' and ' + str(@endid) + ') and ' + @strcondition
if not(@sqlsort is null)
set @strtmp = @strtmp + @sqlsort
exec sp_executesql @strtmp
go
新闻热点
疑难解答