SqlServer2000通用分页存储过程返回总记录行数

August 18, 2011 | tags    | views
Comments 0

CREATE   procedure pagination

 

 @str_sql           varchar(1000) = '*',     -- 执行的SQL 不含Order by 内容  

 @str_orderfield    varchar(255)='''',       -- 排序的字段名 

 @page_size         int = 10,                     -- 页大小 

 @page_index        int = 0,                      -- 页码

 @order_type        int,                           -- 设置排序类型, 非 -1 值则降序 

 @total_count       int   output                 -- 返回记录总数, 非 0 值则返回 

as

 

---------------------

-- 获取指定页的数据--

---------------------

 

declare @strsql   varchar(5000)              -- 主语句

declare @strtmp   varchar(5000)             -- 临时变量

declare @strorder varchar(400)              -- 排序字串

declare @cruRow   int                            -- 当前行号

 

 

--执行总数统计

 declare @tmpsql nvarchar(2000)

 set @tmpsql='select @count=count(*)  from ('+ @str_sql +') a'

 execute sp_executesql @tmpsql,N'@count int output',@total_count output

 

set @strtmp =  ' select * from ' + 

        '      (select top ' + convert(varchar(10),@page_size) + ' * from ' +

        '         (select top ' + convert(varchar(10),(@page_index + 1) * @page_size)  +' * from '+        -- N+1页

        '            ('+ @str_sql +') Src '

 

--排序方向

if @order_type !=0

 begin

 set @strsql= @strtmp +

       '          order by '+@str_orderfield+' asc) a ' +

       '       order by '+@str_orderfield+' desc) b ' +

              ' order by '+@str_orderfield+' asc '

 end

else

 begin

 set @strsql= @strtmp +

       '          order by '+ @str_orderfield+'  desc) a ' +

       '       order by '+  @str_orderfield+' asc) b ' +

              ' order by '+  @str_orderfield +' desc '

 end

 

exec (@strsql)

GO

 

执行:
declare @total_count int
exec pagination 'select * from tableA','ID',20,100,0,@total_count output
 
select @total_count



文章本月排行 文章本年排行
   



发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。