您好,登錄后才能下訂單哦!
這期內(nèi)容當(dāng)中小編將會給大家?guī)碛嘘P(guān)SQL Server存儲過程中怎么同時返回分頁結(jié)果集和總數(shù),文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
1、內(nèi)核層,通常也就是要查詢的字段或者要計算的字段,這部分單獨(dú)拿出來。
2、查詢條件層。 如果內(nèi)核只是查詢一些字段的話,條件可以放在查詢條件層拼接。 如果內(nèi)核層完全是統(tǒng)計業(yè)務(wù)邏輯,那么查詢條件則必須要放在內(nèi)核層,像我們常用的SUM、GROUPBY 業(yè)務(wù)。
3、添加分頁參數(shù)(也就是我們現(xiàn)在多數(shù)用的ROW_NUMBER添加rn參數(shù))。 存儲過程里我們一般會單獨(dú)聲明每個部分的變量用于執(zhí)行時拼接。
存儲過程
CREATE proc [dbo].[usp_manyidu]( @seatno nvarchar(30), @pageIndex int, @pageSize int, @rsCount int out)asbegin declare @sql nvarchar(max) --拼接內(nèi)核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存儲過程中怎么同時返回分頁結(jié)果集和總數(shù)了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。