4

As the documentation describes here, I need to declare a cursor that accepts arguments at OPEN time.

My query looks something similar to:

DECLARE cur CURSOR (argName character varying) FOR SELECT * FROM "TableName" WHERE "SomeColumn" = argName;

When I do this, I get a lovely error:

ERROR:  syntax error at or near "("
LINE 1: DECLARE cur CURSOR (argName character varying) FOR SELECT * FROM...
                           ^

It seems that PostgreSQL is not accepting this form of cursor declaration. Is there any way to solve this? Any workaround?

3 Answers 3

5

That syntax is only valid inside plpgsql functions.

http://www.postgresql.org/docs/current/static/plpgsql-cursors.html

Sign up to request clarification or add additional context in comments.

1 Comment

I marked your answer as accepted, but I changed it to Igor's because yours just states my mistake, while his actually offers a workaround, which was what I was looking for.
3

Try something like:

DECLARE 
  argName varchar;
  cur CURSOR FOR SELECT * FROM "TableName" WHERE "SomeColumn" = argName;

The argName will be taken into the query when you OPEN this cursor.

3 Comments

Thanks! That looks promising.
Question: I should CLOSE and OPEN cur after changing argName to a new value, right?
@gcontreras Yes. When cursor is opened it does not changes its query and params.
1

Excerpt from: https://www.postgresql.org/docs/current/static/plpgsql-cursors.html

DECLARE
    key integer;
    curs4 CURSOR FOR SELECT * FROM tenk1 WHERE unique1 = key;
BEGIN
    key := 42;
    OPEN curs4;

From:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.