首页 > 代码库 > sql 分页存储过程

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 =@pageCurrent * @pagesize
--declare @timediff datetime

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

if @count !=0
begin
if @where = ‘‘
set @strSql =‘select @count=count(*) from ‘+@tablename
else
set @strSql =‘select @count=count(*) from ‘+@tablename+‘ where ‘+@where
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)+‘ ‘+@field+‘ from ‘+@tablename+‘ order by ‘+@orderBy+‘‘
else
set @strSql =‘select top ‘+cast(@pagesize as varchar)+‘ ‘+@field+‘ from ‘+@tablename+‘ where ‘+@where+‘ order by ‘+@orderBy+‘‘
else
if @where !=‘‘
set @strSql=‘select ‘+@field+‘ from (select ‘+@field+‘,row_number() over(order by ‘+@orderBy+‘) rn from ‘+@tablename+‘ where ‘+@where+‘)a where rn<=‘+CONVERT(varchar,@endNum)+‘ and rn>‘+cast(@starNum as varchar)+‘‘
else
set @strSql=‘select ‘+@field+‘ from (select ‘+@field+‘,row_number() over(order by ‘+@orderBy+‘) rn from ‘+@tablename+‘)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 分页存储过程