declare @output int
exec Pagination 'news','nid','nid',@output output,1,'*',5,3,''
print @output
alter proc Pagination
@TableName varchar(50) --表名
,@OrderFld varchar(50) --排序字段
,@KeyFld varchar(30) --主键字段
,@DataCount int output --输出参数 总数据条数
,@OrderType int =1 --排序类型 1:升序 其它降序
,@ReturnFields varchar(200) = '*' --要返回的字段
,@PageSize int = 10 --一页显示多少条数据
,@PageIndex int = 1 --当前页
,@WhereStr varchar(300) ='' --条件
as
begin
declare @OrderBy varchar(300) --排序字符串
declare @WhereTemp varchar(300)--条件字符串
declare @TotalRecord int --总数据条数
declare @SelSql nvarchar(1000)--查询的sql
declare @CountWhere varchar(200)--计算数据条数的where
declare @CountSql nvarchar(1000)--计算数据总条数的sql
set @OrderBy = ''
set @WhereTemp = ''
if @OrderFld <> ''
begin
if @OrderType = 1
begin
set @OrderBy = ' order by '+@OrderFld+' asc '
end
else
begin
set @OrderBy = ' order by '+@OrderFld+' desc '
end
end
if @WhereStr <> ''
begin
set @WhereTemp = ' where '+@WhereStr +' and '
set @CountWhere = ' where '+@WhereStr
end
else
begin
set @WhereTemp = ' where '
set @CountWhere = ''
end
--print '为什么不出来呢'
set @CountSql = 'select @TotalRecord = count(1) from '+@TableName+@CountWhere
execute sp_executesql @CountSql,N'@TotalRecord int out',@TotalRecord out
--print '数据总条数为:'+cast(@TotalRecord as varchar(30))
set @SelSql = 'select top ('+cast(@PageSize as varchar(10))+
') '+@ReturnFields+'from '+@TableName+@WhereTemp+@KeyFld +
' not in (select top ('+cast((@PageSize*(@PageIndex-1)) as varchar(20))+
') '+@KeyFld+' from '+@TableName+')'
set @DataCount = @TotalRecord
--print @SelSql
execute sp_executesql @SelSql
--select @TotalRecord
--set @OutPut = cast(@TotalRecord as varchar(30))
end