📜  PL SQL cursor(1)

📅  最后修改于: 2023-12-03 15:33:42.630000             🧑  作者: Mango

PL/SQL Cursor

A cursor is a structure in PL/SQL that enables the traversal of the records in a result set. Cursors are used to manipulate the data in a row-by-row basis.

Creating a Cursor

Here's an example of how to create a cursor:

DECLARE
  CURSOR department_cursor IS
    SELECT department_name, location
    FROM departments
    WHERE location = 'London';
BEGIN
  -- Some code here
END;

Note that we can use a SELECT statement to specify the records that the cursor will traverse.

Opening and Fetching from a Cursor

Here's how you can open and fetch records from a cursor:

DECLARE
  CURSOR department_cursor IS
    SELECT department_name, location
    FROM departments
    WHERE location = 'London';
BEGIN
  OPEN department_cursor;
  LOOP
    FETCH department_cursor INTO var_department_name, var_location;
    EXIT WHEN department_cursor%NOTFOUND;
    -- Some code here
  END LOOP;
  CLOSE department_cursor;
END;

In this example, we first opened the cursor using the OPEN statement. Then, we looped through the records using the FETCH statement, which assigns the values of the retrieved fields to specified variables. When the cursor has reached the end of the results set, the %NOTFOUND attribute will be set to TRUE and the loop will stop. Finally, we close the cursor using the CLOSE statement.

Cursor Attributes

Below are some useful attributes of PL/SQL cursors:

  • %FOUND - returns TRUE if the last FETCH statement has retrieved a record. Otherwise, it returns FALSE.
  • %NOTFOUND - returns TRUE if the last FETCH statement has not retrieved a record. Otherwise, it returns FALSE.
  • %ROWCOUNT - returns the number of rows that have been retrieved by the cursor.
  • %ISOPEN - returns TRUE if the cursor is currently open. Otherwise, it returns FALSE.
Cursor Parameters

It is possible to pass parameters to a cursor using the cursor's SELECT statement. Here's an example:

DECLARE
  CURSOR employee_cursor (p_department_id departments.department_id%TYPE) IS
    SELECT employee_name
    FROM employees
    WHERE department_id = p_department_id;
BEGIN
  -- Some code here
END;

In this example, we have specified a parameter p_department_id that can be used in the cursor's SELECT statement. We can then use this cursor to retrieve a specific set of records based on the value of p_department_id.

Conclusion

Cursors are powerful structures that enable the manipulation of data at a row-by-row basis. Understanding how to create, open, fetch, and close cursors can be useful in a variety of PL/SQL programming scenarios.