Roshni
Roshni

Reputation: 54

How to pass unix variable in where condition of query?

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'

Upvotes: 0

Views: 511

Answers (2)

Tanmay
Tanmay

Reputation: 1

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

This will substitute your variable.

Upvotes: 0

MT0
MT0

Reputation: 167972

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.

Upvotes: 3

Related Questions