Unix to Sqlplus - Log the SQL statement about to execute and result of execution - sql

I am on AIX using ksh. Created a unix script which generates the CREATE OR REPLACE VIEW ... and GRANT .. statements, which are placed in a single .txt file. Now I need to execute the contents in the file (there are around 300 view creation and grant statements) in Oracle and I need to log the sql statement that is about to execute and the feedback of Oracle whether the view is created or not..
My excerpt goes as
sqlplus -s username/password#servername <<EOF
SET ECHO ON;
SET NEWPAGE 0;
SET PAGESIZE 0;
SET LINESIZE 200;
SET LONG 10000000;
SET TRIMSPOOL ON;
SET HEADING OFF;
SET FEEDBACK ON;
SET VERIFY ON;
SET TERMOUT OFF;
SET SQLBLANKLINES ON;
SPOOL ${drctry}/${v_timestamp}_sql_execution_log.txt
#${drctry}/${v_date}_sql_statements.txt
SPOOL OFF;
EXIT;
EOF
If the contents of the file _${v_date}sql_statements.txt is
CREATE OR REPLACE VIEW V_TABLE1 AS SELECT * FROM TABLE1;
GRANT SELECT ON V_TABLE1 TO USER1;
...
CREATE OR REPLACE VIEW V_TABLE300 AS SELECT * FROM TABLE300;
GRANT SELECT ON V_TABLE300 TO USER300;
Expected output:
CREATE OR REPLACE VIEW V_TABLE1 AS SELECT * FROM TABLE1;
View created
GRANT SELECT ON V_TABLE1 TO USER1;
Grant succeeded
...
CREATE OR REPLACE VIEW V_TABLE300 AS SELECT * FROM TABLE300;
View created
GRANT SELECT ON V_TABLE300 TO USER300;
Grant succeeded
After some search, noticed List option; But it only records only the last statement that was executed if we have more than 1 statement, which doesn't fit here. In Teradata Bteq the ECHOREQuired attribute can be set to ON for this task. But I am not sure in Oracle. Also tried
sqlplus -s username/password#servername <<EOF > ${drctry}/${v_timestamp}_unix_sql_log.txt But still no luck. Will change the password hardcode once I overcome this issue;

The -s[ilent] option:
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.
So by including the -s flag you are overriding the set echo on directive.
If you omit that then the commands are echoed in the spool file, but (a) you also see the banner on stdout and (b) you see the SQL> prompt and the script name spool off echoed too. You can fix the first part by redirecting output, with the risk you may miss something you care about if there is a problem, by changing your shell command to do:
sqlplus -s username/password#servername >/dev/null <<EOF
And you can partly fix the spooled output by changing the prompt, adding:
SET SQLPROMPT ""
With those changes the shell sees no output, and the spool file contains:
#/path/to/v_date_sql_statements.txt
CREATE OR REPLACE VIEW V_TABLE1 AS SELECT * FROM TABLE1;
View created.
GRANT SELECT ON V_TABLE1 TO USER1;
Grant succeeded.
...
SPOOL OFF;
You could potentially post-process that to remove the first and last line, and (if you want) blank lines. You can also hide the script name by including the text file in the heredoc instead of using start/#:
SPOOL ${drctry}/${v_timestamp}_sql_execution_log.txt
`cat ${drctry}/${v_date}_sql_statements.txt`
SPOOL OFF;

I made a sqplus bash script to do that.
link to github: https://github.com/javierB-/ORACLE.git
It create two files, one with the sql sentences, and the other with the sql sentences and their output.
The script core is:
tee -a $FOUT $FOUT_TRAZA | sqlplus $# | tee -a $FOUT
I use the script throught the alias:
alias sqlpluss='$ADMIN_HOME/oracle/sqlpluss.sh'
it's in spanish, i have traslated the output to write here:
sqlpluss
USE ONLY INTERACTIVELY:
sqlplus enriched to save input and output trace.
Use:
sqlpluss [-f fout] user/password#conection #scripts ...
(fout will be opened in add mode and it will default to yyyymmdd.log)
summary:
tee -a fout | sqlplus $# | tee -a fout
the full script its too long to paste here, but if someone want, i'll do it.

Related

SQL query is returning 0 when running shell script but 6 when checking db

I'm trying to run a shell script that has a SQL query in it. Now, I can't use a SQL script in the shell script because of story requirements. I have been trying to get the shell script to return the correct count which is '6' but it is only returning '0'.
#!/bin/ksh
. /apps/path/config/setenv.ksh
DATE=`date "+%m%d%Y`
returnMessage="`sqlplus username/password#$ORACLE_SID << EOF
WHENEVER OSERROR EXIT SQL.OSCODE ;
WHENEVER SQLERROR EXIT SQL.OSCODE ;
spool /apps/path/data/test.txt
SET HEADING OFF
SET FEEDBACK OFF
SET VERIFY OFF
SET ECHO ON
SET PAGES 0
SET LINESIZE 90
select count(*) from table where dt = to_date('06/18/2020','MM/DD/YYYY');
EOF
`
"
exitCode=$?
oracleError=`echo "$returnMessage" | grep ORA-`
if [ -n "$oracleError" -o "$exitCode" -ne 0 ]; then
log "An error occurred while looking up the $COUNT"
log "SQLPlus Exit Code = $exitCode"
log "SQLPlus Message is: $returnMessage"
return 1
fi
export COUNT=`echo $returnMessage"
return 0
The output is also given below
SQL> SET HEADING OFF
SQL> SET FEEDBACK OFF
SQL> SET VERIFY OFF
SQL> SET ECHO ON
SQL> SET PAGES 0
SQL> SET LINESIZE 90
SQL>
SQL> select count(*) from table where dt = to_date('06/18/2020','MM/DD/YYYY');
0
SQL>
THis is the output and the code I'm using. Not sure where it is going wrong since the query should return 6;
UnCOMMITted data is only visible within the session that created it (and will ROLLBACK at the end of the session if it has not been COMMITted). If you can't see the data from another session (i.e. in SQL*Plus invoked from the shell) then make sure you have issued a COMMIT command in the SQL client where you INSERTed the data.
Note: even if you connect as the same user, this will create a separate session and you will not be able to see the uncommitted data in the other session.
If you have issued a COMMIT and still can't see the data then make sure that both the SQL Client and the shell program are connecting to the same server and the same database and are querying the same user's schema of that database.

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.

Running SQL from Batch File [duplicate]

I write shell script and want to use sqlplus, when I write:
#!/bin/bash
result=$(sqlplus -s user/pass#DB << EOF
set trimspool on;
set linesize 32000;
SET SPACE 0;
SELECT MAX(DNNCMNT_ANSWER_TIME) FROM TKIMEI.DNNCMNT_IMEI_APPRV;
/
exit;
EOF)
echo "$result"
the result is in txt file (I'm executing it as ksh sql.sh > result.txt):
MAX(DNNCM
---------
10-MAR-14
MAX(DNNCM
---------
10-MAR-14
it is automatically putting an empty line at the beginning of file and writing the result twice.
How can I fix it ?
Remove the slash. It's causing the previous command (the select) to be repeated:
http://docs.oracle.com/cd/B10501_01/server.920/a90842/ch13.htm#1006932
Also, talk to your DBA about setting up external OS authentication so you don't have to hardcode the password in a shell script for security reasons. Once set up, you can replace the login/password combo with just a slash:
http://docs.oracle.com/cd/E25054_01/network.1111/e16543/authentication.htm#i1007520

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

I want to copy the output of unix and sqlplus into a file

I am using Solaris. I have to log into sql plus and run some queries, which give a huge result set.
I want to copy all that into a file. Is there any command for it in unix or sqlplus ?
Use the SPOOL command:
SQL> SPOOL /opt/output
SQL> SELECT ...
SQL> SPOOL OFF
setup Oracle environment
(there are ways around specifying username/password on the command line - not the best way especially when other users can 'ps' on the server and see your password)
sqlplus -s username/password <<-!!
set trimspool on trimout on pages 0 feedback off linesize 1000 echo off verify off
spool file.out
select sysdate from dual;
exit
!!
If you are on the command line then just use the > and 2> to redirect stdout and stderr respectively to log files
func > out.log