Skip to content
Advertisement

ppgsql declaring variable from parameter

I am running a sql query from the command line where I pass in value called tablename:

psql "hostname" -v tablename=$1 -a -q -f "filename.sql"

I then set the variable like this:

set tablename :tablename

And then I have a function where I want to use the variable tablename like this:

DO $$
BEGIN
    
    if (tablename = 'movie_table') then
     -- query goes in here 
    END if;
END;
$$;

I have also tried declaring the variable with a few variations of this:

DECLARE tablename varchar := :tablename;

Please let me know if you have any suggestions. I get the following error:

syntax error at or near ":"

Advertisement

Answer

Your code cannot to work, because you try to read client side variables (psql) on server side (plpgsql). You need to push the value to custom server side variable, and in next step you can read it from plpgsql environment:

postgres=# set client_side_var Ahoj
postgres=# select set_config('my.client_side_var', :'client_side_var', false);
┌────────────┐
│ set_config │
╞════════════╡
│ Ahoj       │
└────────────┘
(1 row)

postgres=# do $$
declare var text default current_setting('my.client_side_var');
begin
   raise notice '>>>%<<<', var;
end;
$$;
NOTICE:  >>>Ahoj<<<
DO

You cannot to use a psql syntax :var inside plpgsql code.

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