Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variables to psql script

I've searched for this for a while but can't seem to find a definitive answer... I'm trying to run a psql script from the Terminal while passing a table variable name and another variable as part of the psql script.

BASH Command:

psql db1 -U user1 -f '/.../Desktop/.../sample.sql' -v table=pg2 -v v1="'2018-02-01'"; 

PSQL Script:

SELECT count(*) FROM :table WHERE datekey = :v1;

The above works. However, I'd like to be able to convert the tablename and the additional variable into a string in the script itself so I can use it in another function I've defined. For example, I'd like the tablename of pg2 to be available as a string 'pg2'. Similar requirement with the datekey variable. Is this possible? My observation is that passing variables is only possible if used in a CRUD operation or a WHERE clause.

like image 877
thomassantosh Avatar asked Oct 20 '25 10:10

thomassantosh


1 Answers

From what I get from your question is a misunderstanding of what variables in bash do. Try if the script below helps:

#!/bin/bash

user="user1"
sqlfile='/.../Desktop/.../sample.sql'
table='pg2'
v1="'2018-02-01'"

psql db1 -U "$user" -f "$sqlfile" -v table=$table -v v1="$v1"
like image 89
Ljm Dullaart Avatar answered Oct 22 '25 00:10

Ljm Dullaart