Passing argument to a psql procedural script

耗尽温柔 提交于 2019-12-11 11:05:35

问题


I have a loop command script on psqlthat looks like this:

script.sql

DO $$DECLARE
    data_rec RECORD;
    r RECORD;
    r2 RECORD;
BEGIN
select mytables.data_id into data_rec from mytables where id = :arg1;

    FOR r IN select * from
    (select * from ...)
    LOOP
        FOR r2 IN select * from
        (...)
              LOOP
            ......
          END LOOP;
    END LOOP;
END$$;

And I want to pass arg1 as a argument from the command line:

psql -h db.server.com -f script.sql -v arg1=1234 > foo.out

But I keep getting a syntax error at where id = :arg1, so I'm out of ideas how to pass a simple parameter to this script. Suggestions welcome


回答1:


There are few possibilities, how to do it. Anonymous block is relative strongly isolated from client environment, so parametrisation is not intuitive - but it is not hard work.

You can use a server side session variables. These variables are accessible from both environments.

postgres=# \set txt Ahoj
postgres=# set myvars.txt to :'txt'; -- fill server side variable
SET
postgres=# do $$ begin raise notice '%', current_setting('myvars.txt'); end;$$;
NOTICE:  Ahoj
DO

Little bit more complex example

bash-4.1$ cat test.sh
echo "
set myvars.msgcount TO :'msgcount'; 
DO \$\$ 
BEGIN 
  FOR i IN 1..current_setting('myvars.msgcount')::int LOOP 
    RAISE NOTICE 'Hello';
  END LOOP; 
END \$\$" | psql postgres -v msgcount=$1


bash-4.1$ sh test.sh 10
SET
Time: 0.935 ms
NOTICE:  Hello
NOTICE:  Hello
NOTICE:  Hello
NOTICE:  Hello
NOTICE:  Hello
NOTICE:  Hello
NOTICE:  Hello
NOTICE:  Hello
NOTICE:  Hello
NOTICE:  Hello
DO
Time: 1.709 ms


来源:https://stackoverflow.com/questions/24073632/passing-argument-to-a-psql-procedural-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!