在bash脚本中循环sql查询

时间:2011-02-01 06:07:14

标签: sql oracle bash loops sqlplus

我需要使用bash循环oracle sqlplus查询。

我的情况是这样的。我在文本文件中有一组名称,我需要使用sqlplus查询找出这些名称的详细信息。

textfile.txt内容:

john
robert
samuel
chris

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

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

问题是当我运行脚本时出现错误,如

  

SP2-0734:未知命令开头   “罗伯特......” - 其余的一行被忽略了。

有人能告诉我如何解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

我一直这样做的方式如下:

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

答案 1 :(得分:1)

你有set define on吗?你的通配符是&吗?您可以查看glogin.sql以了解。

是的,建立n个连接以传递n个查询可能不是一个好的解决方案。也许你开发速度更快,你会做一次,但如果没有,你应该考虑制作一个程序。