Domanda

Short version

What are some (real) valid use cases of cursors?

Long version

A while ago, when I was in my database class and the teacher touched the cursors topic, I asked her about valid use cases. She answered with an use of cursors for presentation purposes: you have a book database and you want to show all the books but "grouped" by author, and only showing the author's name once. I am not convinced by this example because it seems to me that these kind of presentation concerns do not belong to the database but the client (a UI that shows them in a pretty way).

I have thought about valid use cases for cursors, but I can't find any that I can't express in a clearer way with no cursors. It seems to me that using cursors makes you think in a "imperative way" rather than the "declarative, set-based" way you should think most of the time.

So I would like to know when it's good to use cursors. I would prefer to hear about real use cases.

È stato utile?

Soluzione

Generally speaking, you should go out of your way to avoid cursors, and try to use set-based standard SQL when you can.

One case where it is actually required is if you want to return multiple results in one query with PostgreSQL.

CREATE FUNCTION myfunc(refcursor, refcursor) RETURNS SETOF refcursor AS $$
BEGIN
    OPEN $1 FOR SELECT * FROM table_1;
    RETURN NEXT $1;
    OPEN $2 FOR SELECT * FROM table_2;
    RETURN NEXT $2;
END;
$$ LANGUAGE plpgsql;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top