一个分页存储过程分页,单个表没问题~多表查询时就不行了。。。。。请高手赐教!
一个分页存储过程分页,单个表没问题~多表查询时就不行了。。。。。请高手赐教!
源程序如下,多表关联查询时就出错!提示语法错误,郁闷中……
CREATE proc page
@RecordCount int output,
@QueryStr nvarchar(100),--表名、视图名、查询语句
@PageSize int, --每页的大小(行数)
@PageCurrent, --要显示的页 从0开始
@FdShow nvarchar (1000), --要显示的字段列表
@IdentityStr nvarchar (100), --主键
@WhereStr nvarchar (200),
@FdOrder nvarchar(100) --排序 只能取desc或者asc
as
declare
@sql nvarchar(2000)
set @sql = ''
if @WhereStr = ''
set @WhereStr = '1=1'
if(@RecordCount is null or @RecordCount<=0)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)
GO