/**
** 分页存储过程
** www.flyso.cn
** 传入的参数有:
** 备注:创建临时表
**/
if exists (select 1
from sysobjects
where name = 'Proc_PageableQuery'
and type = 'P')
drop procedure Proc_PageableQuery
go
create procedure Proc_PageableQuery
@QueryStr nvarchar(4000), -- 查询语句
@BeginRow varchar(8), -- 页起始的位置
@PageSize varchar(8) -- 每页行数
as
declare @tmpSQL nvarchar(4000) -- 查询语句
declare @StrSQL nvarchar(4000) -- 查询语句
begin
-- 初始化数据库
SET NOCOUNT ON;
-- 去掉左边空格,和 select
select @tmpSQL = lower(ltrim(@QueryStr));
select @tmpSQL = substring(@tmpSQL, len('select ') + 1, len(@tmpSQL));
-- 如果显示第一页,可以直接用top来完成
if @BeginRow = '0'
begin
select @StrSQL = 'select top ' + @PageSize + ' ' + @tmpSQL;
exec(@StrSQL);
return ;
end;
-- 先创建临时表
select @StrSQL = 'select identity(int, 1, 1) as id_PageRowID, * into #tmpPageTable from ( select top 100 percent '
+ @tmpSQL + ') table_TempPage ;';
-- 查询
select @StrSQL = @StrSQL + ' select top ' + @PageSize + ' * from #tmpPageTable where id_PageRowID between ('
+ @BeginRow + ' + 1) and (' + @BeginRow + ' + ' + @PageSize + '); ';
-- 除去临时表
select @strSQL = @strSQL + ' drop table #tmpPageTable;';
-- 运行
exec(@StrSQL);
SET NOCOUNT OFF;
end
go