欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SQL Server存儲(chǔ)過程同時(shí)返回分頁結(jié)果集和總數(shù)

 更新時(shí)間:2017年01月16日 15:50:09   作者:garfieldzf  
這篇文章主要為大家詳細(xì)介紹了SQL Server存儲(chǔ)過程同時(shí)返回分頁結(jié)果集和總數(shù),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

前言

      好長時(shí)間沒摸數(shù)據(jù)庫了,周末在家寫了個(gè)報(bào)表的存儲(chǔ)過程,一時(shí)間對(duì)使用存儲(chǔ)過程實(shí)現(xiàn)分頁的同時(shí)并計(jì)算出記錄總數(shù)不知道怎么更好的去實(shí)現(xiàn)。按照我們正常的業(yè)務(wù)邏輯,存儲(chǔ)過程數(shù)據(jù)首先是分頁,其次接受若干查詢條件,返回分頁結(jié)果集的同時(shí)還需要返回記錄總數(shù)給客戶端。

      我對(duì)于這樣一個(gè)業(yè)務(wù)存儲(chǔ)過程總結(jié)如下:1、內(nèi)核層,通常也就是要查詢的字段或者要計(jì)算的字段,這部分單獨(dú)拿出來。  2、查詢條件層。 如果內(nèi)核只是查詢一些字段的話,條件可以放在查詢條件層拼接。 如果內(nèi)核層完全是統(tǒng)計(jì)業(yè)務(wù)邏輯,那么查詢條件則必須要放在內(nèi)核層,像我們常用的SUM、GROUPBY 業(yè)務(wù)。 3、添加分頁參數(shù)(也就是我們現(xiàn)在多數(shù)用的ROW_NUMBER添加rn參數(shù))。   存儲(chǔ)過程里我們一般會(huì)單獨(dú)聲明每個(gè)部分的變量用于執(zhí)行時(shí)拼接。

存儲(chǔ)過程

CREATE proc [dbo].[usp_manyidu]
(
 @seatno nvarchar(30),
 @pageIndex int,
 @pageSize int,
 @rsCount int out
)
as
begin
 declare @sql nvarchar(max)  --拼接內(nèi)核SQL
 declare @where nvarchar(max)=' where 1=1' --查詢條件拼接字符串
 declare @cols nvarchar(max)  --查詢字段、計(jì)算字段
 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

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論