Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference psql parameter inside PL/pgSQL anonymous block

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.

like image 681
innocentunremarkable Avatar asked Jan 20 '16 23:01

innocentunremarkable


People also ask

What is := in PostgreSQL?

= is for comparison. := is for assignment.

Can we use PL SQL in PostgreSQL?

PL/pgSQL (Procedural Language/PostgreSQL) is a loadable procedural programming language supported by the PostgreSQL. PL/pgSQL, as a fully featured programming language, allows much more procedural control than SQL, including the ability to use loops and other control structures.

How do you assign a selected value to a variable in PostgreSQL?

In PostgreSQL, the select into statement to select data from the database and assign it to a variable. Syntax: select select_list into variable_name from table_expression; In this syntax, one can place the variable after the into keyword.


1 Answers

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.

like image 197
Clodoaldo Neto Avatar answered Sep 25 '22 18:09

Clodoaldo Neto