Skip to content
Advertisement

ERROR cursor does not exist after first loop in PL/pgSQL

I need to load a large number of csv files in to a PostgreSQL database. I have a table source_files which contains the file paths and a flag which indicates whether a file has already been loaded for all the csv files I need to load.

I have written the following code which loads the first file correctly but then throws the error:

ERROR: cursor "curs" does not exist

Why am I getting this error and how can I fix it?

Advertisement

Answer

There big problem with your code is the COMMIT. You can use COMMIT in a DO statement, but the cursor is closed as soon as the transaction ends. In SQL you can create a cursor WITH HOLD that remains valid after the transaction has ended, but that is not available in PL/pgSQL.

I suggest removing the COMMIT.

Another error in your code is your use of the format function, which exposes you to SQL injection. Instead of

use

You can make the code much simpler by using an implicit cursor in the loop:

That saves you declaring the cursor and the EXIT WHEN. The OPEN and CLOSE statements are unnecessary anyway.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement