SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:顺子
-- Create date: 2008-6-4
-- Description: 通用分页,用于单表查询,联合查询不适用,只适用于sql server 2005,利用ROW_NUMBER()新特性
-- Update: 2008-6-8
-- 修正大于2页时的显示不正确的问题
-- =============================================
Create PROCEDURE usp_Common_Paging
(
@tablename nvarchar(255),--操作的表名
@pagesize int,--单页显示个数
@pageindex int,--当前页码
@condition nvarchar(1000),--筛选条件,格式: a=1 and b=2
@primarykey nvarchar(255),--主键,格式: id
@order nvarchar(255)--排序,格式: id desc,id2 desc
)
AS
DECLARE @sqlcount nvarchar(2000)
DECLARE @sql nvarchar(2000)
DECLARE @orderby nvarchar(255)
SET @orderby = ISNULL(@order,@primarykey)
IF(LEN(@orderby)=0)
SET @orderby=@primarykey
SET @orderby=' '+@orderby
SET @sql='WITH temptbl AS ('
SET @sql=@sql+'Select ROW_NUMBER() OVER (ORDER BY '+@orderby+')AS ROW_NUM, * from '+@tablename
set @sqlcount='Select count(0) FROM '+@tablename
IF(LEN(ISNULL(@condition,''))>0)
BEGIN
set @sqlcount=@sqlcount+ ' where ' + @condition
set @sql=@sql+ ' where ' + @condition
End
DEclARE @rowstart nvarchar(20),@rowend nvarchar(20)
if(@pageindex<1) SET @pageindex=1
SET @rowstart=(@pageindex-1)*@pagesize+1
SET @rowend=CAST((@pageindex-1)*@pagesize+@pagesize as nvarchar(20))
-- 此处会导致第三页开始显示不正确的问题,故注释掉,复制时要把这些删掉
-- update:2008-6-8
--if(@pageindex>2)
--BEGIN
-- SET @rowstart=CAST((@pageindex*@pagesize)+1 as nvarchar(20))
-- SET @rowend=CAST((@pageindex*@pagesize)+@pagesize as nvarchar(20))
--END
set @sql=@sql+')Select * FROM temptbl where ROW_NUM between '+@rowstart+' and '+@rowend
EXECUTE sp_executesql @sql
EXECUTE sp_executesql @sqlcount
GO
我的说明:原创作品,如果您发现有错误或不合理的地方,还请提出!
注意:本存储过程只适用于Sql server 2005,且是单表查询,不支持联合查询