A simple stored procedure data paging

Source: Internet
Author: User
Tags unique id
1. The database structure is as follows: (after creating a database in SQL, execute the following SQL script directly in the SQL structure queryer)
If exists (select * from dbo. sysobjects where id = object_id (n' [dbo]. [Mobile] ') and OBJECTPROPERTY (id, n'isusertable') = 1)
Drop table [dbo]. [Mobile]
GO
Create table [dbo]. [Mobile] (
[MobileID] [int] IDENTITY (1, 1) not null,
[MobileType] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO
2. Stored Procedure (you can create a stored procedure directly in the database and then copy it to the database)
/*
Stored Procedure page
*/
Create procedure Proc_Paging
(
@ TBName NVARCHAR (255 ),
@ SQL nVARCHAR (4000), -- SQL statements without sorting statements
@ Page int, -- Page number
@ RecsPerPage int, -- number of records per page
@ Id varchar (255), -- unique ID to be sorted
@ Sort VARCHAR (255), -- Sort fields and rules
@ PageCount int output -- Total number of pages
)
AS
BEGIN
DECLARE @ sql1 nvarchar (4000)
SET @ sql1 = n' SELECT @ PageCount = COUNT (*)'
+ N' from' + @ tbname
EXEC sp_executesql @ sql1, n' @ PageCount int output', @ PageCount OUTPUT
SET @ PageCount = (@ PageCount + @ RecsPerPage-1)/@ RecsPerPage
END
BEGIN
DECLARE @ Str nVARCHAR (4000)
SET @ Str = 'SELECT TOP '+ CAST (@ RecsPerPage as varchar (20) +' * FROM ('+ @ SQL +') T WHERE T. '+ @ ID +' not in (select top '+ CAST (@ RecsPerPage * (@ Page-1) as varchar (20 )) + ''+ @ ID + 'FROM (' + @ SQL + ') T9 ORDER BY' + @ Sort + ') ORDER BY' + @ Sort
-- PRINT @ Str
-- EXEC sp_ExecuteSql @ Str
-- EXEC @ Str
DECLARE @ Str1 NVARCHAR (400)
DECLARE @ Str2 NVARCHAR (400)
SET @ Str1 = CAST (@ RecsPerPage as varchar (20 ))
SET @ Str2 = CAST (@ RecsPerPage * (@ Page-1) as varchar (20 ))

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.