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) |