Home > front end >  PSQL Execute Commands from a file, where the file is determined based on a passed variable
PSQL Execute Commands from a file, where the file is determined based on a passed variable

Time:02-19

I had asked a very similar question last week and it was answered and it help immensely. Now I have a slightly different psql question

I have a batch script that connects to a database and gives it a sql file to execute (myFirstSQLFile.sql). This script also passes a env variable with the value of test.

%PSQLCOMMAND% -h {server} -U {user} -d {dbname} -E -q -f myFirstSQLFile.sql -v env="test"

myFirstSQLFile.sql has more psql commands to execute other sql files, as such below.

\i file1.sql;
\i file2.sql;
\i file3.sql;

What I am trying to do is execute certain lines within the file based on the value of the env variable that i am passing to it.

Something like a conditional statement, perhaps like this

\i file1.sql;
\i file2.sql;

\if :env = 'test'
  \i file3.sql;
\else
  \i file4.sql
\endif;

However the above doesn't work, I don't know if that is even remotely close to proper syntax.

I've tried a number of things but haven't gotten anything to work so far. I'm open to any type of solution, it doesn't necessarily have to be an if statement, like if its possible to pass a filename as a variable from the batch script and then somehow execute that in the sql file, that would be an acceptable solution for me as well.

CodePudding user response:

You cannot have a comparison in \if. This should work:

SELECT :'env' = 'test' AS is_test \gset
\if :is_test
   \i file3.sql
\else
   \i file4.sql
\endif
  • Related