在SHELL中迭代PL / SQL结果

时间:2015-07-21 08:09:14

标签: oracle shell unix

我想在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行代码只执行一次。看起来它根本不会迭代。任何想法我该如何解决?

1 个答案:

答案 0 :(得分:2)

您可以按如下方式迭代结果集:

SQL> select car_model from available_models
  2  group by car_model ;

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

SQL>

重写shell脚本(使用WHILE),如下所示:

[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]$

这是预期的输出:

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

Corsair
Executive
Country Squire

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

请注意,第0行是空白的,是预期的,因为它也是结果集的一部分。

添加&#34;设置页面大小0&#34;将删除此空行:

[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`
......

预期运行:

[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]$

此致