以前(大概一年前吧)看见一个人写的一片文章说的只用SQL 分页
嗯,具体思想很简单,就是反查再正查,比起用去差集的那种思想要快。
当时我也就记得那么多了,具体的代码我都没有记住
今天项目需要,我跟我MM机遇这种思想,从新实现一次
具体代码如下: (SQL-Server 2005下测试通过)
ALTER PROCEDURE [dbo].[SP_WebContentPager]
@pagesize int,
@pageid int,
@boardid int
AS
BEGIN
-- declare @pagesize int;
-- declare @pageid int;
declare @totalCount int;
declare @tail int;
declare @SQL varchar (5000);
-- select @pagesize = 2;
-- select @pageid = 2;

select @totalCount = count(*) from dbo.WebContent where BoardID=@boardid;

select @tail = @pagesize * @pageid;
if @tail > @totalCount
begin
select @SQL = 'select top '
+ convert ( varchar(50) , @totalCount%@pagesize ) -- 求模运算符有问题mod(@totalCount,@pagesize)
+ ' * from dbo.WebContent where BoardID='
+ convert ( varchar(50) , @boardid)
+ ' order by CID asc';
end


else
begin

select @SQL = 'select top ';
select @SQL = @SQL + convert ( varchar(50) , @tail);
select @SQL = @SQL + ' CID from dbo.WebContent '
+ ' where boardid=' + convert ( varchar(50) , @boardid)
+ ' order by CID desc'

select @SQL = 'select top '+convert ( varchar(50) , @pagesize)
+' CID from dbo.WebContent where CID in('
+ @SQL
+ ')order by CID asc'

select @SQL = 'select * from dbo.WebContent where CID in('
+ @SQL
+ ')order by CID DESC'
end


--print @SQL;
exec (@SQL);
END
有个小问题是求模运算符那里,好像Sql-Server 2000 是MOD(X,Y)的吧。
这里加如一个IF 判断,是为了在最后一页正确显示的。
我的SQL还是不是太熟练,希望大家一起讨论。
嗯,具体思想很简单,就是反查再正查,比起用去差集的那种思想要快。
当时我也就记得那么多了,具体的代码我都没有记住
今天项目需要,我跟我MM机遇这种思想,从新实现一次
具体代码如下: (SQL-Server 2005下测试通过)
ALTER PROCEDURE [dbo].[SP_WebContentPager]
@pagesize int,
@pageid int,
@boardid int
AS
BEGIN
-- declare @pagesize int;
-- declare @pageid int;
declare @totalCount int;
declare @tail int;
declare @SQL varchar (5000);
-- select @pagesize = 2;
-- select @pageid = 2;
select @totalCount = count(*) from dbo.WebContent where BoardID=@boardid;
select @tail = @pagesize * @pageid;
if @tail > @totalCount
begin
select @SQL = 'select top '
+ convert ( varchar(50) , @totalCount%@pagesize ) -- 求模运算符有问题mod(@totalCount,@pagesize)
+ ' * from dbo.WebContent where BoardID='
+ convert ( varchar(50) , @boardid)
+ ' order by CID asc';
end

else
begin
select @SQL = 'select top ';
select @SQL = @SQL + convert ( varchar(50) , @tail);
select @SQL = @SQL + ' CID from dbo.WebContent '
+ ' where boardid=' + convert ( varchar(50) , @boardid)
+ ' order by CID desc'
select @SQL = 'select top '+convert ( varchar(50) , @pagesize)
+' CID from dbo.WebContent where CID in('
+ @SQL
+ ')order by CID asc'
select @SQL = 'select * from dbo.WebContent where CID in('
+ @SQL
+ ')order by CID DESC'
end

--print @SQL;
exec (@SQL);
END有个小问题是求模运算符那里,好像Sql-Server 2000 是MOD(X,Y)的吧。
这里加如一个IF 判断,是为了在最后一页正确显示的。
我的SQL还是不是太熟练,希望大家一起讨论。
本文介绍了一种使用SQL Server 2005进行高效分页的方法,通过先逆序查询再正序显示的方式优化了传统分页策略,并针对最后一页面进行了特殊处理。
1324

被折叠的 条评论
为什么被折叠?



