1

I need to loop a oracle sqlplus query using bash.

my scenario is like this. I have a set of names in a text file and i need to find out details of that names using a sqlplus query.

textfile.txt content:

john
robert
samuel
chris

bash script

#!/bin/bash

while read line
do
/opt/oracle/bin/sqlplus -s user@db/password @query.sql $line
done < /tmp/textfile.txt

sql query: query.sql

set verify off
set heading off
select customerid from customers where customername like '%&1%';
exit

problem is when I run the script I get errors like

SP2-0734: unknown command beginning "robert..." - rest of line ignored.

can someone tell me how to solve this?

2
  • 2
    usually it's better to perform one big query and avoid loops over sql Commented Feb 1, 2011 at 6:17
  • 2
    Indeed. It looks like the OP is trying to re-invent a stored procedure kept in a text file. Commented Feb 1, 2011 at 6:22

2 Answers 2

2

The way I do this all the time is as follows:

#!/bin/bash

cat textfile.txt |while read Name
do
sqlplus -s userid/password@db_name > output.log <<EOF
set verify off 
set heading off 
select customerid from customers where customername like '%${Name}%'
/
exit
EOF

Bash will auto magically expand ${Name} for each line and place it into the sql command before sending it into sqlplus

Sign up to request clarification or add additional context in comments.

Comments

1

Do you have set define on ? Is your wildcard & ? You could check glogin.sql to know.

And yes, establishing n connections to pass n queries is probably not a good solution. Maybe it's faster for you to develop and you will do that one time, but if not, you should maybe think of crafting a procedure.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.