(转载)SQL分页语句
比较万能的分页:
select top 每页显示的记录数 * from topic where id not in
(select top (当前的页数-1)×每页显示的记录数 id from topic order by id desc)
order by id desc
需要注意的是在access中不能是top 0,所以如果数据只有一页的话就得做判断了。。
SQL2005中的分页代码:
with temptbl as (
SELECT ROW_NUMBER() OVER (ORDER BY id desc)AS Row,
...
)
SELECT * FROM temptbl where Row between @startIndex and @endIndex
SELECT ROW_NUMBER() OVER (ORDER BY id desc)AS Row,
...
)
SELECT * FROM temptbl where Row between @startIndex and @endIndex
分页存储过程:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:XX
-- Create date: 2009-07-22 12:41
-- Description: 分页,用到了ROW_NUMBER()
-- =============================================
ALTER PROCEDURE [dbo].[proc_ShowPage]
@tblName varchar(255), -- 表名
@strGetFields varchar(1000) = '*', -- 需要返回的列,默认*
@strOrder varchar(255)='', -- 排序的字段名,必填
@strOrderType varchar(10)='ASC', -- 排序的方式,默认ASC
@PageSize int = 10, -- 页尺寸,默认10
@PageIndex int = 1, -- 页码,默认1
@strWhere varchar(1500) = '' -- 查询条件 (注意: 不要加 where)
AS
declare @strSQL varchar(5000)
if @strWhere !=''
set @strWhere=' where '+@strWhere
set @strSQL=
'SELECT * FROM ('+
'SELECT ROW_NUMBER() OVER (ORDER BY '+@strOrder+' '+@strOrderType+') AS pos,'+@strGetFields+' '+
'FROM ['+@tblName+'] '+@strWhere+
') AS sp WHERE pos BETWEEN '+str((@PageIndex-1)*@PageSize+1)+' AND '+str(@PageIndex*@PageSize)
exec (@strSQL)
print @strSQL -- 测试用,可在查询的时候看到生成的SQL语句
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:XX
-- Create date: 2009-07-22 12:41
-- Description: 分页,用到了ROW_NUMBER()
-- =============================================
ALTER PROCEDURE [dbo].[proc_ShowPage]
@tblName varchar(255), -- 表名
@strGetFields varchar(1000) = '*', -- 需要返回的列,默认*
@strOrder varchar(255)='', -- 排序的字段名,必填
@strOrderType varchar(10)='ASC', -- 排序的方式,默认ASC
@PageSize int = 10, -- 页尺寸,默认10
@PageIndex int = 1, -- 页码,默认1
@strWhere varchar(1500) = '' -- 查询条件 (注意: 不要加 where)
AS
declare @strSQL varchar(5000)
if @strWhere !=''
set @strWhere=' where '+@strWhere
set @strSQL=
'SELECT * FROM ('+
'SELECT ROW_NUMBER() OVER (ORDER BY '+@strOrder+' '+@strOrderType+') AS pos,'+@strGetFields+' '+
'FROM ['+@tblName+'] '+@strWhere+
') AS sp WHERE pos BETWEEN '+str((@PageIndex-1)*@PageSize+1)+' AND '+str(@PageIndex*@PageSize)
exec (@strSQL)
print @strSQL -- 测试用,可在查询的时候看到生成的SQL语句