【问题标题】:Iterating through PL/SQL result in SHELL遍历 PL/SQL 导致 SHELL
【发布时间】:2015-07-21 08:09:14
【问题描述】:

我想遍历 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 行代码只执行一次。看来它根本没有迭代。有什么想法可以解决这个问题吗?

【问题讨论】:

  • 要么没有从查询返回的数据,要么在 for 循环中有问题;在这种情况下,您可以相应地更新。

标签: oracle shell unix


【解决方案1】:

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

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 行是空白的,是预期的,因为它也是结果集的一部分。

添加“set pagessize 0”将删除此空白行:

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

问候

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-11
    • 2023-03-19
    • 1970-01-01
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-24
    相关资源
    最近更新 更多