復(fù)制代碼 代碼如下:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Pagination]
@Page int = 1, -- 當(dāng)前頁碼
@PageSize int = 10, -- 每頁記錄條數(shù)(頁面大小)
@Table nvarchar(500), -- 表名或視圖名,甚至可以是嵌套SQL:(Select * From Tab Where ID>1000) Tab
@Field nvarchar(800) = '*', -- 返回記錄集字段名,","隔開,默認(rèn)是"*"
@OrderBy nvarchar(100) = 'ID ASC', -- 排序規(guī)則
@Filter nvarchar(500), -- 過濾條件
@MaxPage smallint output, -- 執(zhí)行結(jié)果 -1 error, 0 false, maxpage true
@TotalRow int output, -- 記錄總數(shù) /* 2007-07-12 22:11:00 update */
@Descript varchar(100) output -- 結(jié)果描述
AS
BEGIN
-- =============================================
-- Author: Jimmy.Yu
-- Create date: 2007-5-11
-- Description: SQL 2005 以上版本 通用分頁存儲過程
-- =============================================
Set ROWCOUNT @PageSize;
Set @Descript = 'successful';
-------------------參數(shù)檢測----------------
IF LEN(RTRIM(LTRIM(@Table))) !> 0
Begin
Set @MaxPage = 0;
Set @Descript = 'table name is empty';
Return;
End
IF LEN(RTRIM(LTRIM(@OrderBy))) !> 0
Begin
Set @MaxPage = 0;
Set @Descript = 'order is empty';
Return;
End
IF ISNULL(@PageSize,0) = 0
Begin
Set @MaxPage = 0;
Set @Descript = 'page size error';
Return;
End
IF ISNULL(@Page,0) = 0
Begin
Set @MaxPage = 0;
Set @Descript = 'page error';
Return;
End
-------------------檢測結(jié)束----------------
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((@Page-1)*@PageSize AS nvarchar(8));
-- 執(zhí)行SQL, 取當(dāng)前頁記錄集
Execute(@SQL);
--------------------------------------------------------------------
-- 整合SQL
Set @SQL = 'Set @Rows = (Select MAX(ROWNUM) FROM (Select' + @Portion + ')';
-- 執(zhí)行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;
-- 執(zhí)行成功
Return;
END
相對應(yīng)的頁面邏輯中寫的對應(yīng)調(diào)用該存儲過程的方法(C#)
您可能感興趣的文章:- sqlserver 通用分頁存儲過程
- sqlserver 存儲過程分頁(按多條件排序)
- sqlserver 通用存儲過程分頁代碼(附使用ROW_NUMBER()和不使用ROW_NUMBER()兩種情況性能分析)
- sqlserver2005利用臨時表和@@RowCount提高分頁查詢存儲過程性能示例分享
- sqlserver 千萬數(shù)量級分頁存儲過程代碼
- sqlserver關(guān)于分頁存儲過程的優(yōu)化【讓數(shù)據(jù)庫按我們的意思執(zhí)行查詢計劃】
- sqlserver 存儲過程分頁代碼
- 分頁 SQLServer存儲過程
- 分頁存儲過程(三)在sqlserver中打造更加準(zhǔn)確的分頁結(jié)果
- SQLServer存儲過程實現(xiàn)單條件分頁