简体   繁体   中英

How invoke PL/pgSQL from command line instead of SQL

I write PL/SQL scripts using Oracle and I'm trying my first PL/pgSQL script with PostgreSQL. For example, I created this test.sql file.

DECLARE
    v_loc_nbr         INTEGER;
BEGIN
    v_loc_nbr := 0;
END;

Which I try to execute using the command line:

\postgresql\9.3\bin\psql.exe -d postgres -f test.sql

but I get syntax errors like:

psql:test.sql:4: ERROR: syntax error at or near "v_loc_nbr"

I think the problem is it trying to execute SQL when I want it to run PL/pgSQL. What should the command be?

Like with other procedural languages , you cannot run PL/pgSQL directly.
You can only run SQL. Use plpgsql inside a function body or wrapped in a DO command, where the range of DO commands is limited since they cannot return data.

Check out the tag for examples.

I don't want to explain more about this because Erwin explained well.You need to wrap your sql inside a DO , so your test.sql should write like this

DO
$$
DECLARE
    v_loc_nbr INTEGER;
BEGIN
    v_loc_nbr := 0;
END;
$$

and try to execute it \\postgresql\\9.3\\bin\\psql.exe -d postgres -f test.sql

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