SQL Server2000 paging Stored Procedure
- Create procedure [DBO]. [getrecordwithpage]
- @ Fieldstype nvarchar (1000), -- Field List (with type), used for field declaration of @ t table variables, such as photoid int, userid int, phototitle nvarchar (50)
- @ Fieldslist nvarchar (500), -- Field List (without type), used to read the field of the @ t table variable by PAGE, can also be replaced by *, but the performance will decrease, such: photoid, userid, phototitle
- @ Selectsrting nvarchar (2000), -- read the record's SELECT statement from the @ t table variable
- @ Resultorderby nvarchar (200), -- Sort the paging result fields, such as: 'photoid ASC 'in ascending order and 'photoid DESC' in descending order. Note: in descending order, DESC must be added to selectsrting and here.
- @ Pagesize int, -- page size. 0 indicates that all rows are returned.
- @ Currentpage int, -- current page. The homepage is 1.
- @ Recordcount int output -- total number of records returned if the value is not 0
- As
- Begin
- Declare @ strsql varchar (4000)
- Declare @ SQL nvarchar (1000)
- Set @ strsql = 'Clare @ t table ('+ @ fieldstype + ');'
- Set @ strsql = @ strsql + 'insert into @ t' + @ selectsrting + ';'
- Set @ SQL = @ strsql + 'select @ AA = count (*) from @ t ;'
- Exec sp_executesql @ SQL, n' @ AA int output', @ recordcount output;
- If @ pagesize = 0
- Set @ strsql = @ strsql + 'select' + @ fieldslist + 'from @ t ;'
- Else
- If @ currentpage = 1
- Set @ strsql = @ strsql + 'select top ('+ STR (@ pagesize) +') '+ @ fieldslist +' from @ t ;'
- Else
- Begin
- Set @ strsql = @ strsql + 'select top ('+ STR (@ pagesize) + ') '+ @ fieldslist +' from (select top ('+ STR (@ pagesize * @ currentpage) +') '+ @ fieldslist +', row_number () over (order by '+ @ resultorderby + ')'
- Set @ strsql = @ strsql + 'as rownumber from @ t'
- Set @ strsql = @ strsql + ') as R where R. rownumber>' + STR (@ pagesize * (@ currentpage-1) + ';'
- End
- Exec (@ strsql)
- End
========================================================== ======================================