Call sql procedure through a shell script and email if error - sql

I wish to write a shell script that calls a sql procedure(ultimately run the script through a scheduler) and if the procedure gives an sql error of any kind, send the error as an email which i wish to specify inside the script.
How can I do it?
EDIT: Here is what I tried. I cannot figure out how to put the logic that send email only if there is error.
export ORACLE_HOME=/oracle/app/products/11gr1/db
export ORACLE_SID=CTPP01S1
MAIL_TO="xxx#yyy.com"
LOGFILE=./xxx_job.log
exec 2>&1 > $LOGFILE
echo " Job run at: `date`......"
$ORACLE_HOME/bin/sqlplus -s '/ as sysdba' <<EOF
set head on;
set feed on;
set serveroutput on;
set linesize 250;
set pagesize 1000;
exec schema.proc_name;
exit
EOF
echo "Job ended at: `date`"
mailx -s "OLBB Extract Results." $MAIL_TO < $LOGFILE

If you want to send the mail from Oracle then utl_mail is your friend. As #Tony noted you didn't specify your platform, but in Linux there's mail and in Unix both of which you can pass the output of your execution to.
In any environment you can execute your SQL in a wrapper such as Python (I'm biased) and mail from that.

Related

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.

Unable to pass in parameters to SQL Server Stored procedure from Windows batch script

I tried searching for the solution here but didn't find one that can solve my problem. I have following batch script:
for /f "tokens=1-3 delims=, " %%a in ('\path\batch_output.txt') do (
echo %%a, %%b, %%c
sqlcmd -S server -E -i path\spu_update_src_trg_ref.sql -v SourceName= %%a Instancname= %%b exitcode= %%c
ping 1.1.1.1 -n 1 -w 5000 > nul
)
Inside spu_update_src_trg_ref.sql I have below code:
use dbname
go
EXEC dbo.spu_update_src_trg_ref $(SourceName), $(Instancname), $(exitcode)
I am running the below batch script via a job scheduler so unable to see the direct error in the cmd. But my job is getting failed and the stored proc is also not getting executed. If need, stored proc is as below:
CREATE PROCEDURE dbo.spu_update_src_trg_ref
#SourceName VARCHAR(100),
#Instancname VARCHAR(100),
#exitcode INT
AS
BEGIN
IF #exitcode=0
BEGIN
UPDATE dbo.t_ctrm_ref_src_trg SET LoadStatus='Completed' WHERE SourceTableName=#SourceName;
UPDATE dbo.t_ctrm_instance_status SET InstanceStatus='Completed' WHERE InstanceName=#Instancname;
END
END
Its a simple sp that updates two tables, but I am unable to pass the input parameters from batch script. Please advice.
Update:
Thanks everyone for the help. I just removed some spaces and quotes('') from '\path\batch_output.txt' and it worked just fine. Appreciate all your help
There are syntax errors in your sqlcmd command. Remove the spaces between the var name, the equal sign, and the value in the "-v" portion.

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

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.

Suppress SQL*PLUS error in batch script

I have a script db.bat as below:
#echo off
setlocal enabledelayedexpansion
for /F "tokens=*" %%A in (user.txt) do (
sqlplus -s %%A #fetch.sql >> output.txt
)
where user.txt (list of all user details for which I need expiry date. this list may have around 40-50 rows) is:
dbuser/password#database1
readuser/p#ssw0rd#database1
adminuser/Pa$$word#database2
.......
.......
.......
and fetch.sql is:
set pagesize 20
set linesize 200
select username, expiry_date from user_users;
exit;
The problem I am facing here is, whenevey my script db.bat encounters any SQL ERRORS like given below, its not moving further and getting hanged at that point until I manually stop that.
SQL ERRORs:
ERROR:
ORA-12154: TNS:could not resolve the connect identifier specified
ERROR:
ORA-28000: the account is locked
I have checked that there is a WHENEVER SQLERROR command that works in this situation but don't know how I can use it here.
For those kinds of errors, SQL*Plus is 'hanging' at a username prompt, as it hasn't been able to connect. You don't see that because of the -s flag. By default it will allow three attempts, which is useful when running interactively, but isn't helpful when run from a script like this. You can make it exit after the failed login with the -l 'logon' option:
sqlplus -s -l %%A #fetch.sql >> output.txt
Try this, when using the fetch.sql in a script, you need to set the termout to off.
The error is still there, only that your script will continue to execute after it.
set pagesize 20
set linesize 200
whenever sqlerror continue
set termout off
select username, expiry_date from user_users;
exit;

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