通用分頁儲存過程 sqlserver

2021-09-05 16:40:13 字數 2361 閱讀 6461

-- 獲取指定頁的資料

create procedure sppagination

@tblname varchar(255), -- 表名

@strgetfields varchar(1000) = '*', -- 需要返回的列

@fldname varchar(255)='', -- 排序的欄位名

@pagesize int = 10, -- 頁尺寸

@pageindex int = 1, -- 頁碼

@docount bit = 0, -- 返回記錄總數, 非 0 值則返回

@ordertype bit = 0, -- 設定排序型別, 非 0 值則降序

@strwhere varchar(1500) = '' -- 查詢條件 (注意: 不要加 where)

asdeclare @strsql varchar(5000) -- 主語句

declare @strtmp varchar(110) -- 臨時變數

declare @strorder varchar(400) -- 排序型別

if @docount != 0

begin

if @strwhere !=''

set @strsql = "select count(*) as total from [" + @tblname + "] where "

else

set @strsql = "select count(*) as total from [" + @tblname + "]"

end--以上**的意思是如果@docount傳遞過來的不是0,就執行總數統計。以下的所有**都是@docount為0的情況

else

begin

if @ordertype != 0

begin

set @strtmp = "<(select min"

set @strorder = " order by [" + @fldname +"] desc"

--如果@ordertype不是0,就執行降序,這句很重要!

endelse

begin

set @strtmp = ">(select max"

set @strorder = " order by [" + @fldname +"] asc"

endif @pageindex = 1

begin

if @strwhere != ''

set @strsql = "select top " + str(@pagesize) +" "+ " from [" + @tblname + "] where " + @strwhere + " " + @strorder

else

set @strsql = "select top " + str(@pagesize) +" "+ " from ["+ @tblname + "] "+ @strorder

--如果是第一頁就執行以上**,這樣會加快執行速度

endelse

begin

--以下**賦予了@strsql以真正執行的sql**

set @strsql = "select top " + str(@pagesize) +" "+ " from ["

+ @tblname + "] where [" + @fldname + "]" + @strtmp + "(["+ @fldname + "]) from (select top " + str((@pageindex-1)*@pagesize) + " ["+ @fldname + "] from [" + @tblname + "]" + @strorder + ") as tbltmp)"+ @strorder

if @strwhere != ''

set @strsql = "select top " + str(@pagesize) +" "+ " from ["

+ @tblname + "] where [" + @fldname + "]" + @strtmp + "(["

+ @fldname + "]) from (select top " + str((@pageindex-1)*@pagesize) + " ["

+ @fldname + "] from [" + @tblname + "] where " + @strwhere + " "

+ @strorder + ") as tbltmp) and " + @strwhere + " " + @strorder

endend

exec (@strsql)go

#**庫

通用儲存過程 分頁儲存過程

名稱 spall returnrows 輸入 輸出 呼叫 exec spall returnrows select from 表名 頁號,返回記錄數,主鍵 排序字段 spall returnrows select from all categories 2,10,id id 說明 百萬級 通用儲存過...

通用分頁儲存過程

create procedure sp page strtable varchar 50 表名 strcolumn varchar 50 按該列來進行分頁 intcoltype int,strcolumn列的型別,0 數字型別,1 字元型別,2 日期時間型別 intorder bit,排序,0 順序...

通用分頁儲存過程

set quoted identifier on goset ansi nulls off go declare p1 int set p1 null exec sp pageview tbname n v question list fieldkey n id pagecurrent 3,page...