----------------------分页存储过程----------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[Proc_Page]
@PageIndex int = 1, -- 当前页码
@PageSize int = 10, -- 每页记录条数(页面大小)
@Table nvarchar(2000), -- 表名或视图名,甚至可以是嵌套SQL:(Select * From Tab Where ID>1000) Tab
@Field nvarchar(200) = '*', -- 返回记录集字段名,","隔开,默认是"*"
@OrderBy nvarchar(100) = 'ID ASC', -- 排序规则
@Filter nvarchar(500), -- 过滤条件
@MaxPage int output, -- 执行结果 -1 error, 0 false, maxpage true
@TotalRow int output, -- 记录总数
@Descript varchar(100) output -- 结果描述
AS
BEGIN
Set ROWCOUNT @PageSize;
Set @Descript = '';
Set @MaxPage = 0;
-------------------检测结束----------------
Begin Try
-- 整合SQL
Declare @SQL nvarchar(4000), @Portion nvarchar(4000);
Set @Portion = ' ROW_NUMBER() OVER (ORDER BY ' + @OrderBy + ') AS ROWNUM FROM ' + @Table;
Set @Portion = @Portion + (CASE WHEN LEN(@Filter) >= 1 THEN (' Where ' + @Filter + ') AS tab') ELSE (') AS tab') END);
Set @SQL = 'Select TOP(' + CAST(@PageSize AS nvarchar(8)) + ') ' + @Field + ' FROM (Select ' + @Field + ',' + @Portion;
Set @SQL = @SQL + ' Where tab.ROWNUM > ' + CAST((@PageIndex-1)*@PageSize AS nvarchar(8))+' ORDER BY ' + @OrderBy;
PRINT @SQL;
-- 执行SQL, 取当前页记录集
Execute(@SQL);
-- 整合SQL
Set @SQL = 'Set @Rows = (Select MAX(ROWNUM) FROM (Select' + @Portion + ')';
-- 执行SQL, 取最大页码
Execute sp_executesql @SQL, N'@Rows int output', @TotalRow output;
Set @MaxPage = (CASE WHEN (@TotalRow % @PageSize)<>0 THEN (@TotalRow / @PageSize + 1) ELSE (@TotalRow / @PageSize) END);
End Try
Begin Catch
-- 捕捉错误
Set @MaxPage = -1;
Set @Descript = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return;
End Catch;
-- 执行成功
Return;
END
GO
----------------------short 分页存储过程-------------------------------------------------------
if (exists (select * from sys.objects where name = 'Proc_DataPage'))
drop proc Proc_DataPage
GO
CREATE PROCEDURE Proc_DataPage
@PageIndex int = 1, -- 当前页码
@PageSize int = 10, -- 每页记录条数
@Table nvarchar(2000), -- tabs or (Select * From tab) tabs
@Field nvarchar(200) , -- 返回记录集字段
@OrderBy nvarchar(100) , -- 排序规则
@Filter nvarchar(500), -- 过滤条件
@TotalRow int output -- 记录总数
AS
BEGIN
Declare @SQL nvarchar(4000), @Portion nvarchar(4000);
Set @Portion = ' ROW_NUMBER() OVER (ORDER BY ' + @OrderBy + ') AS ROWNUM FROM ' + @Table;
Set @Portion = @Portion + (CASE WHEN LEN(@Filter) >= 1 THEN (' Where ' + @Filter + ') AS tab') ELSE (') AS tab') END);
Set @SQL = 'Select TOP(' + CAST(@PageSize AS nvarchar(8)) + ') ' + @Field + ' FROM (Select ' + @Field + ',' + @Portion;
Set @SQL = @SQL + ' Where tab.ROWNUM > ' + CAST((@PageIndex-1)*@PageSize AS nvarchar(8))+' ORDER BY ' + @OrderBy;
Execute(@SQL);
Set @SQL = 'Set @Rows = (Select MAX(ROWNUM) FROM (Select' + @Portion + ')';
Execute sp_executesql @SQL, N'@Rows int output', @TotalRow output;
End
GO