MySQL 存儲過程中分頁
- 2019 年 10 月 4 日
- 筆記
MySQL資料庫中,自定義存儲過程查詢表中的數據,帶有分頁功能。具體實例如下程式碼:
1 DROP PROCEDURE IF EXISTS `sampledb`.`proc_GetPagedDataSet`; 2 3 CREATE DEFINER=`root`@`%` PROCEDURE `proc_GetPagedDataSet`( 4 IN tableName VARCHAR (20), /*表名 5 IN pageIndex INT, /*當前頁*/ 6 IN pageSize INT, /*每頁記錄數*/ 7 OUT pageCount INT,/*總記錄分頁數*/ 8 out totalRecordCount int /*總記錄數*/) 9 BEGIN 10 /*獲取表中的記錄數*/ 11 set @recordCount=0; 12 set @sql=''; 13 set @sql=CONCAT('select count(*) into @recordCount from ',tableName); 14 prepare stmt from @sql; /*預處理 自定義sql字元串*/ 15 execute stmt; /*執行自定義sql語句*/ 16 deallocate prepare stmt; /*釋放預處理資源*/ 17 18 set totalRecordCount = @recordCount; /*總記錄數*/ 19 20 /*計算返回多少頁*/ 21 set @tmp=1; 22 set @tmp=@recordCount mod pageSize; /*取餘數*/ 23 if @tmp=0 then 24 set pageCount=@recordCount div pageSize; 25 else 26 set pageCount=@recordCount div pageSize + 1; 27 end if; 28 29 /*分頁顯示數據*/ 30 set @sql=CONCAT('select * from ',tableName,' limit ',(pageIndex-1)*pageSize,',',pageSize); 31 prepare stmt from @sql; /*預處理 自定義sql字元串*/ 32 execute stmt;/*執行自定義sql語句*/ 33 deallocate prepare stmt; /*釋放預處理資源*/ 34 END =============================================================================================== MySQL大數據量分頁性能優化