简体   繁体   English

在bash脚本中循环sql查询

[英]loop sql query in a bash script

I need to loop a oracle sqlplus query using bash. 我需要使用bash循环oracle sqlplus查询。

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. 我在文本文件中有一组名称,我需要使用sqlplus查询找出该名称的详细信息。

textfile.txt content: textfile.txt内容:

john
robert
samuel
chris

bash script bash脚本

#!/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 sql查询: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. SP2-0734:未知命令以“ robert ...”开头-其余行被忽略。

can someone tell me how to solve this? 有人可以告诉我如何解决吗?

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 Bash将自动神奇地扩展每一行的$ {Name}并将其放入sql命令中,然后再发送至sqlplus

Do you have set define on ? 您是否已将set define on Is your wildcard & ? 是您的通配符&吗? You could check glogin.sql to know. 您可以检查glogin.sql来了解。

And yes, establishing n connections to pass n queries is probably not a good solution. 是的,建立n连接以传递n查询可能不是一个好的解决方案。 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. 也许对您来说开发起来会更快,并且您会一次完成,但是如果没有,您应该考虑制定一个过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM