sql 分页存储过程

Posted 改变从今天开始

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql 分页存储过程相关的知识,希望对你有一定的参考价值。

ALTER procedure [dbo].[fenye]
@pagesize int, --每页显示数量
@pageCurrent int, --当前页
@tablename varchar(20), --表名
@field varchar(20), --显示的列名(eg: id,name)
@where varchar(20), --筛选条件 (eg: name not null)
@orderBy varchar(20), --排序的列名(eg: id 或者 id desc)
@count int output --返回总共有多少页,0 为不要返回 1 位

as
begin
declare @strSql nvarchar(200)
declare @starNum int
declare @endNum int
set @starNum =(@pageCurrent -1)* @pagesize
set @endNum [email protected] * @pagesize
--declare @timediff datetime

--set nocount on --不返回计数(表示受Transact-SQL 语句影响的行数)。
--select @timediff=getdate() --记录时间

if @count !=0
begin
if @where = ‘‘
set @strSql =‘select @count=count(*) from ‘[email protected]
else
set @strSql =‘select @count=count(*) from ‘[email protected]+‘ where ‘[email protected]
end
exec sp_executesql @strSql,N‘@count int output,@tablename varchar(20),@where varchar(20)‘,@count output,@tablename,@where


if @pageCurrent =1
if @where = ‘‘
set @strSql =‘select top ‘+cast(@pagesize as varchar)+‘ ‘[email protected]+‘ from ‘[email protected]+‘ order by ‘[email protected]+‘‘
else
set @strSql =‘select top ‘+cast(@pagesize as varchar)+‘ ‘[email protected]+‘ from ‘[email protected]+‘ where ‘[email protected]+‘ order by ‘[email protected]+‘‘
else
if @where !=‘‘
set @strSql=‘select ‘[email protected]+‘ from (select ‘[email protected]+‘,row_number() over(order by ‘[email protected]+‘) rn from ‘[email protected]+‘ where ‘[email protected]+‘)a where rn<=‘+CONVERT(varchar,@endNum)+‘ and rn>‘+cast(@starNum as varchar)+‘‘
else
set @strSql=‘select ‘[email protected]+‘ from (select ‘[email protected]+‘,row_number() over(order by ‘[email protected]+‘) rn from ‘[email protected]+‘)a where rn<=‘+CONVERT(varchar,@endNum)+‘ and rn>‘+cast(@starNum as varchar)+‘‘

exec(@strSql)

--select datediff(ms,@timediff,getdate()) as 耗时
--set nocount off --返回计数(默认为OFF)。
end

 

declare @count int
set @count=1
exec fenye 3,3,cj,‘*‘,‘fenshu is not null‘,‘id‘,@count output
select @count






































以上是关于sql 分页存储过程的主要内容,如果未能解决你的问题,请参考以下文章

SQL 分页查询存储过程中order by 后面不能传变量的问题怎么解决

sql server 分页存储过程

SQL存储过程分页(通用的拼接SQL语句思路实现)

Sql分页存储过程

SQL基础分页存储过程(案例一)

数据库sqlserver如何用存储过程做分页