温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》
  • 首页 > 
  • 教程 > 
  • 数据库 > 
  • SQL Server存储过程中怎么同时返回分页结果集和总数

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

发布时间:2021-08-05 14:43:13 来源:亿速云 阅读:365 作者:Leah 栏目:数据库

这期内容当中小编将会给大家带来有关SQL Server存储过程中怎么同时返回分页结果集和总数,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

1、内核层,通常也就是要查询的字段或者要计算的字段,这部分单独拿出来。

 2、查询条件层。 如果内核只是查询一些字段的话,条件可以放在查询条件层拼接。 如果内核层完全是统计业务逻辑,那么查询条件则必须要放在内核层,像我们常用的SUM、GROUPBY 业务。 

3、添加分页参数(也就是我们现在多数用的ROW_NUMBER添加rn参数)。 存储过程里我们一般会单独声明每个部分的变量用于执行时拼接。

存储过程

CREATE proc [dbo].[usp_manyidu]( @seatno nvarchar(30), @pageIndex int, @pageSize int, @rsCount int out)asbegin 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     endGO

上述就是小编为大家分享的SQL Server存储过程中怎么同时返回分页结果集和总数了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI