How do you run a SQL command in a shell script while setting a variable? I had tried this method and it isn't executing the command, it is thinking the command is just a string.
#!/bin/ksh
variable1=`sqlplus -s username/pw@oracle_instance <<EOF
SET PAGESIZE 0 FEEDBACK OFF VERIFY OFF HEADING OFF ECHO OFF
select count(*) from table;
EXIT;
EOF`
if [ -z "$variable1" ]; then
echo "No rows returned from database"
exit 0
else
echo $variable1
fi
#!/bin/ksh
variable1=$(
echo "set feed off
set pages 0
select count(*) from table;
exit
" | sqlplus -s username/password@oracle_instance
)
echo "found count = $variable1"
You can use a heredoc. e.g. from a prompt:
$ sqlplus -s username/password@oracle_instance <<EOF
set feed off
set pages 0
select count(*) from table;
exit
EOF
so sqlplus
will consume everything up to the EOF
marker as stdin.
Maybe it's too late for answering but, there's a working code:
sqlplus -s "/ as sysdba" << EOF
SET HEADING OFF
SET FEEDBACK OFF
SET LINESIZE 3800
SET TRIMSPOOL ON
SET TERMOUT OFF
SET SPACE 0
SET PAGESIZE 0
select (select instance_name from v\$instance) as DB_NAME,
file_name
from dba_data_files
order by 2;
sqlplus -s /nolog <<EOF
whenever sqlerror exit sql.sqlcode;
set echo on;
set serveroutput on;
connect <SCHEMA>/<PASS>@<HOST>:<PORT>/<SID>;
truncate table tmp;
exit;
EOF
Code
PL_CONNECT_STRING="$DB_USERNAME/$DB_PASSWORD@$DB_SERVICE"
OUTPUT=$(sqlplus -s $PL_CONNECT_STRING <<-END-OF-SQL
select count(*) from table;
exit;
END-OF-SQL)
echo "COMPLETED GATHER STATS $OUTPUT";
Explanation:
PL_CONNECT_STRING
carry database username, password and it service name
sqlplus is used to connect the Database with PL_CONNECT_STRING
details
END-OF-SQL
tag contain the query which you want to execute
echo
is used to print the output of the query
NOTE: You can give multiple Query inside the END-OF-SQL
tag, so its useful for batch execution as well