Wednesday, June 26, 2013

How to store sqlplus output into a single or multiple variables via ksh script

db_status=`sqlplus -s "/ as sysdba" <<EOF
       set heading off feedback off verify off
       select status from v\$instance;
       exit
EOF`
echo $db_status
The above works for when you want to retrieve a single value. If you want to retrieve multiple values, use:
output=`sqlplus -s "/ as sysdba" <<EOF
       set heading off feedback off verify off
       select host_name, instance_name, status from v\\$instance;
       exit
EOF`

var1=`echo $output | awk '{print $1}'`
var2=`echo $output | awk '{print $2}'`
var3=`echo $output | awk '{print $3}'`
echo $var1
echo $var2
echo $var3
You can also put your sql statement into a file with .sql extension. Something like that:
set head off
set verify off
set feedback off
set pages 0

SELECT field1, field2, field3 
FROM Table1;

exit;
And then read the script values into variables:
sqlplus -s "/ as sysdba" @script2run.sql.sql | read var1 var2 var3

1 comment: