2012-01-30 101 views
0

前段时间,我写了一个小例程来针对Oracle数据库运行一些快速n'脏查询(并指出它不用于大型查询),但也希望解析错误有点容易一些。具体情况如下:Ksh函数用于返回值查询Oracle

# Executes the query 
# 
# Will execute a query contained in the variable named 
# in the parameter $4 and store the result in the variable 
# named in $5. 
# In case of errors (even SQL related) the function should 
# exit with status 1, making it possible to "if execQuery". 
# 
# @param $1 = User 
#   $2 = Pasword 
#   $3 = Tns Alias 
#   $4 = Name of the variable containing the query 
#   $5 = Name of the variable to hold the result 
# 
# @return query execution status 
function execQuery { 
    typeset eSQLU=$1 
    typeset eSQLP=$2 
    typeset eSQLS=$3 
    typeset etQUERY=$4 
    eval typeset eQUERY=\$$etQUERY 
    typeset eQRES=$5 
    logMessageFile "DEBUG" "Query: $eQUERY" 

    typeset res=$(sqlplus -s $eSQLU/[email protected]$eSQLS <<EOF 
set echo off newpage 0 space 0 pagesize 0 feed off head off verify off lines 999 
WHENEVER SQLERROR EXIT 1 
$eQUERY 
exit; 
EOF 
) 
    [[ $? -gt 0 ]] && return 1 || eval "$eQRES=\"$res\"" 

} 

此功能的想法是,以后我可以这样做:

query="select sysdate from dual;" 
if execQuery $RAID_APP_PI_USR $RAID_APP_PI_PWD $RAID_APP_PI_SID query result ; then 
    echo $result 
    logMessageFile "INFO" "Inserts into XX successful." 
else 
    logMessageFile "ERROR" "Error insertando XXX." 
fi 

它还挺工作...一个正确编写查询会做精,结果变量所有正确评估和所有。问题是错误。如果该示例中的查询类似select * potato potato;,它仍然不会产生正确的返回值,因此缺少错误测试。

我对sqlplusksh不是特别好,可能只是缺少一些明显的东西......有人可以借我一只手吗?

谢谢!

回答

2

我相信$?正在返回typeset命令的退出状态,而不是sqlplus命令。

将SQLPLUS语句的结果输​​出到文件而不是变量中可能更容易。然后,您可以使用grep读取该文件,查找“ORA-”消息或检查退出状态变量。

sqlplus -s $eSQLU/[email protected]$eSQLS > querylog.tmp <<EOF 
set echo off newpage 0 space 0 pagesize 0 feed off head off verify off lines 999 
WHENEVER SQLERROR EXIT 1 
$eQUERY 
exit; 
EOF 

echo $? 
+0

这实际上就是我要做的就是在啤酒查询其他功能...我想保持这种功能虽然简单,但是,真希望我有办法,而不解析它读取查询的实际结果或使用文件......这可能会让我头疼,同时发生多次执行和脚本异常中断(即解析错误文件或生活临时文件)。正如我所说,它在更大的功能中起作用..只是不想在这个简单的问题中产生这种麻烦.. – filippo 2012-01-30 17:10:09

+0

我不知道Korn Shell是否可以做你想做的事情。 Bash允许从子shell(命令替换)的退出状态返回到主shell,如果部分赋值语句,但对于KSH,您最好的选择可能是临时文件。你总是可以为临时文件创建一个有保证的唯一文件名,并且每天清除它们... – 2012-01-30 19:01:07

+0

我最好不要将userid和密码传递给SQL * Plus - 使用'sqlplus/nolog'选项并且那么立即使用'CONNECT $ eSQLU/$ eSQLP @ $ eSQLS'就可以避免这种情况。 – 2012-01-30 20:41:58