I am trying to learn basic cursors using PostgreSQL. This is my script:
DECLARE cur_employees CURSOR FOR
SELECT *
FROM employee
CLOSE cur_employees
I want to traverse the list and output those which are active. Where should I start?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You very rarely want to explicitly use cursors at all in PostgreSQL, even when processing query results in plpgsql. This is a marked contrast from many other SQL databases where they are used almost all the time.
In plpgsql you could simply write something like:
In the above, the plpgsql language handler deals with opening, binding, fetching and closing itself (more on declarations, and control structures).
With PostgreSQL from 9.0, you can simply drop into executing plpgsql using a “DO” block. For prior versions, you need to create a function and select it. If you’re looking for the PostgreSQL equivalent of, for example, iterating through a result with a cursor on SQL Server, that’s what it is. Note that iteration etc. are not part of the SQL dialect, only part of plpgsql (or any of the other emebedded languages).
The “DECLARE CURSOR xxx” syntax at the SQL level can be used like this:
This can be used to carefully get just part of the query result set. However, it’s unusual to use these, since usually your client driver will provide some sort of functionality to do this (e.g. scrollable result sets in JDBC). You can also return cursors from functions similar to Oracle, although again that’s a comparatively rare use case.