Search code examples
shellunixkshsql-scripts

How to run multiple SQL script files in a Shell script


I have to create 1 UNIX Shell script. In that shell script i want to run multiple SQL script files from the same directory. I have used like this-

#!usr/bin/ksh
SQLPATH = /usr/sql/
(cd $SQLPATH;
'sqlplus usr/password@sid <<EOF
 spool <db_file>.log
 @<db_name>.sql
 set echo off
 set heading off
 spool off
 &&

 spool <db_file2>.log
 @<db_name2>.sql
 set echo off
 set heading off
 spool off
 &&

 spool <db_file3>.log
 @<db_name3>.sql
 set echo off
 set heading off
 spool off
 exit;
 EOF')

exit 0

There are multiple SQL scripts like this and for each SQL script I have to create log files so I used spool here. After every SQL script files execute I used &&. So Is it good to use && here and in 3rd line ; when I define the PATH. Please provide me the better solution.


Solution

  • Don't override the system PATH (or now SQLPATH) and don't put commands in single quotes. Use lowercase for your private variables, and you can't have spaces around the equals sign in an assignment; but a variable you only use once is useless anyway, so I took it out, and hardcoded the cd argument.

    I'm guessing you want something like

    #!/usr/bin/ksh
    
    # No spaces around equals sign, and don't use uppercase for private variables
    # But why use a variable at all anyway
    #sqlpath=/usr/sql
    cd /usr/sql  # is this really necessary and useful??
    
    sqlplus usr/password@sid <<____EOF &&
     spool <db_file>.log
     @<db_name>.sql
     set echo off
     set heading off
     spool off
    ____EOF
    
    sqlplus usr/password@sid <<____EOF &&
     spool <db_file2>.log
     @<db_name2>.sql
     set echo off
     set heading off
     spool off
    ____EOF
    
    sqlplus usr/password@sid <<____EOF
     spool <db_file3>.log
     @<db_name3>.sql
     set echo off
     set heading off
     spool off
    ____EOF
    
    # exit 0  # Not necessary or useful
    

    If the multiple sqlplus commands can be executed in a single session, that would be an obvious improvement; but I'm guessing sqlplus has no way of expressing what you appear to mean with && (this syntax seems to have a quite distinct meaning in sqlplus).