SQL Server存儲(chǔ)過程同時(shí)返回分頁結(jié)果集和總數(shù)
好長(zhǎng)時(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
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持本站。
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。