公用分頁存儲過程

忙了一上午,現在終於能停下手來。今天整理下桌面腳本,看到之前自己所編寫過的公用分頁存儲過程,小弟在此獻醜。在此之前有發佈過一篇高效ms sql分頁存儲過程解釋如何讓分頁腳本提高執行性能。

共有兩個分頁存儲過程:查詢字段在單表中,查詢字段分佈在多表;


--查詢字段在單表中
--公用分頁存儲過程
alter procedure [dbo].[Erp_Common_PageList]
@pageIndex int,--頁索引
@pageSize int,--每頁顯示條數
@count int,--總數
@id varchar(40),--主表主鍵
@tabel varchar(35),--主表名
@sortparam varchar(50),--排序
@selectParam nvarchar(2000),--查詢字段字符串
@condition nvarchar(4000),--篩選條件
@relation nvarchar(4000)--關聯表
as
declare @sql nvarchar(4000),@min int,@max int
set @min=(@pageIndex-1)*@pageSize+1
set @max=@pageIndex*@pageSize
set @sql='if @count=0 begin
    set @count=(select count('+@id+') from '+@tabel+' WITH (NOLOCK) '+@condition+')
end
select '+@selectParam+',@count as num from '+@tabel+@relation+' where '+@id+' in (select top '+
cast(@pageSize as varchar(5))+' '+@id+' from (select '+@id+',ROW_NUMBER() OVER (ORDER BY '+@sortparam+')
AS RowNumber from '+@tabel+' WITH (NOLOCK) '+@condition+') as lind where RowNumber between @min and @max)'
EXECUTE sp_executesql @sql,N'@count int,@min int,@max int',@count,@min,@max
GO

--查詢字段分佈在多表
--綜合公用分頁存儲過程
alter procedure [dbo].[Erp_Common_PageList_TemTableByRelation]
@pageIndex int,--頁索引
@pageSize int,--每頁顯示條數
@count int,--總數
@id varchar(40),--主表主鍵
@sortparam varchar(50),--排序
@selectParam nvarchar(2000),--查詢字段
@condition nvarchar(2000),--查詢條件
@temTable nvarchar(3000),--臨時表字符串
@dropTable varchar(300),--刪除臨時表字符串
@relation varchar(2000),--關聯表
@insrtParam varchar(100),--插入到統計總量臨時表的字段
@param varchar(100)--插入到頁顯示的臨時表字段
as
declare @sql nvarchar(4000),@min int,@max int,@date varchar(15),@tem1 varchar(20),@tem2 varchar(20),@part2 nvarchar(4000)
set @date=replace(CONVERT(varchar,getdate(),114),':','')
set @tem1='#page1'+@date
set @tem2='#page2'+@date
set @min=(@pageIndex-1)*@pageSize+1
set @max=@pageIndex*@pageSize
set @sql='
select '+@id+' as spkid'+@insrtParam+',ROW_NUMBER() OVER (ORDER BY '+@sortparam+') AS RowNumber into '+@tem1+' from '+@condition+'
select spkid,RowNumber'+@param+' into '+@tem2+' from '+@tem1+' where RowNumber between '+CAST(@min as varchar(11))+' and '+
CAST(@max as varchar(11))
if @count=0 begin
    set @part2='declare @count int
        set @count=(select max(RowNumber) from '+@tem1+')
        if @count is null set @count=0
        select  '+@selectParam+',@count as num'
end else begin
    set @part2='select  '+@selectParam+','+CAST(@count as varchar(11))+' as num'
end
set @part2=@part2+',RowNumber from '+@tem2+' as pt join '+@relation+' order by pt.RowNumber
truncate table '+@tem1+'
truncate table '+@tem2+'
drop table '+@tem1+'
drop table '+@tem2+'
'+@dropTable
--關閉影響行數
exec('set nocount on
'+@temTable+@sql+@part2+'
set nocount off')
--打開影響行數
GO

下載地址:高效公用分頁存儲過程  

提供源碼及示例



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章