我有很多shell脚本来执行Oracle数据库上的过程和其他任务。通常,它们具有相同的结构,检查envvars,执行sql并使用show sqlcode
来了解脚本是否成功执行。
这是代码:
#!/bin/bash
# Check for var's in another script
. /home/oracle/cron/scripts/exp_variaveis.sh
$ORACLE_HOME/bin/sqlplus User/pass@database <<!
spool /home/oracle/cron/log/some_name.log_$date_log
set serveroutput on
DECLARE
V_QTD NUMBER;
BEGIN
SELECT COUNT(*) QTD
INTO V_QTD
FROM D.TB_R_A TRA
WHERE TRA.CD_STATUS = 'A'
AND TRA.CD_T_AUT = 'E'
AND TRA.DT_P < TRUNC(SYSDATE);
IF V_QTD = 0 THEN
DBMS_OUTPUT.PUT_LINE('Sem resgates para serem expirados.');
ELSE
FOR R1 IN (SELECT TRA.CD_R, TRA.CD_A, TRA.CD_O
from D.TB_R_A TRA
WHERE TRA.CD_STATUS = 'A'
AND TRA.CD_T_AUT = 'E'
and TRA.DT_P < TRUNC(sysdate))
LOOP
BEGIN
UPDATE D.TB_R_A T
SET T.CD_STATUS = 'E'
WHERE T.CD_R = R1.CD_R;
COMMIT;
DBMS_OUTPUT.PUT_LINE('Resgate expirado: ' || R1.CD_R);
EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
DBMS_OUTPUT.PUT_LINE('Falha na expiracao do resgate: ' || R1.CD_R);
END;
END LOOP;
END IF;
END;
-- command show slqcode to know if was executed with success
show sqlcode
spool off
exit
!
# A variavel recebe a instrucao de busca do arquivo e se existir reporta o "sqlcode 0" que equilave a "SUCESSO"
sql_code=`grep -i "sqlcode 0" /home/oracle/cron/log/some_name.log_$date_log`
# A variavel trata a instrucao acima e processa os dados nos textos e operacoess com arquivos (awk) mostrando de forma CSV (-F)
# apresentando as strings da segunda coluna '{ print $2 }'
ret_code=`echo $sql_code | awk -F" " '{ print $2 }'`
# Se a variavel $ret_code for diferente de 0
if [ "$ret_code" != 0 ]
then
# Send error message
mail dbajob@domain.com -s "!! ERROR !! CRON => DATABASE - SOME TEXT HERE" < /home/oracle/cron/log/some_name.log_$date_log
exit 1
else
# Send sucessful message
mail dbajob@domain.com -s "Job OK CRON => DATABASE - SOME TEXTE HERE" < /home/oracle/cron/log/some_name.log_$date_log
exit 0
fi
我的问题是:这个sql没有输出sqlcode,所以如果我的脚本没有找到字符串&#34; sqlcode&#34;在日志中,即使成功执行,它也会发送错误消息。
请有人告诉我有什么问题。
答案 0 :(得分:3)
请注意,在the docs中提及的情况下,在异常处理程序之外使用时,SQLCODE将始终返回0:
SQLCODE
仅在异常处理程序中有用。在处理程序之外,SQLCODE
始终返回0.
但是你甚至没有看到0输出的原因是你从不执行PL / SQL代码块,因此show
语句不被识别为立即执行的语句。您需要添加一行forward slash (/):
<强> /(斜杠)强>
执行最近执行的SQL命令或存储在SQL缓冲区中的PL / SQL块。
所以放在这里斜杠:
END LOOP;
END IF;
END;
/
-- command show slqcode will always show 0.
show sqlcode
答案 1 :(得分:1)
SQLCODE仅在异常处理程序中生成sens,以下是其用法示例:
CREATE TABLE errors (code NUMBER, message VARCHAR2(64), happened TIMESTAMP);
DECLARE
name employees.last_name%TYPE;
v_code NUMBER;
v_errm VARCHAR2(64);
BEGIN
SELECT last_name INTO name FROM employees WHERE employee_id = -1;
EXCEPTION
WHEN OTHERS THEN
v_code := SQLCODE;
v_errm := SUBSTR(SQLERRM, 1 , 64);
DBMS_OUTPUT.PUT_LINE('Error code ' || v_code || ': ' || v_errm);
INSERT INTO errors VALUES (v_code, v_errm, SYSTIMESTAMP);
END;