Getting value from Oracle database table to UNIX variable - sql

I am trying to create a simple script that connects to a oracle database, executes a select query and store the return value into a Unix variable. Below is the script I have created by following this post:
#!/bin/sh
VALUE=`sqlplus -silent $DB_USERNAME/"$PASSWORD"#"(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=$HOST_NAME)(PORT=$DB_PORT)))(CONNECT_DATA=(SID=$DB_SID)))" <<END
set pagesize 0 feedback off verify off heading off echo off
SELECT ID FROM TEST_USERS WHERE USER_NAME=$SAMPLE_USER;
exit;
END`
if [ -z "$VALUE" ]; then
echo "No rows returned from database"
exit 0
else
echo $VALUE
fi
Now when I run this script I am facing error as :
ERROR: ORA-12533: TNS:illegal ADDRESS parameters SP2-0306: Invalid
option. Usage: CONN[ECT] [{logon|/|proxy} [AS {SYSDBA|SYSOPER|SYSASM}]
[edition=value]] where ::=
[/][#] ::=
[][/][#] SP2-0306:
Invalid option. Usage: CONN[ECT] [{logon|/|proxy} [AS
{SYSDBA|SYSOPER|SYSASM}] [edition=value]] where ::=
[/][#] ::=
[][/][#] SP2-0157:
unable to CONNECT to ORACLE after 3 attempts, exiting SQL*Plus
Please let me know where I am doing mistake?

Try with this VALUE variable:
VALUE=`sqlplus $DB_USERNAME/$PASSWORD#//$HOST_NAME:$DB_PORT/$DB_SID`
And, of course, you need to define all variables, you use there before this line

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
^

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.

File name is coming in SQL query output from unix

I have written a simple sh file to retrieve data from Oracle SQL but getting error. Following is my code:
. $HOME/.profile
function assignVariables
{
ID="finapp"
PASS="finapp"
MAIL_BODY_PATH="/rbluat/BACKEND/Finacle/FC10.2.9/app/CDCI_LOGS/"
}
echo $ID
echo $PASS
function getDatatrans
{
TRANID=`sqlplus -s $ID/$PASS#rbluat <<EOF
SELECT DISTINCT TRAN_ID,DTH_INIT_SOL_ID,TRAN_DATE,DEL_FLG FROM TBAADM.DTD WHERE PSTD_FLG='N' AND ENTRY_USER_ID='FIVUSR' and del_flg='N' and tran_date=(select db_stat_date from tbaadm.gct)AND REF_NUM IN (SELECT PYMT_REF_NUM FROM TBAADM.PORD WHERE STATUS IN ('A','H'));
exit;
EOF`
}
assignVariables
getDatatrans
echo $TRANID
I am getting output as :
[YOU HAVE NEW MAIL]
SELECT DISTINCT TRAN_ID,DTH_INIT_SOL_ID,TRAN_DATE,DEL_FLG FROM TBAADM.DTD WHERE PSTD_FLG='N' AND ENTRY_USER_ID='FIVUSR' and del_flg='N' and tran_date=(select db_stat_date from tbaadm.gct)AND REF_NUM IN (SELECT PYMT_REF_NUM FROM TBAADM.PORD WHERE STATUS IN ('A','H')) few.sh test.sh ERROR at line 1: ORA-00942: table or view does not exist
`
Here few.sh and test.sh are the file names present in the current working directory. few.sh is the file where I have written this code. I have no idea how these names are coming. I am working in KSH. I tried googling about it but found no clue.
The output of sqlplus in evaluated in the command
echo $TRANID
When TRANID has a * in it, ksh will show the files it can find.
You should use quotes to avoid evaluation:
echo "$TRANID"
When you are editing you code, you might as well add {} (not needed here, good habit):
echo "${TRANID}"
Likewise:
echo "${ID}"
echo "${PASS}"
...
-s "${ID}/${PASS}#rbluat"

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