create PROCEDURE [dbo].[PagingRecord]
(
@PageIndex int,--页号,从0开始
@PageSize int,--页尺寸
@OrderField varchar(100),--排序字段及类型(多个条件用逗号分开)如:JobID DESC,Checkintime
@TableName varchar(100),--表名或视图表
@FieldList varchar(2000),--欲选择字段列表
@DoCount AS bit=1-- 0值返回记录总数, 非 0 值则返回记录
)
AS
DECLARE @SqlQuery varchar(4000)
IF @DoCount<>0--需要返回记录总数
begin
DECLARE @SearchSql AS Nvarchar(4000)
SET @SearchSql= 'SELECT Count(*) AS Total FROM '+@tablename
exec sp_executesql @SearchSql
--print @SearchSql
end
SET @SqlQuery='SELECT '+@FieldList+'
FROM (SELECT row_number() over(ORDER BY '+@OrderField+') as rownum,
'+@FieldList+'
FROM '+@TableName+') as temp
WHERE rownum BETWEEN ('+cast(@PageIndex as varchar)+'-1)*'+cast(@PageSize as varchar)+'+1 and '+cast(@PageIndex as varchar)+'*'+cast(@PageSize as varchar)+'
ORDER BY '+@OrderField
--print @SqlQuery
SET NOCOUNT ON
execute(@SqlQuery)
SET NOCOUNT OFF
注意事项:(
@PageIndex int,--页号,从0开始
@PageSize int,--页尺寸
@OrderField varchar(100),--排序字段及类型(多个条件用逗号分开)如:JobID DESC,Checkintime
@TableName varchar(100),--表名或视图表
@FieldList varchar(2000),--欲选择字段列表
@DoCount AS bit=1-- 0值返回记录总数, 非 0 值则返回记录
)
AS
DECLARE @SqlQuery varchar(4000)
IF @DoCount<>0--需要返回记录总数
begin
DECLARE @SearchSql AS Nvarchar(4000)
SET @SearchSql= 'SELECT Count(*) AS Total FROM '+@tablename
exec sp_executesql @SearchSql
--print @SearchSql
end
SET @SqlQuery='SELECT '+@FieldList+'
FROM (SELECT row_number() over(ORDER BY '+@OrderField+') as rownum,
'+@FieldList+'
FROM '+@TableName+') as temp
WHERE rownum BETWEEN ('+cast(@PageIndex as varchar)+'-1)*'+cast(@PageSize as varchar)+'+1 and '+cast(@PageIndex as varchar)+'*'+cast(@PageSize as varchar)+'
ORDER BY '+@OrderField
--print @SqlQuery
SET NOCOUNT ON
execute(@SqlQuery)
SET NOCOUNT OFF
传入的那个table字符串,你可以后面加上 where 条件拼接起来。
如果需要返回总查询量,最后那个参数 @DoCount 传递 1 进去,不然传递 0 进去。
这个是这篇文章的改编 http://www.cnblogs.com/Randy0528/archive/2007/02/05/640788.html