分頁查詢儲存過程
/****** object: storedprocedure [dbo].[pagination3] script date: 2019/1/11 9:02:01 ******/
set ansi_nulls on
goset quoted_identifier on
goalter procedure [dbo].[pagination3] --新建儲存過程用:create procedure [dbo].[pagination3]
@tblname varchar(50), --表名
@strgetfields varchar(5000) = '*', --欄位名(全部欄位為*)
@fldname varchar(5000), --排序字段(必須!支援多欄位)
@strwhere varchar(5000) = null,--條件語句(不用加where)
@pagesize int, --每頁多少條記錄
@pageindex int = 1 , --指定當前為第幾頁
@ordertype bit=0, -- 設定排序型別, 非 0 值則降序
@docount bit = 0
asbegin
declare @sql nvarchar(4000)
--計算總記錄數
if @docount != 0
begin
if (@strwhere='' or @strwhere=null)
set @sql = 'select count(*) as total from [' + @tblname + ']'
else
set @sql = 'select count(*) as total from [' + @tblname + '] where '+@strwhere
end
else
begin
if (@strwhere='' or @strwhere=null)
if(@ordertype=1)
set @sql = 'select * from (select row_number() over(order by ' + @fldname + ' desc) as rowid,' + @strgetfields + ' from ' + @tblname
else
set @sql = 'select * from (select row_number() over(order by ' + @fldname + ' asc) as rowid,' + @strgetfields + ' from ' + @tblname
else
if(@ordertype=1)
set @sql = 'select * from (select row_number() over(order by ' + @fldname + ' desc) as rowid,' + @strgetfields + ' from ' + @tblname + ' where ' + @strwhere
else
set @sql = 'select * from (select row_number() over(order by ' + @fldname + ' asc) as rowid,' + @strgetfields + ' from ' + @tblname + ' where ' + @strwhere
--處理開始點和結束點
declare @startrecord int
declare @endrecord int
set @startrecord = (@pageindex-1)*@pagesize + 1
set @endrecord = @startrecord + @pagesize - 1
--繼續合成sql語句
if(@ordertype=1)
set @sql = @sql + ') as ' + @tblname + ' where rowid between ' + convert(varchar(50),@startrecord) + ' and ' + convert(varchar(50),@endrecord) + 'order by '+@fldname+' desc'
else
set @sql = @sql + ') as ' + @tblname + ' where rowid between ' + convert(varchar(50),@startrecord) + ' and ' + convert(varchar(50),@endrecord) + 'order by '+@fldname+' asc'
endendexec(@sql)
儲存過程實現分頁查詢
以學生資訊表為例 一 建立分頁儲存過程 create proc proc findstudentsplitpage 宣告引數 pagesize int,每頁記錄數 輸入引數 curpage int,當前是第幾頁 輸入引數 totalpage int out,總頁數 輸出引數 totalcount i...
分頁查詢的儲存過程
建立有識別符號列的table變數 declare t table table rownum int identity 1,1 primary key not null author last name varchar 40 author first name varchar 20 phone cha...
多表查詢分頁儲存過程
set ansi nulls on set quoted identifier on go 支援多表查詢分頁儲存過程 事理改進 2012.3 多表聯查1 declare count int exec proc datapagination sl article a,sl user u u.realn...