Three types of SQL server paging stored procedures

Source: Internet
Author: User
Tags rtrim sort table name

Example 1. Used for paging of common data

The code is as follows: Copy code

Create procedure [dbo]. [Pub_DataPager]
@ PTableName nvarchar (1000), -- table name
@ PFieldNames nvarchar (max), -- string to be queried, separated by ",", or '*'
@ PWhere nvarchar (max), -- query condition
@ POrderby nvarchar (max), -- sort string, required field
@ PStartIndex int,
@ PEndIndex int,
@ PForceInnerJoin int = 0 -- 1 does not use SQL engine optimization. 0. This parameter is not recommended in general.
As
Begin
Set nocount on
Declare @ SQL nvarchar (max)
Select @ pWhere = rtrim (ltrim (isnull (@ pWhere, ''), @ pOrderby = rtrim (ltrim (isnull (@ pOrderby ,'')))
     
If (@ pOrderby = '') set @ pOrderby = 'iid'
If (@ pWhere <> '') set @ pWhere = 'where' + @ pWhere
Set @ pOrderby = 'Order by' + @ pOrderby
Set @ SQL = 'select * from (select '+ @ pFieldNames +', convert (int, ROW_NUMBER () OVER ('+ @ pOrderBy +') as DataIndexNumber'
Set @ SQL = @ SQL + 'from' + @ pTableName + @ pWhere + ') as a where DataIndexNumber between' + convert (nvarchar (15), @ pStartIndex) + 'and' + convert (nvarchar (15), @ pEndIndex)
Set @ SQL = @ SQL + 'Order by dataindexnumber'
If (@ pForceInnerJoin = 1)
Begin
Set @ SQL = @ SQL + 'option (force order )'
End
Exec (@ SQL)
End

Example 2: SQL 2005 General paging stored procedure

The ROW_NUMBER () General stored procedure is used to process the number of pages out of the range. There are a lot of more complex online operations, but this is very simple and practical.

The code is as follows: Copy code

Create Procedure [dbo]. [Usp_Pager]
@ TableName varchar (50), -- table name
@ Fields varchar (5000) = '*', -- field name (all fields are *)
@ OrderField varchar (5000), -- sort field (required! Supports multiple fields)
@ SqlWhere varchar (5000) = Null, -- condition statement (where is not required)
@ PageSize int, -- number of records per page
@ PageIndex int = 1, -- specifies the current page number
@ TotalRecord int output -- Total number of returned Records
As
Begin
 
Begin Tran -- start transaction
 
Declare @ SQL nvarchar (4000 );
Declare @ TotalPage int;
 
-- Calculate the total number of records
          
If (@ SqlWhere = ''or @ sqlWhere = NULL)
Set @ SQL = 'SELECT @ totalRecord = count (*) from' + @ TableName
Else
Set @ SQL = 'SELECT @ totalRecord = count (*) from '+ @ TableName + 'where' + @ sqlWhere
 
EXEC sp_executesql @ SQL, n' @ totalRecord int output', @ totalRecord OUTPUT -- calculate the total number of records
     
-- Calculate the total number of pages
Select @ TotalPage = CEILING (@ totalRecord + 0.0)/@ PageSize)
 
If (@ SqlWhere = ''or @ sqlWhere = NULL)
Set @ SQL = 'select * FROM (Select ROW_NUMBER () Over (order by '+ @ OrderField +') as rowId, '+ @ Fields + 'from' + @ TableName
Else
Set @ SQL = 'select * FROM (Select ROW_NUMBER () Over (order by '+ @ OrderField +') as rowId, '+ @ Fields + 'from' + @ TableName + 'where' + @ SqlWhere
         
     
-- Processing page number out of range
If @ PageIndex <= 0
Set @ pageIndex = 1
     
If @ pageIndex> @ TotalPage
Set @ pageIndex = @ TotalPage
 
-- Process start and end points
Declare @ StartRecord int
Declare @ EndRecord int
     
Set @ StartRecord = (@ pageIndex-1) * @ PageSize + 1
Set @ EndRecord = @ StartRecord + @ pageSize-1
 
-- Continue merging SQL statements
Set @ SQL = @ SQL + ') as' + @ TableName + 'Where rowId between' + Convert (varchar (50), @ StartRecord) + 'and' + Convert (varchar (50), @ EndRecord)
     
Exec (@ SQL)
---------------------------------------------------
If @ Error <> 0
Begin
RollBack Tran
Return-1
End
Else
Begin
Commit Tran
Return @ totalRecord --- Total number of returned Records
End
End

Example 3: Paging stored procedures for SQL 2005/2008

The code is as follows: Copy code

/*
  
@ CurrentPage: displays the page,
@ PageSize: the number of rows displayed on each page,
@ Field_info: the field to be displayed can be *,
@ Table_info: the table or view to be queried,
@ Field_id: primary key or unique field,
@ Field_Order: sorting field,
@ Otherwhere is a condition without "WHERE ",
@ RecordCount: total number of rows, OUTPUT
@ PageCount: total page number, OUTPUT
@ SQLSTR if an error occurs, you can use this parameter to output an SQL statement.
  
*/
Alter procedure [dbo]. [uoSp_RecordPager]
@ CurrentPage int = 1,
@ PageSize int = 10,
@ Field_Info varchar (500 ),
@ Table_info varchar (100 ),
@ Field_id varchar (20 ),
@ Field_Order varchar (100 ),
@ Otherwhere varchar (8000 ),
@ RecordCount int output,
@ PageCount int output,
@ SQL STR varchar (8000) output
AS
   
Begin
DECLARE @ MinPage int, @ MaxPage int
Declare @ SQL varchar (8000)
Declare @ sqlt nvarchar (4000)
   
Set @ sqlt = 'SELECT @ RecordCount = COUNT ('+ @ Field_id +') FROM '+ @ Table_Info
IF @ otherwhere! =''
Set @ sqlt = @ sqlt + 'where' + @ otherwhere
   
Exec sp_executesql @ sqlt, n' @ RecordCount int output', @ RecordCount output
   
-- How to put the exec execution result into a variable. If it is a string, use N. The variable after N must have the same name as the variable in @ sqlt.
   
IF @ PageSize <= 0
Begin
Set @ PageSize = 10
End
   
-- Else if @ PageSize> @ RecordCount
-- Begin
-- Set @ pageSize = @ RecordCount
-- End
   
Set @ pagecount = @ RecordCount/@ PageSize
   
If (@ recordcount % @ pagesize )! = 0) -- add one page if no cleaner exists
Begin
Set @ PageCount = @ RecordCount/@ PageSize
Set @ PageCount = @ pagecount + 1
End
Else
Begin
Set @ pagecount = @ recordcount/@ PageSize
End
   
IF @ CurrentPage <= 0
Begin
Set @ CurrentPage = 1
End
   
Else if @ CurrentPage> @ pagecount
Begin
Set @ currentpage = @ pagecount -- if the input page number is greater than the total page number, it indicates the last page.
End
   
SET @ MinPage = (@ CurrentPage-1) * @ PageSize + 1
   
SET @ MaxPage = @ MinPage + @ PageSize-1
   
        
   
BEGIN
   
If @ Field_Info like''
Set @ field_Info = '*'
   
IF @ otherwhere like''
Set @ SQL = 'SELECT top '+ str (@ PageSize) +' * from
(SELECT '+ @ Field_Info +', row_number () over (order by '+ @ Field_Order +') as rownumber
From '+ @ Table_info +'
) As TMP_TABLE where (rownumber between '+ convert (varchar (10), @ minpage) + 'and' + convert (varchar (10), @ maxpage) + ')'
ELSE
Set @ SQL = 'SELECT top '+ str (@ PageSize) +' * from
(SELECT '+ @ Field_Info +', row_number () over (order by '+ @ Field_Order +') as rownumber
From '+ @ Table_info +' where 1 = 1 and '+ @ otherwhere +'
) As TMP_TABLE where (rownumber between '+ convert (varchar (10), @ minpage) + 'and' + convert (varchar (10), @ maxpage) + ') and '+ @ otherwhere
   
EXEC (@ SQL)
SET @ SQLSTR = @ SQL
 
END
   
End

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.