Create Procedure Selectpagedsql
(
@ SQL Nvarchar ( 512 ),
@ Indexfield Nvarchar ( 100 ),
@ Pagesize Int = 10 ,
@ Pageindex Int = 1 ,
@ Sort Nvarchar ( 128 ) = @ Indexfield ,
@ Totalcount Int = 0 Output
)
As
Declare @ Strsql Nvarchar ( 1024 )
Set Nocount On
Set @ Strsql = '
Select @ totalcount = count (*) from ( ' + @ SQL + ' ) As T '
Exec Sp_executesql
@ Strsql ,
N ' @ Totalcount Int = 0 output ' ,
@ Totalcount = @ Totalcount Output
Declare @ Itemcount Int
Set @ Itemcount = @ Totalcount - @ Pagesize * @ Pageindex
If ( @ Itemcount < 0 )
Set @ Itemcount = @ Itemcount + @ Pagesize
Else
Set @ Itemcount = @ Pagesize
If ( @ Itemcount < 0 ) Return 1
Set @ Strsql = ' Select * from
(Select top ' + Str ( @ Itemcount ) + ' * From
(Select top ' + Str ( @ Pagesize * @ Pageindex ) + ' * From
( ' + @ SQL + ' ) As t0
Order ' + @ Indexfield + ' ASC) as T1
Order ' + @ Indexfield + ' DESC) as T2
Order ' + @ Sort
Exec Sp_executesql
@ Strsql
Go
---------------------------------- Set quoted_identifier off
Go
Set ansi_nulls off
Go
Createprocedure commgetrecordbypage
@ Tblname varchar (255), -- table name
@ Fldname varchar (255), -- primary key field name
@ Pagesize Int = 10, -- page size
@ Pageindex Int = 1, -- page number
@ Isrecount bit = 0, -- returns the total number of records. If the value is not 0, the system returns
@ Ordertype bit = 0, -- set the sorting type. If the value is not 0, the sorting type is descending.
@ Strwhere varchar (1000) = ''-- Query condition (Note: Do not add where)
As
Declare @ strsql varchar (6000) -- subject sentence
Declare @ strtmp varchar (100) -- Temporary Variable
Declare @ strorder varchar (400) -- sort type
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
Set @ strsql = 'select top '+ STR (@ pagesize) +' * from ['
+ @ Tblname + '] Where [' + @ fldname + ']' + @ strtmp + '(['
+ @ Fldname + ']) from (select top' + STR (@ PageIndex-1) * @ pagesize) + '['
+ @ Fldname + '] from [' + @ tblname + ']' + @ strorder + ') as tbltmp )'
+ @ Strorder
If @ strwhere! =''
Set @ strsql = 'select top '+ STR (@ pagesize) +' * from ['
+ @ Tblname + '] Where [' + @ fldname + ']' + @ strtmp + '(['
+ @ Fldname + ']) from (select top' + STR (@ PageIndex-1) * @ pagesize) + '['
+ @ Fldname + '] from [' + @ tblname + '] Where' + @ strwhere +''
+ @ Strorder + ') as tbltmp) and' + @ strwhere + ''+ @ strorder
If @ pageindex = 1
Begin
Set @ strtmp =''
If @ strwhere! =''
Set @ strtmp = 'where' + @ strwhere
Set @ strsql = 'select top '+ STR (@ pagesize) +' * from ['
+ @ Tblname + ']' + @ strtmp + ''+ @ strorder
End
If @ isrecount! = 0
Set @ strsql = 'select count (*) as total from ['+ @ tblname +'] '+ 'where' + @ strwhere
Exec (@ strsql)
Go
Set quoted_identifier off
Go
Set ansi_nulls on
Go
This is also good.