简体   繁体   中英

spool multiple files in loop of shell script

I am trying to spool multiple files to reduce the manual work.

The SQL file (spool_csv.sql) have a select statement which i need to spool as a CSV file like below

set colsep ','
set linesize 9999
set trimspool on
set heading on
set pagesize 0 embedded on
set wrap off
set feedback off
set newpage 0
set verify off
set arraysize 5000
SET TERMOUT OFF
spool C:\Users\spool_csv\csv_03\csv_file_03-jan_&1..csv
select * from CRAFT_MVT_H where code = '&1';
spool off;
exit;

and then i have simple shell script (spool_csv.sh) which is looping through a file to pass parameter to SQL file and to change the name of spool file on runtime and also for where clause of SELECT statement.

for line in `cat chartfield1_03.txt`
do
  echo $line
  sqlplus -s user/password@SID @spool_03.sql $line
done 

chartfield1_03.txt contains --

778
769
741 
728
739
759
737
752
710
734
747

i need to have separate csv file for each line (say value) of chartfield1_03.txt

so it will be like

csv_file_03-jan_778.csv
csv_file_03-jan_769.csv
csv_file_03-jan_741.csv
and so on....

but when i run the shell script it only creating one CSv file that is for last line of chartfield1_03.txt ie csv_file_03-jan_747.csv

i am not sure why other file are not creating while i am passing the spool file as parameter and calling it in a loop so each time it should open a new SQL session and create the new spool file.

Please help me understand what i am missing here !!

So in the end i found out why it was not working as i missed to EOF in SQLPLUS command after adding this as below it is working fine.

Solution as i find it.

#!/bin/bash

for line in `cat chartfield1_03.txt`
do
  echo $line
  dt1 = `sqlplus -s HEW/hew_dba14@DEVHEW<<EOF
  whenever sqlerror exit sql.sqlcode;
  @spool_03.sql $line;
EOF` &

done

One possible solution is to create on each sqlplus execution the same file and rename it in shell. For this you can change line:

spool C:\Users\spool_csv\csv_03\csv_file_03-jan_&1..csv

to be

spool C:\Users\spool_csv\csv_03\csv_file_03-jan_..csv

and in shell script:

sqlplus -s user/password@SID @spool_03.sql $line

to be

sqlplus -s user/password@SID @spool_03.sql 
mv "C:\Users\spool_csv\csv_03\csv_file_03-jan_..csv" "C:\Users\spool_csv\csv_03\csv_file_03-jan_${line}.csv"

My solution.

please provide any other solution if you have in your mind :)

#!/bin/bash

for line in `cat chartfield1_03.txt`
do
  echo $line
  dt1 = `sqlplus -s HEW/hew_dba14@DEVHEW<<EOF
  whenever sqlerror exit sql.sqlcode;
  @spool_03.sql $line;
EOF` &

done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM