Middle
Explicit and implicit cursors — when are they used?
sobes.tech AI
Answer from AI
Explicit cursors are used when more fine-grained control over the processing of a set of rows from a query result is needed. For example, when it is necessary to process each row sequentially, perform complex logic, or update data within a loop.
Implicit cursors are automatically created for each SQL query that returns a result (e.g., SELECT INTO). They are convenient for simple operations where step-by-step control over the selection is not required.
Example of using an explicit cursor in PL/SQL:
DECLARE
CURSOR c_emp IS SELECT employee_id, salary FROM employees WHERE department_id = 10;
v_emp_id employees.employee_id%TYPE;
v_salary employees.salary%TYPE;
BEGIN
OPEN c_emp;
LOOP
FETCH c_emp INTO v_emp_id, v_salary;
EXIT WHEN c_emp%NOTFOUND;
-- process each row
DBMS_OUTPUT.PUT_LINE('Employee ' || v_emp_id || ': ' || v_salary);
END LOOP;
CLOSE c_emp;
END;