Connect to sqlplus in a shell script and run SQL scripts
For example:
sqlplus -s admin/password << EOF
whenever sqlerror exit sql.sqlcode;
set echo off
set heading off
@pl_script_1.sql
@pl_script_2.sql
exit;
EOF
Wouldn't something akin to this be better, security-wise?:
sqlplus -s /nolog << EOF
CONNECT admin/password;
whenever sqlerror exit sql.sqlcode;
set echo off
set heading off
@pl_script_1.sql
@pl_script_2.sql
exit;
EOF
If you want to redirect the output to a log file to look for errors or something. You can do something like this.
sqlplus -s <<EOF>> LOG_FILE_NAME user/passwd@host/db
#Your SQL code
EOF
This should handle issue:
- WHENEVER SQLERROR EXIT SQL.SQLCODE
- SPOOL ${SPOOL_FILE}
- $RC returns oracle's exit code
- cat from $SPOOL_FILE explains error
SPOOL_FILE=${LOG_DIR}/${LOG_FILE_NAME}.spool
SQLPLUS_OUTPUT=`sqlplus -s "$SFDC_WE_CORE" <<EOF
SET HEAD OFF
SET AUTOPRINT OFF
SET TERMOUT OFF
SET SERVEROUTPUT ON
SPOOL ${SPOOL_FILE}
WHENEVER SQLERROR EXIT SQL.SQLCODE
DECLARE
BEGIN
foooo
--rollback;
END;
/
EOF`
RC=$?
if [[ $RC != 0 ]] ; then
echo " RDBMS exit code : $RC " | tee -a ${LOG_FILE}
cat ${SPOOL_FILE} | tee -a ${LOG_FILE}
cat ${LOG_FILE} | mail -s "Script ${INIT_EXE} failed on $SFDC_ENV" $SUPPORT_LIST
exit 3
fi
Some of the other answers here inspired me to write a script for automating the mixed sequential execution of SQL tasks using SQLPLUS along with shell commands for a project, a process that was previously manually done. Maybe this (highly sanitized) example will be useful to someone else:
#!/bin/bash
acreds="user_a/supergreatpassword"
bcreds="user_b/anothergreatpassword"
hoststring='fancyoraclehoststring'
runsql () {
# param 1 is $1
sqlplus -S /nolog << EOF
CONNECT $1@$hoststring;
whenever sqlerror exit sql.sqlcode;
set echo off
set heading off
$2
exit;
EOF
}
echo "TS::$(date): Starting SCHEM_A.PROC_YOU_NEED()..."
runsql "$acreds" "execute SCHEM_A.PROC_YOU_NEED();"
echo "TS::$(date): Starting superusefuljob..."
/var/scripts/superusefuljob.sh
echo "TS::$(date): Starting SCHEM_B.SECRET_B_PROC()..."
runsql "$bcreds" "execute SCHEM_B.SECRET_B_PROC();"
echo "TS::$(date): DONE"
runsql
allows you to pass a credential string as the first argument, and any SQL you need as the second argument. The variables containing the credentials are included for illustration, but for security I actually source them from another file. If you wanted to handle multiple database connections, you could easily modify the function to accept the hoststring as an additional parameter.