SQLServer stored efficient paging procedure

/ ************************************************* *********************
parameters: @PrimaryKey primary key, @ OrderBy sort field, @ SqlStr sql statement @ PageSize records to display per page, @ PageIndex this page ( starting 0)
********************************************** ************************************************************ /
the ALTER Procedure [the dbo] [PageQuery].
@PrimaryKey VARCHAR (100), - the primary key
@OrderBy varchar (100 ), - the sort field
@SqlStr varchar (8000), - sql statement
@PageSize int, - records to display per page
@PageIndex int-- this page (starting with 1)
- @ the RecordCount the Output int - return total records
AS
DECLARE @ExecSql VARCHAR (8000) - the Sql combinations to perform
IF the OrderBy @ = ''
SET = the OrderBy @ 'Order by' the PrimaryKey @ + + 'ASC'
the else IF (len (@OrderBy) <Upper. 8 or (the substring (the OrderBy @, 1,8)) <> 'the ORDER BY')
SET = the OrderBy @ 'order by '+@OrderBy
if @PageSize=-1--用于ajax的第一次查询
set @PageSize=0
set @PageIndex=@PageIndex-1
print('-----'+CAST(@PageIndex as varchar(10)) )
begin
declare @recordCount int,@pageCount int
declare @s nvarchar(4000)
set @s = N'select @recordCount = count('+@PrimaryKey+') from ('+@SqlStr+') TN'
exec sp_executeSql @s,N'@recordCount int output',@recordCount output
if(@pageSize>0)
set @pageCount = (@recordCount - 1 + @PageSize) / @PageSize;--总页数
else
set @pageCount = 0;--总页数

    if @PageIndex<=0--如果是第一页就执行这个
        begin
            set @ExecSql='select top '+cast(@PageSize as varchar(100))+' * from ('+@SqlStr+') T '+@OrderBy
        end
    else
        begin
            if charindex('2000 - 8.00.',@@version)>0
                begin
                    set @ExecSql=
                    'select top '+cast(@PageSize as varchar(100))+' *
                    from ('+@SqlStr+') as T where T.'+@PrimaryKey+' not in
                    (select top '+cast((@PageSize*@PageIndex) as varchar(100))+' '+@PrimaryKey+'
                        from ('+@SqlStr+') T2 '+@OrderBy+') '+ @OrderBy
                end
            else
                begin
                    set @ExecSql=
                    'select * from
                    (
                        select * from
                        (SELECT *, #RowNum#=ROW_NUMBER() OVER('+@OrderBy+') FROM ('+@SqlStr+') T1) T2 where T2.#RowNum#>='+cast(@PageSize*@PageIndex+1 as varchar(10))+' and T2.#RowNum#<='+cast(@PageSize*(@PageIndex+1) as varchar(10))+'
                    ) T3
                    '
                end
        end
        exec (@ExecSql+' select '+@recordCount+' as RecordCount,'+@pageCount+' as PageCount ')

end

Guess you like

Origin www.cnblogs.com/Yann123/p/11711172.html