SQLServer分页查询存储过程
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQLServer分页查询存储过程相关的知识,希望对你有一定的参考价值。
项目中用到的SQLServer分页查询存储过程。
【存储过程】
create PROCEDURE prcPageResult
-- 获得某一页的数据 --@currPage int = 1, --当前页页码 (即Top currPage)
@showColumn varchar(2000) = ‘*‘, --须要得到的字段 (即 column1,column2,......)
@strCondition varchar(2000) = ‘‘, --查询条件 (即 where condition......) 不用加wherekeyword
@ascColumn varchar(100) = ‘‘, --排序的字段名 (即 order by column asc/desc)
@bitOrderType bit = 0, --排序的类型 (0为升序,1为降序)
@pkColumn varchar(50) = ‘‘, --主键名称
@pageSize int = 20, --分页大小
@RecordCount int output --返回总行数
AS
BEGIN -- 存储过程開始
-- 该存储过程须要用到的几个变量 --
DECLARE @strTemp varchar(1000)
DECLARE @strSql varchar(4000) --该存储过程最后运行的语句
DECLARE @strSql01 varchar(4000)
DECLARE @strOrderType varchar(1000) --排序类型语句 (order by column asc或者order by column desc)
BEGIN
IF @bitOrderType = 1 -- bitOrderType=1即运行降序
BEGIN
SET @strOrderType = ‘ ORDER BY ‘+@ascColumn+‘ DESC‘
SET @strTemp = ‘<(SELECT min‘
END
ELSE
BEGIN
SET @strOrderType = ‘ ORDER BY ‘+@ascColumn+‘ ASC‘
SET @strTemp = ‘>(SELECT max‘
END
IF @currPage = 1 -- 假设是第一页
BEGIN
IF @strCondition != ‘‘
SET @strSql = ‘SELECT TOP ‘+STR(@pageSize)+‘ ‘+@showColumn+‘ FROM dbo.DemoData ‘+
‘ WHERE ‘+@strCondition+@strOrderType
ELSE
SET @strSql = ‘SELECT TOP ‘+STR(@pageSize)+‘ ‘+@showColumn+‘ FROM dbo.DemoData ‘+@strOrderType
END
ELSE -- 其它页
BEGIN
IF @strCondition !=‘‘
SET @strSql = ‘SELECT TOP ‘+STR(@pageSize)+‘ ‘+@showColumn+‘ FROM dbo.DemoData ‘+
‘ WHERE ‘+@strCondition+‘ AND ‘+@pkColumn+@strTemp+‘(‘+@pkColumn+‘)‘+‘ FROM (SELECT TOP ‘+STR((@currPage-1)*@pageSize)+
‘ ‘+@pkColumn+‘ FROM dbo.DemoData ‘+@strOrderType+‘) AS TabTemp)‘+@strOrderType
ELSE
SET @strSql = ‘SELECT TOP ‘+STR(@pageSize)+‘ ‘+@showColumn+‘ FROM dbo.DemoData ‘+
‘ WHERE ‘+@pkColumn+@strTemp+‘(‘+@pkColumn+‘)‘+‘ FROM (SELECT TOP ‘+STR((@currPage-1)*@pageSize)+‘ ‘+@pkColumn+
‘ FROM dbo.DemoData ‘+@strOrderType+‘) AS TabTemp)‘+@strOrderType
END
END
select @RecordCount=COUNT(*) from dbo.DemoData
EXEC (@strSql)END -- 存储过程结束
------------------------------------------------
GO
【调用方式】
DECLARE @RecordCount int
exec prcPageResult 1,‘*‘,‘‘,‘id‘,1,‘id‘,10,@RecordCount out
SELECT @RecordCount
---
DECLARE @RecordCount int
exec prcPageResult 1,‘*‘,‘name=‘‘hugh‘‘‘,‘id‘,0,‘id‘,10,@RecordCount out
--存储过程中转义字符为‘。所以name=’hugh‘正确的写法应该是‘name=‘‘hugh‘‘‘而不是‘name=/‘hugh/‘‘
SELECT @RecordCount
以上是关于SQLServer分页查询存储过程的主要内容,如果未能解决你的问题,请参考以下文章
SQL 分页查询存储过程中order by 后面不能传变量的问题怎么解决
使用Oracle的rownum或者存储过程分页的详细例子(jsp)~新手