当前位置: 移动技术网 > IT编程>数据库>MSSQL > SQL Server存储过程同时返回分页结果集和总数

SQL Server存储过程同时返回分页结果集和总数

2017年12月08日  | 移动技术网IT编程  | 我要评论

flash成人色情视频网,徐熙康,777带头大哥

前言

      好长时间没摸数据库了,周末在家写了个报表的存储过程,一时间对使用存储过程实现分页的同时并计算出记录总数不知道怎么更好的去实现。按照我们正常的业务逻辑,存储过程数据首先是分页,其次接受若干查询条件,返回分页结果集的同时还需要返回记录总数给客户端。

      我对于这样一个业务存储过程总结如下:1、内核层,通常也就是要查询的字段或者要计算的字段,这部分单独拿出来。  2、查询条件层。 如果内核只是查询一些字段的话,条件可以放在查询条件层拼接。 如果内核层完全是统计业务逻辑,那么查询条件则必须要放在内核层,像我们常用的sum、groupby 业务。 3、添加分页参数(也就是我们现在多数用的row_number添加rn参数)。   存储过程里我们一般会单独声明每个部分的变量用于执行时拼接。

存储过程

create proc [dbo].[usp_manyidu]
(
 @seatno nvarchar(30),
 @pageindex int,
 @pagesize int,
 @rscount int out
)
as
begin
 declare @sql nvarchar(max)  --拼接内核sql
 declare @where nvarchar(max)=' where 1=1' --查询条件拼接字符串
 declare @cols nvarchar(max)  --查询字段、计算字段
 declare @sort nvarchar(50)  --排序
  
 set @sql=' from dbo.log where seatno is not null and seatno<>'''' group by seatno '
 set @cols='seatno,sum(case when manyidu=0 then 1 else 0 end) as manyi,
      sum(case when manyidu=1 then 1 else 0 end) as yiban,
      sum(case when manyidu=2 then 1 else 0 end) as bumanyi,
      sum(case when manyidu is null or manyidu='''' then 1 else 0 end) as weipingjia'
  
 set @sort='order by seatno'
  
 if(@seatno <>'')
  set @where+=' and seatno='+@seatno
   
  
 declare @strsql nvarchar(max)
  
 set @strsql=n'select * from (select row_number() over('+@sort+') as tmpid,* from( select * from (select '+@cols+@sql+') as tmptable1'+@where+') as tmptable2) as tmptable3'
    +' where tmpid between '+str((@pageindex-1)*@pagesize+1)+' and '+str(@pageindex*@pagesize)
 print @strsql
 exec(@strsql) 
  
 set @strsql='select @total=count(*) from (select '+@cols+@sql+') as tmptable'+@where
  
 print @strsql
 exec sp_executesql @strsql,n'@total int out',@total=@rscount out
  
   
end
go

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网