2011-02-01 130 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查詢可能不是一個好的解決方案。也許你開發的速度會更快,你會這樣做,但是如果沒有,你應該考慮制定一個程序。