Search code examples
oracleloopsplsqlcursor

previous row oracle in cursor


I'm here because i could not finde anywhere else if there is a way to return the previous value in a loop (Cursor) to compare with the current value, for instance..

Cursor.Value = Cursor-1.Value;

It's bacause i have several contract numbers that i need to send by mail to the Business sector, but, in order to resume all the rows i want to compare if the current contract number are the same as the last contract number and validate it to dont send duplicated contract numbers.

Exemple of Record that i to skip in order to send no duplicate "Order Numbers": (Order_Number is my Key, not a sequencial numeric id):

cCursor.Value = cCursor-1.Value

cCursor.(111) = cCursor-1.(111)

Exemple of Record that i want to save in order to send as a processed "Order Number": (Order_Number is my Key, not a sequencial numeric id):

cCursor.Value = cCursor-1.Value

cCursor.(132) = cCursor-1.(111)

My Regards.


Solution

  • You cant reference backwards. Th easiest alternative is to store the key value (contract_id) in a variable and have logic like:

    DECLARE
       CURSOR c1 IS .....;
       vLastContractID  NUMBER := 0;
    BEGIN
       FOR r1 IN c1 LOOP
          IF vLastContractID != r1.CONTRACT_ID THEN
             -- do something
             vLastContractID := r1.CONTRACT_ID;
          END IF;
       END LOOP;
    END;