使用游標編寫的儲存過程進行分頁

2021-03-31 08:56:31 字數 954 閱讀 6605

思路:採用遊標定位於所需頁面的每一條記錄的位置,再迴圈獲取此頁面的其它記錄。

--pageindex 為所要獲取的頁面的索引號,pagesize為每頁顯示的記錄數

create procedure fetchpage(@pageindex **allint,@pagesize **allint)

asdeclare @index **allint

declare @firstrecord **allint

--設定要獲取的頁面的第一條記錄位置

set @firstrecord=(@pageindex-1)*@pagesize+1

--關聯游標

declare customer_cursor scroll cursor for

select customerid,***panyname,contactname,address from customers order by ***panyname

open customer_cursor

fetch absolute @firstrecord from customer_cursor

--迴圈獲取剩餘記錄

set @index =1

while @@fetch_status=0 and @index<@pagesize begin

fetch next from customer_cursor

set @index=@index+1

endclose customer_cursor

deallocate customer_cursor

使用游標的好處是可以跳到想要獲取頁面的第一條記錄並提取需要的記錄,缺點是會同時返回多個記錄集,而每個記錄集卻只包含一條

需要的記錄。

解決方案:可以採用dateset 或datareader 來處理每個記錄集,將所有記錄集新增到乙個新的資料容器裡

至於儲存過程在程式中的呼叫就不說了

Mysql 儲存過程使用游標

完整例子 create procedure test begin 定義引數 declare id int 定義游標 declare no more products int default 0 declare result test cursor for select num1 from numte...

mysql 使用游標進行刪除操作的儲存過程

begin declare hprocessinstanceid bigint default 0 歷史流程例項id declare hprocessinstanceidstarttime char default 歷史流程例項啟動時間 declare hprocessinstanceidendti...

mysql 使用游標進行刪除操作的儲存過程

begin declare hprocessinstanceid bigint default 0 歷史流程例項id declare hprocessinstanceidstarttime char default 歷史流程例項啟動時間 declare hprocessinstanceidendti...