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

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

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

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

存储过程

CREATEproc[dbo].[usp_manyidu](@seatnonvarchar(30),@pageIndexint,@pageSizeint,@rsCountintout)asbegindeclare@sqlnvarchar(max)--拼接内核SQLdeclare@wherenvarchar(max)='where1=1'--查询条件拼接字符串declare@colsnvarchar(max)--查询字段、计算字段declare@sortnvarchar(50)--排序set@sql='fromdbo.logwhereseatnoisnotnullandseatno<>''''groupbyseatno'set@cols='seatno,SUM(casewhenmanyidu=0then1else0end)asmanyi,SUM(casewhenmanyidu=1then1else0end)asyiban,SUM(casewhenmanyidu=2then1else0end)asbumanyi,SUM(casewhenmanyiduISnullormanyidu=''''then1else0end)asweipingjia'set@sort='orderbyseatno'if(@seatno<>'')set@where+='andseatno='+@seatnodeclare@strSQLnvarchar(max)set@strSQL=N'select*from(selectROW_NUMBER()over('+@sort+')astmpid,*from(select*from(select'+@cols+@sql+')astmpTable1'+@where+')astmpTable2)astmpTable3'+'wheretmpidbetween'+STR((@pageIndex-1)*@pageSize+1)+'and'+STR(@pageIndex*@pageSize)print@strSQLexec(@strSQL)set@strSQL='select@total=count(*)from(select'+@cols+@sql+')astmpTable'+@whereprint@strSQLexecsp_executesql@strSQL,N'@totalintout',@total=@rsCountoutendGO

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