mysql通用儲存過程分頁

2021-08-11 11:25:37 字數 3493 閱讀 7401

/*

完成乙個通用的儲存過程分頁

1.當前頁碼

1必填

2.每頁大小

5必填

3.任意表

'employee'

必填

4.任意的查詢列

'num,name,tel,depno' 可選

5.任意查詢條件

'depno=1'

可選

6.任意的排序列

'birth'

可選

7.任意的排序型別(

asc/desc

) 'asc'

可選

8.總記錄數

9.總頁數

*/

create procedure sp_paging

(

currentpage int,

pagesize int,

tname varchar(64),

selections varchar(2000),

conditions varchar(2000),

sortcolumn varchar(64),

sortorder

char(4),

out totalnum int,

out totalpage int

)

begin

#臨時變數,標記開始查詢位置

declare vstart int default 0;

#設定查詢的起始位置

set vstart = (currentpage - 1) * pagesize;

#判斷是否填寫查詢列,若未填寫則預設使用

*

if selections is null or selections = '' then

set

selections = '*';

end if;

#判斷是否填寫查詢條件

if conditions is null or conditions = '' then

set conditions = '1=1';

end if;

#判斷是否填寫排序列,若未填寫則使用預設的排序列『

_id』(需要事先約定好)

if sortcolumn is null or sortcolumn = '' then

set sortcolumn = '_id';

end if;

#判斷是否給定正確的排序方式,如未給定或者不符合要求,則預設使用

asc(公升序)

if lower(sortorder) != 'asc' and lower(sortorder) != 'desc' then

set sortorder = 'asc';

end if;

#select * from employee where depno>1 order by birth desc limit 0,5;

set @vsql = concat('select ',

selections,

' from ',

tname,

' where ',

conditions,

' order by ',sortcolumn,' ',sortorder,

' limit ',vstart,',',pagesize);

#對

sql語句預編譯

prepare stmt from @vsql;

execute stmt;

deallocate prepare stmt;

#總記錄數

set @vsql = concat('select count(*) into @tnum from ',tname,' where ',conditions);

prepare stmt from @vsql;

execute stmt;

set totalnum = @tnum;

#將臨時變數中的資料賦值給輸出引數

set totalpage = ceiling(totalnum/pagesize);

deallocate prepare stmt;

end;

call sp_paging(1,2,'department',null,null,'depno','desc',@tn,@tp);

select @tp,@tn;

MySQL通用的分頁儲存過程

分頁的顯示效果 1 5 條資料 實現 delimiter create procedure t204.a column varchar 10 查詢的列名 table varchar 10 查詢的表名 pageindex int,查詢的頁碼數 linenumber int 查詢的行數 begin se...

MySQL通用的分頁儲存過程

效果圖 procedure t204 曾傑 zz in myr int begin set myr concat select from person limit myr 1 5 5,prepare m from myr execute m end delimiter call zz 2 註解 1....

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

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