2010-05-14 135 views
1

我的問題很簡短。我創建一個遊標來從我的表中獲取一些值。我想獲取遊標的當前記錄(獲取的記錄)和遊標中的下一條記錄,而不用提取它,因爲我想對當前記錄和下一條記錄進行計算。在傳統的編程中這是一個簡單的操作;你可以通過增加1來做到索引。從PLSQL光標獲取兩條記錄

你有什麼建議嗎?

+0

這是PostgreSQL的PL/SQL還是Oracle的PLSQL? – Earlz 2010-05-14 18:02:56

回答

1

我不知道你能做到這一點不移動光標,但你應該能夠完成這樣的(僞代碼)相同的目標:

open cursor; 
fetch cursor to rec1; 
if cursor%found then 
    loop  
     fetch cursor to rec2; 
     exit when cursor%notfound; 
     perform calculations with rec1 and rec2; 
     rec1 := rec2; 
    end loop; 
end if; 
6

我想在做一個計算 當前記錄和下一條記錄。

假設您使用的是Oracle,這可以在SQL中使用分析函數,特別是lead()函數完成。這將從下一個第n條記錄中檢索列值(默認n = 1)。

SQL> select empno 
    2   , sal as this_sal 
    3   , lead(sal) over (order by empno) as next_sal 
    4 from emp 
    5 order by empno 
    6/

    EMPNO THIS_SAL NEXT_SAL 
---------- ---------- ---------- 
     7369  800  1600 
     7499  1600  1250 
     7521  1250  2975 
     7566  2975  1250 
     7654  1250  2850 
     7698  2850  2450 
.... 

此查詢可以在遊標或任何其他機制中用於檢索記錄。

0

要回答您的具體問題,您可以將BULK COLLECT及其限制條款用於集合(表格)變量。

DECLARE 
    CURSOR my_cursor IS 
    [YOUR SQL HERE]; 

    TYPE t_my_type IS TABLE OF my_cursor%ROWTYPE INDEX BY BINARY_INTEGER; 
    v_my_var t_my_type; 
BEGIN 
    FETCH my_cursor BULK COLLECT INTO v_my_var LIMIT 2; 
    dbms_output.put_line('My first value: ' || v_my_var(1).some_column); 
    dbms_output.put_line('My second value: ' || v_my_var(2).some_column); 
END; 

的限制條款將導致只有前兩個記錄被獲取並存儲。第一條記錄將有1的指數,第二個是2

0

可以通過保存一個到當地比較兩個變量,然後將它與光標值進行比較,例如

declare 
l_local1 table_name%type := null; 

begin 

for c1 in (select 
      * 
      from 
      table_name 
      where some clause) 
loop 
-- do comparation 
    if l_local1 is not null and c1.field_value is not null then 
    -- do something to compare 
    . 
    . 
    . 
    -- empty local1 variable 
    l_local1 := null; 
    end if; 
    -- get the value of loop in local variable 
    l_local1 := c1.field_value; 
end loop; 

end;