SQLPLUS output to shell script not returning value
I'm trying to return a sqlplus output to a shell 开发者_如何学编程script. This may sound simple enough but I've searched online for some time and cannot get my script to work.
Here is my pl/sql script:
SET SERVEROUTPUT ON
DECLARE
X_RETURN_MSG VARCHAR2(32767);
X_RETURN_CODE NUMBER;
BEGIN
X_RETURN_MSG := NULL;
X_RETURN_CODE := 5;
COMMIT;
END;
EXIT X_RETURN_CODE;
Here is my shell script:
sqlplus -s user/pwd <<EOF
@../sql/tester.sql
EOF
RETVAL=$?
echo $RETVAL
$RETVAL always returns 0 even when I have X_RETURN_CODE := 5
X_RETURN_CODE
has no meaning outside of the scope of the PL/SQL block where it is declared. You need to use a SQLPlus bind variable.
SQL> VARIABLE return_code NUMBER
SQL> BEGIN
2 :return_code := 5;
3 END;
4 /
PL/SQL procedure successfully completed.
SQL> EXIT :return_code
Disconnected from Oracle Database 10g Release 10.2.0.4.0 - Production
> echo $?
5
My guess is END marks the end of the block and X_RETURN_CODE goes out of scope so it defaults to 0. Or maybe you should look into using the RETURN statement instead of EXIT.
$ sqlplus -s <<!
> / as sysdba
> @tester
> !
PL/SQL procedure successfully completed.
$ echo $?
5
$ cat tester.sql
SET SERVEROUTPUT ON
var X_RETURN_CODE number
DECLARE
X_RETURN_MSG VARCHAR2(32767);
BEGIN
X_RETURN_MSG := NULL;
:X_RETURN_CODE := 5;
COMMIT;
END;
/
EXIT :X_RETURN_CODE;
精彩评论