SQL paging stored procedures commonly used in asp.net

Source: Internet
Author: User

SQL paging stored procedures commonly used in asp.net

The following is a reference fragment:
Create PROCEDURE [dbo]. [MyPage]
@tblName varchar (255),--table name
@fldName varchar (255),--The sorted field name, typically uniquely identified
@strGetFields varchar (1000) = ' * ',--columns to be returned
@PageSize int = 10,--How many records per page
@PageIndex int = 1,--page
@Count int output,--Returns the total number of records
@OrderType bit = 0,--set sort type, not 0 value descending
@strWhere varchar (1500) = ' 1=1 '--Query condition (Note: Do not add where, initialize to 1=1 make query condition never empty)
As
DECLARE @strSQL varchar (5000)--subject sentence
DECLARE @strTmp varchar (110)--Temporary variable
DECLARE @strOrder varchar (400)--Sort type
declare @sumsql nvarchar (3000)--Total records
--Total execution statistics.
Set @sumsql = ' Select @Count = Count (*) from ' + @tblname + ' where ' + @strwhere
EXEC sp_executesql @sumsql, N ' @Count int output ', @Count output--record Total
--If @ordertype is not 0, perform descending
If @OrderType!= 0
Begin
Set @strTmp = ' < (select Min '
Set @strOrder = ' ORDER by [' + @fldName + '] desc '
End
Else
Begin
Set @strTmp = ' > select Max '
Set @strOrder = ' ORDER by [' + @fldName + '] ASC '
End
--If the first page executes the following code, speed up execution
If @PageIndex = 1
Set @strSQL = ' SELECT top ' + str (@PageSize) + ' + @strGetFields + '
From [' + @tblName + '] where ' + @strWhere + ' + @strOrder
Else
--The following code gives @strsql the SQL code to actually execute
Set @strSQL = ' SELECT top ' + str (@PageSize) + ' + @strGetFields + ' from ['
+ @tblName + '] where [' + @fldName + '] ' + @strTmp + ' (['
+ @fldName + ']) from (select Top + str (@PageIndex-1) * @PageSize) + ' ['
+ @fldName + '] from [' + @tblName + '] where ' + @strWhere + '
+ @strOrder + ') as tbltmp) and ' + @strWhere + ' + @strOrder
EXEC (@strSQL)



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.