2011-02-01 131 views
1

我需要使用bash循环一个oracle sqlplus查询。在bash脚本中循环sql查询

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

TextFile.txt的内容:

john 
robert 
samuel 
chris 

bash脚本

#!/bin/bash 

while read line 
do 
/opt/oracle/bin/sqlplus -s [email protected]/password @query.sql $line 
done < /tmp/textfile.txt 

SQL查询:query.sql的

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

问题是,当我运行该脚本,我得到这样的错误

SP2-0734:未知命令开始 “robert ...” - 忽略行的其余部分。

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

+2

通常最好是执行一个大的查询并避免循环执行sql – 2011-02-01 06:17:53

+2

的确如此。它看起来像OP正试图重新创建一个保存在文本文件中的存储过程。 – lll 2011-02-01 06:22:32

回答

2

我做这一切的时候的方法如下:

#!/bin/bash 

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

bash将自动奇迹般地扩大$ {名称}的每一行并把它发送到sqlplus中之前将其放置到SQL命令

1

您有set define on?你的通配符是&?你可以检查glogin.sql知道。

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