简体   繁体   中英

How to pass a query stored in a variable to a sql file. Shell script

I am creating a shell script where I have saved entries from a text file into an array. Those values are properly stored and show the correct contents. One of those entries contains a simple query and I want to pass it to a sql file. With that sql query I want to save the results into a text file.

Here is the part of the code that calls the sql file to run the sql script

PURGE_SITES=purge_site.txt
logmsg "USERID - $PURGES_SITE" n

QUERY=${Unix_Array[4]}


echo $QUERY
sqlplus -s $USER/$PASS <<EndSQL
     @purges_sites.sql $PURGE_SITES '$QUERY'
     EXIT SQL.SQLCODE
EndSQL

for now query stored in ${Unix_Array[4]} is "select -1 from dual"

Here is the file contents of the .sql file

set echo off ver off feed off pages 0

accept fname prompt 'Loading Sites...'

spool &1;
&2
/
spool off

It gives me error and reads &2 as "&2" instead of the query saved in the variable. However when i edit the .sql file and add something beforehand, it will display the correct data from the variable.

Here is the output

select -1 from dual
File Name===> results.txt
select -1 from dual
Loading Sites...SP2-0042: unknown command "&2" - rest of line ignored.
SP2-0103: Nothing in SQL buffer to run.

Here is the output if I add something before &2.

select -1 from dual
File Name===> results.txt
select -1 from dual
Loading Sites...select * from table_table select -1 from dual
                          *
ERROR at line 1:
ORA-00933: SQL command not properly ended

I typed in select * from table_table before &2. So its actually retrieving the value from the variable but something needs to come beforehand in order to pass correctly.

Is there a system execute command in oracle that will execute a query? &2 just by itself is not allowed.

Wont this help you?

PURGE_SITES=purge_site.txt
logmsg "USERID - $PURGES_SITE" n

QUERY=${Unix_Array[4]}


echo $QUERY
# FRAME YOUR QUERY, PROMPTING USER IN SHELL ITSELF AND SEND TO SQLPLUS DIRECTLY
# BEWARE SQL INJECTION POSSIBLE
# YOU CAN REDIRECT THE SQLPLUS OUTPUT TO A FILE LIKE THIS, NO SPOOL NEEDED
sqlplus -s $USER/$PASS <<EndSQL >> $OUTPUT_FILE
    set echo off ver off feed off pages 0
    $QUERY
    /
    EXIT SQL.SQLCODE
EndSQL

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