简体   繁体   中英

How to pass parameters from a bat file or a command line to a plpgsql function?

This is my sql code:

create extension if not exists dblink;

drop function if exists  func_statistic(host varchar(32),port varchar(32),username varchar(32),password varchar(32));
create or replace function func_statistic(host varchar(32),port varchar(32),username varchar(32),password varchar(32)) returns int as
$$
declare v_dbname text;
declare v_dest_file text;
declare v_connect_info text;
declare v_sql_str text;
begin
   ......
end;
$$ language plpgsql;


select func_statistic(:host,:port,:username,:password);

And I wrote this in the bat:

psql -U %user% -h %host% -p %port%  -v host=%host% -v port=%port% 
-v username=%user% -v password=%PGPASSWORD% -c %sql_file% cmsdb 

That's wrong. I can't pass parameter to the function of the .sql file in this way. Do you know how to pass parameters to the plpgsql function or why they can't be passed? Thank you very much.

probably using -c option in this context is wrong. Probably you should to use -f option or reading from stdin . The text parameters should be escaped and closed between apostrophes with syntax :'varname' :

CREATE OR REPLACE FUNCTION public.fx(text)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
begin
  raise notice '>>%<<', $1;
end;
$function$

[oracle@ora2pg migrace]$ echo "select fx(:'xxx')" | psql -v xxx='aaaaa bbbb'
Time: 1,962 ms
Debug assertions "off"
NOTICE:  >>aaaaa bbbb<<
┌────┐
│ fx │
╞════╡
│    │
└────┘
(1 row)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM