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

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

Related

Passing variable into SQL script using BAT file

Here is my dilemma. I cannot get my code to work. I have a batch file which executeS an SQL script. The batch file needs to be able to execute the sql script using the proper variable. Here is my batch file
#echo off
set list= TRA-1000 TRA-1002 TRA-1003 TRA-1004
for %%a in (%list%) do (
#sqlplus gpms/gpms#prod112 #get_tra1098_data.sql outputfilename = %%a
)
#pause
So essentially I am trying to pass the selected item from 'list' into my sql script. Here are the relevant lines of code from my sql file:
spool $(outputfilename).csv
...
where inst.instruction_doc_no in ($(outputfilename))
...
It is not working. How do I get my batch file to properly call my sql file in a loop, each time calling the sql file using the proper item in 'list'?
ps. this is what the sql file would look like if I wasn't trying to automate it:
spool TRA-1000.csv
...
where inst.instruction_doc_no in ('TRA-1000')
...

Create CSV Issue [duplicate]

I am running a file via batch file
Batch File:
sqlplus admin/admin#SERVER #abc.sql > output.txt
SQL File abc.sql:
set PAGESIZE 1000
set LINESIZE 550
set echo off
set head off
set FEEDBACK OFF
select * from S_ABC
exit;
Output.txt:
Connected To:
Oracle Database 11g................................
.
.
.
DATA
.
.
Disconnected from Oracle Database 11g .......
.
.
Please help me remove the extra data, in the starting and end of output.txt file.
-S seems to be what you're looking for;
sqlplus -S admin/admin#SERVER #abc.sql > output.txt
-S[ILENT]
Suppresses all SQL*Plus information and prompt messages, including the command prompt, the echoing of commands, and the banner normally displayed when you start SQL*Plus. If you omit username or password, SQL*Plus prompts for them, but the prompts are not visible. Use SILENT to invoke SQL*Plus within another program so that the use of SQL*Plus is invisible to the user.

Calling SQL*PLUS from UNIX Shell script and print the status message about the query

I want to run a SQL code using shell script and return the message whether the SQL query executed successfully or not. For this I have used unix script given below.
#!/bin/sh
sqlplus -S hr/hr#xe<<EOF
#emp.sql
EOF
var1=$(cat /cygdrive/d/scripts/output.txt | grep -c 'COUNT')
if [ $var1 -ge 1 ];
then
echo "success"
else
echo "failure"
fi
exit;
and emp.sql(called sql file) as
SET ECHO OFF
SPOOL D:\scripts\output.txt
SET LINESIZE 100
SET PAGESIZE 50
SELECT count(*) FROM employees;
SPOOL OFF;
EXIT 0;
When I execute the script I am getting output as
COUNT(*)
----------
107
./script1.sh: line 13: syntax error: unexpected end of file.
I don't know where I should put EOF statement exactly. Also I am not getting the status message whether it is success or failure which I want as output. Please help. Thanks in advance
SPOOL D:\scripts\output.txt Isnt this windows way of referring to a file where as in the shell script you referred to the file as /cygdrive/d/scripts/output.txt. I assume you are using linux shell to execute so I executed your script changing the spool line in sql file. It worked fine.
Edit: Also the \ that you used, for the spooled output.txt path, will cause the sqlplus to terminate. Hence the error line 13: syntax error: unexpected end of file. Perhaps add quotes to the path or use the same file path as you used in shell

How to output oracle sql result into a file in windows?

I tried
select * from users
save D:\test.sql create;
But SQL plus gives me "no proper ended"
How to specify path in oracle sql in windows?
Use the spool:
spool myoutputfile.txt
select * from users;
spool off;
Note that this will create myoutputfile.txt in the directory from which you ran SQL*Plus.
If you need to run this from a SQL file (e.g., "tmp.sql") when SQLPlus starts up and output to a file named "output.txt":
tmp.sql:
select * from users;
Command:
sqlplus -s username/password#sid #tmp.sql > output.txt
Mind you, I don't have an Oracle instance in front of me right now, so you might need to do some of your own work to debug what I've written from memory.
Very similar to Marc, only difference I would make would be to spool to a parameter like so:
WHENEVER SQLERROR EXIT 1
SET LINES 32000
SET TERMOUT OFF ECHO OFF NEWP 0 SPA 0 PAGES 0 FEED OFF HEAD OFF TRIMS ON TAB OFF
SET SERVEROUTPUT ON
spool &1
-- Code
spool off
exit
And then to call the SQLPLUS as
sqlplus -s username/password#sid #tmp.sql /tmp/output.txt
spool "D:\test\test.txt"
select
a.ename
from
employee a
inner join department b
on
(
a.dept_id = b.dept_id
)
;
spool off
This query will spool the sql result in D:\test\test.txt
just to make the Answer 2 much easier, you can also define the folder where you can put your saved file
spool /home/admin/myoutputfile.txt
select * from table_name;
spool off;
after that only with nano or vi myoutputfile.txt, you will see all the sql track.
hope is that help :)
Having the same chore on windows 10, and windows server 2012.
I found the following solution:
echo quit |sqlplus schemaName/schemaPassword#sid #plsqlScript.sql > outputFile.log
Explanation
echo quit | send the quit command to exit sqlplus after the script completes
sqlplus schemaName/schemaPassword#sid #plsqlScript.sql execute plssql script plsqlScript.sql in schema schemaName with password schemaPassword connecting to SID sid
> outputFile.log redirect sqlplus output to log file outputFile.log

Execute SQL from file in bash

I'm trying to load a sql from a file in bash and execute the loaded sql. The sql file needs to be versatile, meaning it cannot be altered in order to make things easy while being run in bash (escaping special characters like * )
So I have run into some problems:
If I read my sample.sql
SELECT * FROM SAMPLETABLE
to a variable with
ab=`cat sample.sql`
and execute it
db2 `echo $ab`
I receive an sql error because by doing a cat the * has been replaced by all the files in the directory of sample.sql.
Easy solution would be to replace "" with "\" . But I cannot do this, because the file needs to stay executable in programs like DB Visualizer etc.
Could someone give me hint in the right direction?
The DB2 command line processor has options that accept a filename as input, so you shouldn't need to load statements from a text file into a shell variable.
This command will execute all SQL statements in the file, with newline treated as the statement terminator:
db2 -f sample.sql
This command will execute all SQL statements in the file, with semicolon treated as the statement terminator:
db2 -t -f sample.sql
Other useful CLP flags are:
-x : Suppress the column headings
-v : Echo the statement text immediately before execution
-z : Tee a copy of all CLP output to the filename immediately following this flag
Redirect stdin from the file.
db2 < sample.sql
In case, you have a variable used in your script and wanted to get it replaced by the shell before executed in DB2 then use this approach:
Contents of File.sql:
cat <<xEOF
insert values(1,2) into ${MY_SCHEMA}.${MY_TABLE};
select * from ${MY_SCHEMA}.${MY_TABLE};
xEOF
In command prompt do:
export MY_SCHEMA='STAR'
export MY_TAVLE='DIMENSION'
Then you are all good to get it executed in DB2:
eval File.sq |db2 +p -t
The shell will replace the global variables and then DB2 will execute it.
Hope it helps.