STORED PROCEDURE and Cursor
STORED PROCEDURE and Cursor
DECLARE
CURSOR employee_cursor IS
SELECT employee_id, first_name, last_name FROM employees
WHERE department_id = 20;
BEGIN
-- Cursor declaration
-- Placeholder for further code
END;
Opening a Cursor
• In PL/SQL, after declaring a cursor, you need to open it before fetching
data from it. Here's how you can open a cursor:
DECLARE
CURSOR cursor_name IS
SELECT column1, column2, ... FROM table_name WHERE condition;
BEGIN
OPEN cursor_name;
-- Fetch and process rows here
CLOSE cursor_name; -- Close the cursor when done
END;
DELETE
Once a cursor is positioned, we can delete row identifying by the
cursor using DELETE WHERE CURRENT OF statement
delete from table_name where current of cursor_variable;
Looping through a cursor
• Loops can be used to iterate through records of a cursor.
• Eg:-
DO $$
DECLARE
Cur_books CURSOR FOR SELECT * FROM BOOKS;
row_books RECORD;
BEGIN;
OPEN cur_books;
LOOP
FETCH cur_books INTO row_books;
EXIT WHEN NOT FOUND;
RAISE NOTICE ‘%,%,Rs %’, row_books.TITLE, row_books.author, row_books.price;
END LOOP;
END; $$