0

For inputs of a postgis function, I used a cursor to fetch a record at once from a table.

I know that the single record can be printed by the code: FETCH 1 FROM cur1. I wonder how to convert the fetched result into a single string.

BEGIN;
DECLARE cur1 CURSOR FOR SELECT rec FROM Table;
FETCH 1 FROM cur1;
                    rec
---------------------------------------
 vehicles
(1 row)
END;

Thanks!

1
  • You can concat string in format: string || string Commented Jul 20, 2014 at 16:11

1 Answer 1

1

You can convert row to text just by casting it to text:

BEGIN;
DECLARE cur1 CURSOR FOR SELECT t.*::text FROM Table t;
FETCH 1 FROM cur1;

Row values will be separated by comma and whole row will be enclosed into parenthesis.

If you also want column names it is possible to convert row to JSON:

BEGIN;
DECLARE cur1 CURSOR FOR SELECT row_to_json(t.*) FROM Table t;
FETCH 1 FROM cur1;
Sign up to request clarification or add additional context in comments.

7 Comments

yes, the codes can convert row to text, but they cannot used in the cursor situation.
Why not? Just prepend DECLARE cur1 CURSOR FOR and you will get a cursor.
how do you select the table? I used cur1 as the table (SELECT t.rec::text FROM cur1 t), but it does not work, showing: relation "cur1" does not exist. If I selected the original table, all records are showed, instead of just 1 by 1.
I just updated my answer with full commands. Hope this will be more clear.
One more issue that I cannot use the results of FETCH 1 FROM cur1 for string functions, if I set more than one cursor. For example, SELECT (FETCH 1 FROM cur_1)||","||FETCH 1 FROM cur_2), although the cursors are in text.
|

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.