unix shell script to check result of sql query - shell

I have the code like this
v_use_xref_result=`sqlplus -s $UP <
Select Code_Desc
From Code_Detail
Where Code='UXLOC'
and CODE_TYPE='UXRF'
EOF`
if [ "$v_use_xref_result" == "Y" ]; then
echo "s" else
echo "n"
fi
when I query the same in sql developer I am getting the result as Y for this query Select Code_Desc From Code_Detail Where Code='UXLOC' and CODE_TYPE='UXRF' the datatype of Code_Desc is varchar
but I am unable to check in if condition. i am getting "n" as result for this script.
can anyone help me how to check it in if condition.

As written, the heredoc syntax in your script doesn't seem to be correct. Try saying:
v_use_xref_result=$(sqlplus -s $UP <<EOF
Select Code_Desc
From Code_Detail
Where Code='UXLOC'
and CODE_TYPE='UXRF'
EOF
)

Related

Shell Script: Hive query is not returning the value/result

I've the below code which I'm using to retrieve the hive result, storing it in a variable, doing the comparison and then accordingly printing the message using shell script.
count_students=`/usr/bin/hive -e 'select count(*) from student_records.fresher;'`
echo $count_students
if [ $count_students -gt 0 ]; then
echo "There are students to be grouped."
exit 1
else
echo "There are no students to be grouped."
fi
echo "Student count to check for Freshers is completed."
But the code is not returning anything i.e.:
Actual O/P:
-bash: line 2: [: -ge: unary operator expected
There are no students to be grouped.
Also the echo $count_students is not printing anything.
The hive query gives the result as:
admin$ select count(*) from student_records.fresher;
179
Not getting why the hive is not able to return the result. Bcz of that the query is prompting wrong message. Any help/ suggestion will be really helpful. Thanks to the community.

Is there a hive condition to exit out if the table count is zero or equals a number?

I am using shell to trigger hive and run the queries in hql file where there are more than 10 queries.
My question : Is there a way were we can exit out of hive and return back to shell if my first query returns zero.
For better understanding :
IF select COUNT(*) from mytable is 0 then exit ELSE continue ;
You can move this logic to the shell:
rowcount=$(hive -S -e "select COUNT(*) from mytable")
if [ $rowcount == 0 ] ;then
exit
else echo ok; #run your script here
fi;
Also in Hive you can use assert_true() function to check boolean expression. If False, the script will fail with exception: ASSERT_TRUE(): assertion failed:
select assert_true(COUNT(*)!=0) from mytable

Execute psql query in bash

I have a problem with executing a psql-query in a bash script.
Below is my code.
run_sql(){
sql_sel="$1;";#sql select
table=$2;#table name
for i in "${!GP_SERVER_NAMES[#]}"
do
logmsg "Executing [$sql_sel] on "${GP_SERVER_NAMES[$i]}": " $loglvl;
result_host[$i]=`${PSQL_HOST[$i]}${sql_sel}`;
#result_host[$i]=cleanresult "`$(${PSQL_HOST[$i]} "$tx_fix $sql_sel" 2>&1`");
if [[ `checkresult "${result_host[$i]}"` != 'true' ]]; then
logmsg "Error occured during sql select: Result for "${GP_SERVER_NAMES[$i]}" '${table}': ${result_host[$i]};" '1' '1';
raise_alarm "${GP_SYNC_SQL_ERR}" "${i}" "${table}" "${result_host}";
fi
logmsg "Result for" ${GP_SERVER_NAMES[$i]} " '${table}': ${result_host[$i]}";
done
final_result='true';
for i in "${!result_host[#]}"
do
if [[ `checkresult "${result_host[$i]}"` = 'true' ]]; then
final_result='false';
I am trying to executing the query on many different servers, with the following command
result_host[$i]=${PSQL_HOST[$i]}${sql_sel};
The above variables have the following meaning:
1. result_host[$i] : is an array that holds the i-th result of the sql query.
2. PSQL_HOST[$i] : is the command line psql-statement, including the IP address which is of the form
psql -t -q -h -U password -d database -c
3. $sql_sel : is the sql_statement
When I run the script, I get the following output.
scriptname.sh: line 168: SELECT: command not found
ERROR: syntax error at end of input
LINE 1: SELECT
^
Why is that? Any help, comments or suggestions would be appreciated.

What is wrong with this perl script

Below is the Perl script that I have written
my $COUNT_1;
my $parameter1 = 'PU_CLERK';
$COUNT_1 = `sqlplus -s hr/password\#dbname\#sql_script.sql $parameter1`;
SQL SCRIPT:
select count(*) from employees
where job_id <> '&1'
and salary > 9000
and commission_pct is not null
order by first_name desc
/
exit;
When I run this query by passing the argument &1 it is giving me a string with an error message. But when I run the same query by hardcoding I'm getting the output properly (the count is 15 which is the correct answer).
select count(*) from employees
where job_id <> 'PU_CLERK'
and salary > 9000
and commission_pct is not null
order by first_name desc
/
exit;
I'm not able to understand where I'm going wrong. How do I pass parameters in Perl. We used to do the same way in shell script and it was working absolutely fine.
EDIT:
This is the error message im getting
perl call_sql.pl
value of first variable isold 2: whe
re job_id <> '&1'
new 2: where job_id <> 'PU_CLERK'
15
So its basically not printing the 15 value its printing all those string also when i use '&1' in my sql script
EDIT2:
Hi Guys finally it is working. In my sql code instead of giving '&1' i gave '$1' Now i want to know is $1 of some significance in Perl? Thanks..
I don't know the answer to your current problem, but using the DBI module is the better solution, so I wrote a sample script to get you started. You may need to tweak some things to get it to work.
use strict;
use warnings;
use DBI;
my $dbname = "mydb";
my $user = "foo";
my $passwd = "bar";
my $dbh = DBI->connect("dbi:Oracle:$dbname", $user, $passwd)
or die $DBI::errstr;
my $parameter1 = 'PU_CLERK';
my $statement = "select count(*) from employees
where job_id <> ?
and salary > 9000
and commission_pct is not null
order by first_name desc";
my $sth = $dbh->prepare($statement) or die $dbh->errstr;
$sth->execute($parameter1) or die $sth->errstr;
while (my $row = $sth->fetchrow_arrayref) {
print "#$row"; # or whatever you want to do with it
}
$dbh->disconnect or warn $dbh->errstr;
This has nothing with perl.
Proof: make an shell script, say mytest.sh with the next content:
#!/bin/bash
echo "$0: Got $# args" >&2 #to stderr
i=0
for arg
do
let i++
echo "$0: arg($i)=$arg=" >&2 #to stderr
done
echo "15" #result to stdout
make it executable, with chmod 755 mytest.sh
Now modify your perl script as:
my $COUNT_1;
my $parameter1 = 'PU_CLERK';
$COUNT_1 = `./mytest.sh -s hr/password\#dbname\#sql_script.sql $parameter1`;
print "script returned: $COUNT_1\n";
run it
$ perl script.pl
result:
./mytest.sh: Got 3 args
./mytest.sh: arg(1)=-s=
./mytest.sh: arg(2)=hr/password#dbname#sql_script.sql=
./mytest.sh: arg(3)=PU_CLERK=
script returned: 15
e.g. the perl
correctly run the external script
correctly passes the arguments to it
so, search for the error in the sqlplus doccumentation...

Check if value within column exists, if not create the column

I need to check if one of the columns in my db contains specific value. If it doesn't I want to create that row with folowing values:
#!/bin/bash
#
MODEL=$1
if true (SELECT * FROM table.STATISTICS
WHERE MODEL = '$MODEL' )
do this (INSERT INTO table.STATISTICS('$MODEL',0,SYSDATE,0,SYSDATE,0); )
You could use a merge for this, run through SQL*Plus as a 'heredoc', so you don't have to do a separate count operation; the merge will do that for you effectively:
#!/bin/bash
MODEL=$1
sqlplus -s /nolog <<!EOF
connect user/pass
merge into statistics s
using (select '${MODEL}' as model, 0 as num1, sysdate as date1,
0 as num2, sysdate as date2 from dual) t
on (s.model = t.model)
when not matched then
insert (s.model, s.num1, s.date1, s.num2, s.date2)
values (t.model, t.num1, t.date1, t.num2, t.date2);
!EOF
But using your real column names, obviously. It's better to list them explicitly even for a plain insert.
get_count () {
sqlplus -s username/pass <<!
set heading off
set feedback off
set pages 0
select count(model) from statistics
where model='$MODEL';
!
}
count=$(get_count $1)
if [ "${count:-0}" -eq 0 ]; then
echo "its zero"
sqlplus -S username/pass << EOF
whenever sqlerror exit 1;
set echo on
set verify off
INSERT INTO table.STATISTICS VALUES('$MODEL',0,SYSDATE,0,SYSDATE,0);
exit;
EOF
fi

Resources