這是我項目中使用的一個分頁存儲過程,具有很強的通用性。配合前臺ASP.NET使用50萬條數據基本感不到延遲。數據庫為SQLServer2000。
1.分頁存儲過程
CREATE procedure pagination
@str_sql varchar(1000) = '*', -- 執行的SQL 不含Order by 內容
@str_orderfield varchar(255)='''', -- 排序的字段名
@page_size int = 10, -- 頁大小
@page_index int = 0, -- 頁碼
@order_type int, -- 設置排序類型, 非 -1 值則降序
@total_count int output -- 返回記錄總數, 非 0 值則返回
as
---------------------
-- 獲取指定頁的數據--
---------------------
declare @strsql varchar(5000) -- 主語句
declare @strtmp varchar(5000) -- 臨時變量
declare @strorder varchar(400) -- 排序字串
declare @cruRow int -- 當前行號
--執行總數統計
exec getRowCount @str_sql,@total_count output
set @strtmp = ' select * from ' +
' (select top ' + convert(varchar(10),@page_size) + ' * from ' +
' (select top ' + convert(varchar(10),(@page_index + 1) * @page_size) +' * from '+ -- N+1頁
' ('+ @str_sql +') Src '
--排序方向
if @order_type !=0
begin
set @strsql= @strtmp +
' order by @str_orderfield asc) a ' +
' order by @str_orderfield desc)b' +
' order by @str_orderfield asc'
end
else
begin
set @strsql= @strtmp +
' order by @str_orderfield desc) a ' +
' order by @str_orderfieldasc)b' +
' order by @str_orderfield desc'
end
exec (@strsql)
GO
----------------------------------------------------------------------------
2.分頁存儲過程執行中用到的行數統計
create procedure getRowCount
@sql nvarchar(2000),
@count int output
as
begin
--------------------
-- 獲取數據總行數 --
--------------------
declare @tmpsql nvarchar(2000)
set @tmpsql='select @count=count(*) from ('+ @sql +') a'
execute sp_executesql @tmpsql,N'@count int output',@count output
end
GO