一个不错的分页储存过程(支持时间排序)

CREATE procedure p_show2
(
@select_list varchar(1000)='*',--不需要select
@table_name varchar(100),
@where varchar(1000)='',--不需要where
@primary_key varchar(100),--当是表联合时,加表名前缀.
@order_by varchar(200),--需要完整的子句 order by ...
@page_size smallint=20,--每页记录
@page_index int=1,--页索引
@do_count bit=0,
@iPageCount int = 1 OUTPUT,  --总的记录数
@pageCount    int = 1 output  ----查询结果分页后的总页数
)--1只统计总数
as
/*
过程名:通用存储过程分页
使用示例:
单表sql调用:exec select_pagesize 'login_id,login_name','tb_login',' login_name like ''%%''','login_id',' order by login_dt desc',20,10
多表sql调用:exec select_pagesize 'a.login_id,a.login_name,b.pro_name','tb_login a,tb_code_province b',' a.pro_id=b.pro_id and a.login_name like ''%%''','a.login_id',' order by a.login_dt desc',20,10
备注:外部程序调用不需要转义单引号
原型结构:select top 20 select_list
  from tablename
  where z_id not in(select z_id from (select top 100 z_id from tablename order by order_by) temptable)
      and ...
  order by order_by

*/
declare @strTmp nvarchar(4000)
declare @QueryStr nvarchar(4000)

set @QueryStr='select * from '+@table_name+' where '+@where
print(@QueryStr)
set @strTmp='select @iPageCount=count(*) from '+@table_name+' where '+@where
----取得查询结果总数量-----
--print(@strTmp)
exec sp_executesql @strTmp,N'@iPageCount int out ',@iPageCount out
--print(@backinfo)

declare @tmpCounts int
if @iPageCount = 0
begin
    set @pageCount = 0
end
else
begin
    set @tmpCounts = @iPageCount
    --取得分页总数
    set @pageCount=(@tmpCounts+@page_size-1)/@page_size
    --print(@pageCount)
end


declare @sql_str varchar(8000)
declare @record_min int
declare @new_where varchar(1000),@newin_where varchar(1000)
if @where=''--重新为梳理,此过程时性能的考虑,因此不使用 where 1=1 再追加条件。
begin
select @new_where=''
select @newin_where=''
end
else
begin
select @new_where=' and '+@where
select @newin_where=' where '+@where
end

if @do_count=1
select @sql_str='select count(*) from '+@table_name+@newin_where
else
if @page_index=1
if @where=''
select @sql_str='select top '+convert(varchar,@page_size)+ ' '+@select_list+' from '+@table_name+' '+@order_by
else
select @sql_str='select top '+convert(varchar,@page_size)+ ' '+@select_list+' from '+@table_name+' where '+@where+' '+@order_by
else
begin
select @record_min=(@page_index-1)*@page_size
select @sql_str='select top '+convert(varchar,@page_size)+' '+@select_list+' from '+@table_name+' where '+@primary_key+' not in (select '+stuff(@primary_key,1,charindex('.',@primary_key),'')
select @sql_str=@sql_str+' from (select top '+convert(varchar,@record_min)+' '+@primary_key+' from '+@table_name+@newin_where+' '+@order_by+') temptable0000)'
select @sql_str=@sql_str+@new_where+' '+@order_by
end
--print @sql_str
exec(@sql_str)
GO
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值