8

I'd like to pass a parameter to an anonymous PL/pgSQL block via psql command line, then check that parameter in a conditional.

The relevant part of the SQL is here:

do $$
begin
    if (':para' = 1) then
        -- statements;
    end if;
end $$
;

I call this script as such:

psql -d dbname -v para=1 < script.sql

I receive the error:

ERROR:  invalid input syntax for integer: ":para"
LINE 1: SELECT (':para' = 1)
            ^
QUERY:  SELECT (':para' = 1)
CONTEXT:  PL/pgSQL function inline_code_block line 3 at IF

I tried using the case/when paradigm, which did not work either.

I am guessing that a psql parameter is not compatible with PL/pgSQL? Ultimately, my goal is to run a single delete statement if I pass 1 as a psql parameter, and not run it if I pass 0.

Clodoaldo Neto
  • 118,695
  • 26
  • 233
  • 260

1 Answers1

6

The psql parser can't see what is inside strings. This might be what you want:

delete from t
where :para = 1

Do it outside of an anonymous block. If you really need PL/pgSQL use a parameterized function:

create or replace function f(_para integer)
returns void as $$
begin
    if _para = 1 then
        --statements
    end if;
end; $$ language plpgsql;

And your script file will have:

select f(:para);

If you do not want to permanently add a function to the db do it all inside the script:

drop function if exists f_iu7YttW(integer);

create or replace function f_iu7YttW(_para integer)
returns void as $$
begin
    if _para = 1 then
        --statements
    end if;
end; $$ language plpgsql;

select f_iu7YttW(:para);

drop function f_iu7YttW(integer);

Give the function an unique name so you do not run the risk of dropping something else.

Clodoaldo Neto
  • 118,695
  • 26
  • 233
  • 260