shell脚本和sqlplus间的交互


有些时候我们可能需要shell脚本通过oracle的sqlplus执行一些sql,并对结果集进行相关的操作。这里大致总结有如下几种方法
直接获取单个值
Python代码 
#!/bin/bash 
result=`sqlplus -S system/password <<EOF 
set heading off feedback off pagesize 0 verify off echo off numwidth 4 
select 1 from dual; 
exit 
EOF` 
echo $result #将返回sql执行的结果 
 
将shell的参数传递给sqlplus
Python代码 
#!/bin/bash 
TEST="table_name" 
sqlplus -S system/password <<EOF 
select * from user_tables where table_name = upper('$TEST'); 
exit 
EOF 
 
sqlplus的结果含有多个列值

#使用上篇日志的例子
Python代码 
result=`sqlplus -S system/password <<EOF 
set heading off feedback off pagesize 0 verify off echo off numwidth 4 
select t2.used,t1.maxsize from (select count(file_name)*32 maxsize from dba_data_files where tablespace_name ='$TBS_NAME') t1,(select trunc(sum(bytes)/1024/ 
1024/1024) used from dba_data_files where tablespace_name='$TBS_NAME') t2; 
exit 
EOF` 
 
USED=`echo $result |cut -d " " -f1` 
MAXSIZE=`echo $result |cut -d " " -f2` 
 
最后两行就是对多结果集的处理,该查询语句将返回两列。不管是两列还是多列。系统都是用空格作为分隔符的顺序输出。所以我们通过上面两行就可以取到需要的值。如果列数或行数较多,可以使用其他方法,如for等。
但是一定要注意,返回的结果集数据里面本身是否就含有空格~不要造成无伤
 

相关内容

    暂无相关文章

评论关闭