sql分頁存儲過程

CREATE PROCEDURE [dbo].[UP_GetRecordByPage]
    @tblName      varchar(255),       --table name
    @fldName      varchar(255),       --key filed name
    @PageSize     int = 10,           --page size
    @PageIndex    int = 1,            --page index
    @IsReCount    bit = 0,            --record count
    @OrderType    bit = 0,            --asc:0 or desc:1
    @strWhere     varchar(1000) = ''  --where
AS

declare @strSQL   varchar(6000)      
declare @strTmp   varchar(100)       
declare @strOrder varchar(400)       

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)

posted on 2007-06-19 11:20  白亚伟  阅读(699)  评论(0编辑  收藏  举报

导航