2015-07-21 47 views
0

我想遍歷SHELL腳本中的PL/SQL行,並且想要使用當前行執行某些代碼。在這一點上,我得到了:在SHELL中遍歷PL/SQL結果

VALUE='sqlplus -s /nolog <<EOF 
    CONNECT ${CONNECT} 
     select smth from table; 
     /
     EXIT 
     EOF' 

for i in "${VALUE[@]}" 
do 
##some code using "i" variable 
done 

此時對於5行代碼只執行一次。看起來它根本不會迭代。任何想法如何解決?

+0

要麼沒有數據從查詢或內部的一些錯誤返回for循環;在這種情況下,你可以相應地更新。 – Richard

回答

1

您可以重複你的結果集如下:

SQL> select car_model from available_models 
    2 group by car_model ; 

CAR_MODEL 
------------------------------ 
Corsair 
Executive 
Country Squire 

SQL> 

重寫你的shell腳本(使用時間)如下:

[[email protected] 1]$ cat test.sh 
CONNECT='z_test/welcome1' 
VALUE=`sqlplus -s /nolog <<EOF 
    CONNECT ${CONNECT} 
    set head off 
    select car_model from available_models 
    group by car_model 
     /
     EXIT 
EOF` 

echo "resultset: " 
echo "${VALUE}" 

echo " " 

echo "now iterate ..." 
let rec=0 

echo "${VALUE}" |while read line 
do 
    echo "processing $rec: $line" 
    let rec=rec+1 
done 

[[email protected] 1]$ 

這是預期輸出:

[[email protected] 1]$ ./test.sh 
resultset: 

Corsair 
Executive 
Country Squire 

now iterate ... 
processing 0: 
processing 1: Corsair 
processing 2: Executive 
processing 3: Country Squire 

請注意,第#0行是空白的,因爲它也是結果集的一部分。

添加「設置頁面大小0」將刪除該空白行:

[[email protected] 1]$ cat test.sh 
CONNECT='z_test/welcome1' 
VALUE=`sqlplus -s /nolog <<EOF 
    CONNECT ${CONNECT} 
    set head off 
    set pagesize 0 
    select car_model from available_models 
    group by car_model 
     /
     EXIT 
EOF` 
...... 

預期的運行:

[[email protected] 1]$ ./test.sh 
resultset: 
Corsair 
Executive 
Country Squire 

now iterate ... 
processing 0: Corsair 
processing 1: Executive 
processing 2: Country Squire 
[[email protected] 1]$ 

問候