Iterating through PL/SQL result in SHELL

主宰稳场 提交于 2021-02-08 10:21:06

问题


I want to iterate over PL/SQL rows in SHELL script and for each row I want to execute some code using current row. At this point I got:

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

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

At this point for 5 rows code executes only once. It appears it doesn't iterate at all. Any ideas how can I fix that?


回答1:


You can iterate your resultset as follows:

SQL> select car_model from available_models
  2  group by car_model ;

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

SQL>

Rewrite your shell script (using WHILE) as follows:

[oracle@ora12c 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

[oracle@ora12c 1]$

And this is the expected output:

[oracle@ora12c 1]$ ./test.sh
resultset:

Corsair
Executive
Country Squire

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

Note that line #0 is blank and is expected, because is part of your resultset too.

Adding "set pagesize 0" will remove this blank line:

[oracle@ora12c 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`
......

Expected run:

[oracle@ora12c 1]$ ./test.sh
resultset:
Corsair
Executive
Country Squire

now iterate ...
processing 0: Corsair
processing 1: Executive
processing 2: Country Squire
[oracle@ora12c 1]$

Regards



来源:https://stackoverflow.com/questions/31533591/iterating-through-pl-sql-result-in-shell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!