Execsqlstatement1="select
'ZZZ|'
||count(*) total
from table1"
$ORACLE_HOME/bin/sqlplus user/tneal01 << Eossql
set lines 80
set pages 50000
set timing on
spool /user/tneal01/SPOOL/output.`date +%Y-%m-%d`.tmp
$Execsqlstatement1
/
spool off
quit;
Eossql
出力ファイルの結果以外に何も必要ない場合は、スクリプトで次のようにすることができます。
grep 'ZZZ' $OutPutDir/$OutPutFile.$today.tmp|cut -d"|" -f2- >$OutPutDir/$OutPutFile.$today.txt
これが機能する理由の完全な例を次に示します。
#!/bin/ksh
today=`date "+%Y-%m-%d"`
OutPutDir="/users/ttead01/SPOOL"
OutPutFile="output"
#add sql statements here
Execsqlstatement1="select
'ZZZ|'
||count(*) total
from users"
#adding connection details here
$ORACLE_HOME/bin/sqlplus tead01/rangers $SQLPLUS -s / << Eossql
set lines 80
set pages 50000
set timing on
spool /users/ttead01/SPOOL/output.`date +%Y-%m-%d`.tmp
$Execsqlstatement1;
spool off
quit;
Eossql
#check to make sure no ORA errors in the query
grep "ORA-" $OutPutDir/$OutPutFile.$today.tmp
if [ $? -eq 0 ]
then
echo "LOG MESSAGE sql select failed"
exit 1
fi
#Seach for ZZZ and cut out junk and send only result to a .txt file
grep 'ZZZ' $OutPutDir/$OutPutFile.$today.tmp|cut -d"|" -f2- >$OutPutDir/$OutPutFile.$today.txt
#Remove the .tmp file if .txt was created
if [ $? -eq 0 ]
then
/usr/bin/rm -f $OutPutDir/$OutPutFile.$today.tmp
else
exit 1
fi
テストのために:
bash-3.2$ test.sh
Copyright (c) 1982, 2010, Oracle. All rights reserved.
SQL> set autocommit on;
SQL> rem set linesize 132;
SQL> define _editor = vi
SQL> alter session set nls_date_format = 'YYYYMMDD HH24MISS';
Session altered.
SQL> SQL> SQL> SQL> SQL> 2 3 4 5 6 7 8
TOTAL
--------------------------------------------
ZZZ|32
Elapsed: 00:00:00.17
出力された .txt ファイルを見てみましょう。
bash-3.2$ cat output.2016-05-28.txt
32
bash-3.2$