sql 存儲(chǔ)過程分頁(yè)代碼 支持億萬(wàn)龐大數(shù)據(jù)量
發(fā)布日期:2022-01-24 10:59 | 文章來源:CSDN
復(fù)制代碼 代碼如下:
CREATE PROCEDURE page
@tblName varchar(255), -- 表名
@strGetFields varchar(1000) = '*', -- 需要返回的列
@fldName varchar(255)='id', -- 排序的字段名
@PageSize int = 10, -- 頁(yè)尺寸
@PageIndex int = 1, -- 頁(yè)碼
@doCount bit = 0, -- 返回記錄總數(shù), 非 0 值則返回
@OrderType bit = 0, -- 設(shè)置排序類型, 非 0 值則降序 0:asc 1:desc
@strWhere varchar(1500) = '', -- 查詢條件 (注意: 不要加 where)
@ID nvarchar(50)='id' --主表的列。。最好是主鍵
AS
declare @strSQL varchar(5000) -- 主語(yǔ)句
declare @strTmp varchar(110) -- 臨時(shí)變量
declare @strOrder varchar(400) -- 排序類
if @doCount != 0 begin
if @strWhere !=''
set @strSQL = 'select count(*) as Total from ' + @tblName+ ' where '+@strWhere
else
set @strSQL = 'select count(*) as Total from ' + @tblName + ''
end
--以上代碼的意思是如果@doCount傳遞過來的不是0,就執(zhí)行總數(shù)統(tǒng)計(jì)。以下的所有代碼都是@doCount為0的情況
else begin
if @OrderType != 0 begin
set @strTmp = '<(select min'
set @strOrder = ' order by ' + @fldName +' desc'
--如果@OrderType不是0,就執(zhí)行降序,這句很重要!
end
else begin
set @strTmp = '>(select max'
set @strOrder = ' order by ' + @fldName +' asc'
end
if @PageIndex = 1 begin
if @strWhere != ''
set @strSQL = 'select top ' + str(@PageSize) +' '+@strGetFields+ ' from ' + @tblName + ' where ' + @strWhere + ' ' + @strOrder
else
set @strSQL = 'select top ' + str(@PageSize) +' '+@strGetFields+ ' from '+ @tblName + ' '+ @strOrder
--如果是第一頁(yè)就執(zhí)行以上代碼,這樣會(huì)加快執(zhí)行速度
end
else begin
--以下代碼賦予了@strSQL以真正執(zhí)行的SQL代碼
set @strSQL = 'select top ' + str(@PageSize) +' '+@strGetFields+ ' from '
+ @tblName + ' where ' + @fldName + ' ' + @strTmp + '( '+ @ID + ' ) from (select top ' + str((@PageIndex-1)*@PageSize) + ' '+ @fldName + ' from ' + @tblName + @strOrder + ') as tblTmp)'+ @strOrder
if @strWhere != ''
set @strSQL = 'select top ' + str(@PageSize) +' '+@strGetFields+ ' from '
+ @tblName + ' where ' + @fldName + ' ' + @strTmp + '('
+ @ID + ') from (select top ' + str((@PageIndex-1)*@PageSize) + ' '
+ @fldName + ' from ' + @tblName + ' where ' + @strWhere + ' '
+ @strOrder + ') as tblTmp) and ' + @strWhere + ' ' + @strOrder
end
end
exec (@strSQL)
版權(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處理。
相關(guān)文章