Analysis of the asp.net paging Stored Procedure

Source: Internet
Author: User

Here we use the temporary performance of SQL to implement the database paging function. The benefits of this function can achieve mass data processing. For more information, see, if there is a better method for this method, please provide comments.

The Code is as follows: Copy code

Alter procedure [dbo]. [sp_ SQL _Paging]
(
@ SqlDataTable NVARCHAR (4000), -- table name
@ PrimaryKey NVARCHAR (4000), -- primary key name
@ Fields NVARCHAR (4000), -- the field to be returned
@ PageSize INT, -- page size
@ PageIndex INT, -- page number
@ RecordCount int output, -- total number of records
@ StrOrderBy NVARCHAR (4000), -- Sort
@ StrWhere NVARCHAR (4000) -- Query Condition
)
AS
BEGIN
SET NOCOUNT ON
DECLARE @ strSQL1 NVARCHAR (4000) -- SQL statement 1
DECLARE @ strSQL2 NVARCHAR (4000) -- SQL statement 2
DECLARE @ strSQL3 NVARCHAR (4000) -- SQL statement 3

SET @ strSQL1 = 'select' + @ PrimaryKey + ', ROW_NUMBER () OVER (' + @ strOrderBy +

') AS RowNumber FROM' + @ SqlDataTable + ''+ @ strWhere

-- Get the total number of records
SET @ strSQL3 = 'select @ recordCount = COUNT (*) FROM '+ @ SqlDataTable + ''+

@ StrWhere
EXEC SP_EXECUTESQL
@ Stmt = @ strSQL3,
@ Params = n' @ recordCount as int output ',
@ RecordCount = @ recordCount OUTPUT

-- Paging Query
IF @ pageIndex> @ recordCount * 1.0/@ pageSize + 1.0 OR @ recordCount <= @ pageSize
BEGIN
SET @ pageIndex = 1
END
SET @ strSQL2 = 'select' + @ Fields + 'from' + @ SqlDataTable + 'where' +

@ PrimaryKey + 'in (SELECT '+ @ PrimaryKey +' FROM ('+ @ strSQL1 +') TempTable WHERE

RowNumber BETWEEN '+ Str (@ pageIndex-1) * @ pageSize + 1) + 'and' + Str

(@ PageIndex * @ pageSize) + ')' + @ strOrderBy
EXEC SP_EXECUTESQL @ strSQL2
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.