📄 pagingpro.txt
字号:
/*
此存储过程是通用分页,只能针对有ID列使用,否则请使用top分页或TempTable方式.
如觉行此过程性能不好,希望您能优化一下,再发一份给我,谢谢!
*/
CREATE PROCEDURE [dbo].[p_Table_Max_Paging]
--MAX和MIN通用分页,需要以ID来排序,排序参数不能为其它的,也就是说不能改变order by id asc的id
@tableName varchar(50), --表名
@field varchar(255)=' * ',
@pageSize int=10, --每页分页数
@paging int=1, --当前分页码
@where varchar(255)='', --加where的条件
@maxID varchar(50)='id', --加在order by 后的排序参数, 一定要是max统计字段,否则不能分页
@order varchar(4)='asc', --排序方法
@tableCount int=0 output, --输出表总数
@pageCount int=0 output --总分出多少页
AS
declare @sql nvarchar(1000)
declare @countNum int
declare @param nvarchar(255)
--得到表总数
select @sql='select @countNum=count(*) from '+@tableName+' '+@where
select @param=N'@countNum int output'
execute sp_executesql @sql,@param,@countNum output
set nocount on
declare @sorting varchar(4),@pageNum int
--相反的排序,默认值
select @pageNum=@countNum/@pageSize
select @sorting='desc'
--算出分页数
if (@countNum%@pageSize)>0
select @pageNum=@pageNum+1
select @tableCount=@countNum
select @pageCount=@pageNum
--生成SQL语句,要加cast转换函数转换成字符
if @paging<=1 or @pageNum=1 --首页
begin
select @sql='select top '+str(@pageSize)+' '+@field+' from '+@tableName+' '+@where+' order by '+@maxID+' '+@order
end
else if @paging>=@pageNum --尾页
begin
--非默认时,相反的方式
if @order='desc'
select @sorting='asc'
select @pageSize=@countNum-(@pageNum-1)*@pageSize
select @sql='select * from (select top '+str(@pageSize)+' '+@field+' from '+@tableName+' '+@where+' order by '+@maxID+' '+@sorting+') as table_a order by '+@maxID+' '+@order
end
else
begin
declare @topNum varchar(100),@inputWhere varchar(100)
select @topNum=str((@paging-1)*@pageSize)
if @where<>''
set @inputWhere=@where+' and '
else
set @inputWhere=' where '
if @order='asc' --顺排非首页和尾页
select @sql='select top '+str(@pageSize)+' '+@field+' from '+@tableName+' '+@inputWhere+@maxID+'>
(select max('+@maxID+') as '+@maxID+' from
(select top '+@topNum+' '+@maxID+' from '+@tableName+' '+@where+' order by '+@maxID+' asc) as a) order by '+@maxID+' asc'
else --倒排非首页和尾页
select @sql='select top '+str(@pageSize)+' '+@field+' from '+@tableName+' '+@inputWhere+@maxID+'<
(select min('+@maxID+') as '+@maxID+' from
(select top '+@topNum+' '+@maxID+' from '+@tableName+' '+@where+' order by '+@maxID+' desc) as a) order by '+@maxID+' desc'
end
--注意加括号
exec(@sql)
GO
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -