通用分页存储过程4

 CREATE proc [dbo].[page]
     
@RecordCount int output,
     
@ReturnCount bit,
     
@QueryStr nvarchar(1000)='table1',      --表名、视图名、查询语句
     @PageSize int=20,             --每页的大小(行数)
     @PageCurrent int=2,             --要显示的页 从0开始
     @FdShow nvarchar (2000)='*',         --要显示的字段列表
     @IdentityStr nvarchar (100)='id',     --主键
     @WhereStr nvarchar (2000)='1=1',
     
@FdOrder nvarchar(100)='desc'         --排序    只能取desc或者asc
 as

 
set nocount on
 
declare
 
@sql nvarchar(2000)

 
if @WhereStr = ''
     
begin
     
set @WhereStr = '1=1'
     
end

 
if @ReturnCount=1
     
begin
     
declare @tsql nvarchar(200)
     
set @tsql=N'select @RecordCount = count(*) from ' + @QueryStr + ' where ' + @WhereStr
     
exec sp_executesql @tsql,N'@RecordCount int output',@RecordCount output
     
end

 
if @PageCurrent = 0
     
begin
     
set @sql = 'select top ' + cast(@PageSize as nvarchar(3)) + ' ' + @FdShow + ' from ' + @QueryStr + ' where ' + @WhereStr + ' order by ' + @IdentityStr + ' ' + @FdOrder
     
end

 
else
     
begin
         
if upper(@FdOrder= 'DESC'
             
begin
             
set @sql = 'select top ' + cast(@PageSize as nvarchar(3)) + ' ' + @FdShow + ' from ' + @QueryStr + ' where ' + @WhereStr + ' and ' + @IdentityStr + '< ( select min(' + @IdentityStr + ') from (select top ' + cast(@PageSize*@PageCurrent as nvarchar(10)) + ' ' + @IdentityStr + ' from ' + @QueryStr + ' where ' + @WhereStr + ' order by ' + @IdentityStr + ' desc) as t) order by ' + @IdentityStr + ' desc'
             
end
         
else
             
begin
             
set @sql = 'select top ' + cast(@PageSize as nvarchar(3)) + ' ' + @FdShow + ' from ' + @QueryStr + ' where ' + @WhereStr + ' and ' + @IdentityStr + '> ( select max(' + @IdentityStr + ') from (select top ' + cast(@PageSize*@PageCurrent as nvarchar(10)) + ' ' + @IdentityStr + ' from ' + @QueryStr + ' where ' + @WhereStr + ' order by ' + @IdentityStr + ' asc) as t) order by ' + @IdentityStr + ' asc'
             
end
      
end

 
--print @sql

 
execute(@sql)
posted @ 2009-02-16 13:04  ssihc  阅读(126)  评论(0编辑  收藏  举报