Run sql query from If else block in shell script - sql

I want to connect sql db and execute sql query from shell script. I tried using this
if float_cmp "$size1 > 7.50"; then
echo "### THE DATA SIZE IS GREATER THAN 7.5 GB ###"
echo "############### DROPPING CREATED $IMPUSER USER ###########################"
${PATH_TO_CLIENT}sqlplus $EXPUSER/$EXPPWD#$ENDPOINT<< EOF
drop user $IMPUSER cascade;
exit;
EOF
exit 1
else
echo "### THE DATA SIZE IS OKAY ###"
fi
The statement is working outside if block but throwing error when executing in IF block
line 80: warning: here-document at line 72 delimited by end-of-file (wanted `EOF')
line 81: syntax error: unexpected end of file
Can anyone please tell what am I doing wrong and what is the solution?

Try removing the indentation inside of the here-document:
if float_cmp "$size1 > 7.50"; then
echo "### THE DATA SIZE IS GREATER THAN 7.5 GB ###"
echo "############### DROPPING CREATED $IMPUSER USER ###########################"
"${PATH_TO_CLIENT}"sqlplus $EXPUSER/$EXPPWD#$ENDPOINT<< EOF
drop user $IMPUSER cascade;
exit;
EOF
exit 1
else
echo "### THE DATA SIZE IS OKAY ###"
fi

Related

How to replace SQL with bash variable of SQL command output

I am working on a program in bash that checks for valid JSON files before loading them into a table. The process first runs f_check_valid_json to verify the JSON. This process runs f_exe_sql_stmnt() that returns a column of bad files, stored in variable bad_fl_list. I would like to be able to input bad_fl_list in the WHERE clause of my update and delete sections of the function.
Right now, the SQL fails when there is more than one JSON file ID in bad_fl_list
f_exe_sql_stmnt(){
db=$1
sql_str=$2
psql -d "$db" -Atc "$sql_str"
if [ $? -gt 0 ]
then
echo "======================================================================="
echo "***Error: Database error while executing sql statement($sql_str)..."
exit 123
fi
}
f_check_valid_json() {
echo "*** checking for valid JSON format***"
sql_stmnt="Select json_fl_id from json_stgng where is_valid_json(json_datarec_fl) = false;"
bad_fl_list=$(f_exe_sql_stmnt "$t_db" "${sql_stmnt}")
echo "BAD FILE LIST: ${bad_fl_list}"
if [ ! -z "$bad_fl_list" ]
then
echo "BAD JSON LIST IS NOT EMPTY"
echo "*** updating balancing table to reflect bad file ***"
updt_bal_log_str="UPDATE ${bal_log_tbl} SET trgt_load_stus_cd ='F' where json_fl_id in ($bad_fl_list);"
f_exe_sql_stmnt "$DB" "$updt_bal_log_str"
echo "*** deleting bad JSON file record from staging with file ID: ${bad_fl_list}"
delete_stmnt="delete from ${stg_tbl} where json_fl_id in ($bad_fl_list);"
f_exe_sql_stmnt "$t_db" "${delete_stmnt}"
fi
}
Here is some example output from the logs:
+ psql -d dedw -Atc 'UPDATE json_load_bal_dtl_log SET trgt_load_stus_cd ='\''F'\'' where json_fl_id in (O21181043417
O21181043417
O21181003641);'
ERROR: syntax error at or near "O21181043417"
LINE 2: O21181043417
^

Error while executing Merge through shell script

I am trying to execute a script which calls Merge statement through sqlplus.
The merge statement is executing fine but when I am executing it through shell script, it's giving an error :
current_time=`date`
echo "FSG_PRCB_PRVD_FAC_SEQ table UPDATE STARTED at $current_time"
Result=`sqlplus -s $TgtUsrID/$TgtPswd#$TgtServer <<eof
whenever sqlerror exit sql.sqlcode;
merge into FSG_WRK.FSG_PRCB_FAC_REF_DATA T1
using
(select NUM_ID, ALPHA_NUM_ID from FSG.FSG_PRCB_ADDRESS_CROSSWLK) T2
ON (T1.ADDR_TYPE=T2.ALPHA_NUM_ID)
when matched then
update set T1.ADDR_TYPE_N = T2.NUM_ID ;
eof
`
ERRORCODE=$?
#Check the return code from SQL Plus
if [ $ERRORCODE != 0 ]
then
echo "********************"
echo "ERROR: Updating Status Failed. ErrorCode: $ERRORCODE"
exit -1
else
echo "********************"
echo "UUpdating Status returns $Result"
current_time=`date`
echo "Updating Status Query finished at $current_time"
fi
Output :
updating status failed.Errorcode:174
I am not sure what went wrong.
Using exit sql.sqlcode can be misleading, or even dangerous.
From The Linux Documentation Project:
Out of range exit values can result in unexpected exit codes. An exit value greater than 255 returns an exit code modulo 256. For example, exit 3809 gives an exit code of 225 (3809 % 256 = 225).
You're seeing the exit code reported as 174, but the original error code could have been anything where mod(<actual code>, 256) evaluates to 174. You'll be able to see the actual error code and message in your $Result variable.
A likely candidate is an ORA-00942 error (as mod(942, 256) is 174) - and as you've said the merge works standalone, you'll probably find that the user you're connecting to and running the merge as, represented by $TgtUsrID, does not have the necessary privileges on the tables owned by FSG and/or FSG_WRK.
This shows that the reported exit code can be confusing or misleading. The potentially dangerous part if if you get a real error code which is an exact multiple of 256, such as the plausible ORA-01536 "space quota exceeded for tablespace %s'. As mod(1536, 256) is zero, $ERRORCODE will be zero too, so your check:
if [ $ERRORCODE != 0 ]
will be false even though an error did occur.
It will probably be simpler to change your SQL to have whenever sqlerror exit failure (maybe with the addition of rollback?), and then your check for non-zero will work; and you can use $Result to see/report what was actually wrong.

redirecting sql output to a file in a shell script

I am facing an issue while executing the following script snippet.
$ORACLEHOME/bin/sqlplus -s $DBUSER/$DBPASSWORD <<EOF
set pages 0 feedback off
SELECT * FROM ERR_STG_ROAMING_PARTNER;
EOF > Err_File.txt
The following error message appears.
./Roaming.sh: line 213: warning: here-document at line 206 delimited by end-of-file (wanted `EOF')
./Roaming.sh: line 214: syntax error: unexpected end of file
Any help will be appreciated.
Try this:
$ORACLEHOME/bin/sqlplus -s $DBUSER/$DBPASSWORD > Err_File.txt <<EOF
set pages 0 feedback off
SELECT * FROM ERR_STG_ROAMING_PARTNER;
EOF
That is, specify the output redirection before the input heredoc redirection. The shell expects EOF to be on its own on the line terminating the heredoc.
The error message you are getting is the shell complaining about finding end-of-file (of the script file) before finding EOF. The usage of EOF for the heredoc delimiter might lead to some confusion here!

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 capture sqlplus command line output in unix file

I am running below : sqlplus ABC_TT/asfddd#\"SADSS.it.uk.hibm.sdkm:1521/UGJG.UK.HIBM.SDKM\"
afte that I am executing one stored procedure exec HOLD.TRWER
I want to capture return code of the above stored procedure in unix file as I am running the above commands in unix. Please suggest.
I guess you are looking for spool
SQL> spool output.txt
SQL> select 1 from dual;
1
----------
1
SQL> spool off
Now after you exit. the query/stroed procedure output will be stored in a file called output.txt
If by return code you mean output then:
command > file
If by return code you mean exit status then:
command
echo "$?" > file
If you mean something else, let us know.
You can store command return value in variable
value=`command`
And then checking it's value
echo "$value"
For your case to execute oracle commands within shell script,
value=`sqlplus ABC_TT/asfddd#\"SADSS.it.uk.hibm.sdkm:1521/UGJG.UK.HIBM.SDKM\" \
exec HOLD.TRWER`
I'm not sure about the sql query, but you can get the returned results by using
value=`oraclecommand`.
To print the returned results of oracle command,
echo "$value"
To check whether oracle command or any other command executed successfully, just
check with $? value after executing command. Return value is 0 for success and non-zero for failure.
if [ $?=0 ]
then
echo "Success"
else
echo "Failure"
fi