postgresqlargumentspostgresql-9.1

PostgreSQL cursor with arguments


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?


Solution

  • 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.