標籤:style blog ar color sp 資料 on div 2014
2014-11-20
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 BEGIN10 /*擷取表中的記錄數*/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 then24 set pageCount=@recordCount div pageSize;25 else26 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 預存程序中分頁