SQL Server通用分頁預存程序,用預存程序可以提高效率與節約時間。
IF EXISTS(SELECT * FROM SYSOBJECTS WHERE name = 'commonPagination')DROP PROC commonPaginationGOCREATE proc [dbo].[commonPagination] @columns varchar(500), --要顯示的列名,用逗號隔開 @tableName varchar(100), --要查詢的表名 @orderColumnName varchar(100), --排序的列名 @order varchar(50), --排序的方式,升序為asc,降序為 desc @where varchar(100), --where 條件,如果不帶查詢條件,請用 1=1 @pageIndex int, --當前頁索引 @pageSize int, --頁大小(每頁顯示的記錄條數) @pageCount int output --總頁數,輸出參數 as begin declare @sqlRecordCount nvarchar(1000) --得到總記錄條數的語句 declare @sqlSelect nvarchar(1000) --查詢語句 set @sqlRecordCount=N'select @recordCount=count(*) from ' +@tableName + ' where '+ @where declare @recordCount int --儲存總記錄條數的變數 exec sp_executesql @sqlRecordCount,N'@recordCount int output',@recordCount output --動態 sql 傳參 if( @recordCount % @pageSize = 0) --如果總記錄條數可以被頁大小整除 set @pageCount = @recordCount / @pageSize --總頁數就等於總記錄條數除以頁大小 else --如果總記錄條數不能被頁大小整除 set @pageCount = @recordCount / @pageSize + 1 --總頁數就等於總記錄條數除以頁大小加1 set @sqlSelect = N'select '+@columns+' from ( select row_number() over (order by ' +@orderColumnName+' '+@order +') as tempid,* from ' +@tableName+' where '+ @where +') as tempTableName where tempid between ' +str((@pageIndex - 1)*@pageSize + 1 ) +' and '+str( @pageIndex * @pageSize) exec (@sqlSelect) --執行動態Sql end
--以下是調用樣本
use pubs
go
declare @pageCount int
exec commonPagination
'job_id,job_desc','jobs','job_id',
'asc','1=1',2,2,@pageCount output
select '總頁數為:' + str(@pageCount)
IF EXISTS(SELECT * FROM SYSOBJECTS WHERE name = 'Pagination')DROP PROCEDURE PaginationGOCREATE PROCEDURE Pagination@Columns VARCHAR(500), -- The columns to be displayed, divide by comma@Tablename VARCHAR(100), -- The name of the table to be searched@OrderColumnName VARCHAR(100), -- The name of the column to be used in order@Order VARCHAR(50), -- The order method, ASC or DESC@Where VARCHAR(100), -- The where condition, if there is not conditon use 1=1@PageIndex INT, -- Current page index@PageSize INT, -- The size of the page@PageCount INT OUTPUT -- The total page count,define as output parameterASBEGINDECLARE @SqlRecordCount NVARCHAR(100) -- The SQL Statement to get the total count of the recordsDECLARE @SqlSelect NVARCHAR(1000) -- The SQL SELECT statmentSET @SqlRecordCount = N'SELECT @RecordCount = COUNT(*) FROM' + @Tablename + ' WHERE ' +@WhereDECLARE @RecordCount INTEXEC sp_executesql @SqlRecordCount, N'@RecordCount INT OUTPUT',@RecordCount OUTPUT -- Transfer the parameter dynamicIF(@RecordCount % @PageSize = 0)SET @PageCount = @RecordCount / @PageSizeELSESET @PageCount = @RecordCount / @PageSize + 1SET @SqlSelect = N'SELECT ' + @Columns + ' FROM(SELECT ROW_NUMBER() OVER (ORDER BY ' + @OrderColumnName +' ' + @Order + ') AS tempid, * FROM ' + @Tablename + ' WHERE ' + @Where + ') AS tempTableName WHERE tempid BETWEEN ' + STR((@PageIndex - 1)*@PageSize + 1) + ' AND ' + STR(@PageIndex * @PageSize)EXEC (@SqlSelect)ENDGO