Home > database >  How to pass unix variable in where condition of query?
How to pass unix variable in where condition of query?

Time:03-20

I have a file whose filename I am storing in a shell variable and I wish to pass that variable in the WHERE condition of my SQL select query. How can I achieve this ?

my code

cd /path/to/folder
var =$(ls tail)
id_var=$(echo "$var" | cut -f 1 -d '.')
...
...
sqlplus -s user/pwd@db < mysql.sql > output.txt

cat mysql.sql

select * from Records where "GlobalId"='$id_var'

CodePudding user response:

From this answer:

cd /path/to/folder
var =$(ls tail)
id_var=$(echo "$var" | cut -f 1 -d '.')
sqlplus -s user/pwd@db @mysql.sql "${id_var}" > output.txt

Then in mysql.sql use &1 to substitute the first start argument:

select * from Records where "GlobalId"='&1'

Note: &1 is a substitution variable (and not a bind variable) so you will need to make sure that the value passed in does not perform any SQL injection attacks.

CodePudding user response:

You can export the variable export id_var Then use envsubst command envsubst < mysql.sql

This will substitute your variable.

  • Related