測試了下,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
新聞熱點
疑難解答