Search code examples
functionpostgresqlstored-proceduresexecuteplpgsql

Execute a SELECT statement and discard results in PL/pgSQL


I am trying to create a simple stored procedure in PostgreSQL within which I want to execute a SELECT statement. I do not want to return the results of the select statement.

If I use the select statement directly like the following code, I get an error saying that "query has no destination for result data"

DECLARE
affected_rows INTEGER;
BEGIN
SET search_path TO testing;

    SELECT * FROM testing.csv_data_already_imported;

    GET DIAGNOSTICS affected_rows := ROW_COUNT;
    RETURN affected_rows;
END;

Therefore I use the PREPARE .. EXECUTE statements like so:

DECLARE
affected_rows INTEGER;
BEGIN
SET search_path TO testing;

    PREPARE fooplan AS SELECT * FROM testing.csv_data_already_imported;
    EXECUTE fooplan;

    GET DIAGNOSTICS affected_rows := ROW_COUNT;
    RETURN affected_rows;
END;

Using this method still gives me errors:

ERROR:  column "fooplan" does not exist
LINE 1: SELECT fooplan
               ^

QUERY:  SELECT fooplan
CONTEXT:  PL/pgSQL function "returning_affected_rows" line 8 at EXECUTE statement

Can anyone help me understand what is wrong? The stored procedure is declared to be a plpgsql function meaning that the EXECUTE command should not be considered as being the standard SQL command to execute dynamic SQL statements. All I want to know is how to execute a SELECT statement inside a PostgreSQL stored procedure without needing to return its results. The full DDL of the stored procedure is as follows:

CREATE OR REPLACE FUNCTION testing.returning_affected_rows ()
RETURNS integer AS
$body$
DECLARE
    affected_rows INTEGER;
BEGIN
    SET search_path TO testing;

    PREPARE fooplan AS SELECT * FROM testing.csv_data_already_imported;
    EXECUTE fooplan;

    GET DIAGNOSTICS affected_rows := ROW_COUNT;
    RETURN affected_rows;
END;
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT
SECURITY INVOKER
COST 100;

Solution

  • You need PERFORM "to execute a SELECT statement inside a postgresql stored procedure without needing to return its results".

    Otherwise your problem is that PL/pgSQL's command EXECUTE is different than the SQL command EXECUTE.