Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Capture both sql result and status code in shell script 2

Status
Not open for further replies.

akelabanda

Programmer
Dec 19, 2001
61
IN
Hi There

I'm running an sql query from within a shell script.

We use a different exit code to denote SUCCESS (99) rather than 0.

The code is something like this (assuming only 1 row is returned) -
-------------------------------------
temp_percent="set pages 0
set head off
whenever sqlerror exit sql.sqlcode;
select name from Test_table where age=100;
/
exit 99"
age=$(print "${temp_percent}"|sqlplus -s scott/tiger@testdb)
-------------------------------------
My problem is when 'age' gets assigned with the value from the query, the shell would return zero for $? rather than the sql exit code.

Is there a way to get both the result and the exit code from the sql query into the shell script.

Many thanks in advance for your responses.

Rajeev

UK's best mobile deals online
 
How about assigning $? to a variable immediately after the exit from sqlplus. Then you have it saved and can query it as much as you like.
 
Why are you doing it like that, anyway ? Most people use this approach:

Code:
sqlplus -s scott/tiger@testdb << EOF
set pages 0
set head off
whenever sqlerror exit sql.sqlcode;
select name from Test_table where age=100;
/
exit 99
EOF
if [ $? -eq 99 ]
then
...


 
Well, some people claim that sqlplus does not return ZERO for SUCCESS always. So, our guys decided they are going to use 99 as our success code. Lot of other stuff depend on the exit status of 99.

Secondly, in this case, I would also like to store the result of the query in a shell variable.

UK's best mobile deals online
 
This seems to work OK:

var=`sqlplus -s xxxxx/xxxxx@xxxxx << EOF
spool junk.dat
set pages 0
set head off
set feedback off
whenever sqlerror exit sql.sqlcode;
select 'result' from dual
/
spool off
exit 99
EOF
`
if [ $? -eq 99 ]
then
echo $var
else
echo Failed with $?
fi
 
Remember that $(...) opens a subshell, so the returnvalue you got is correct, as the subshell terminated without an error. If you like to return the sqlpluscode you have to tell the subshell to do so:
Code:
#!/bin/ksh
temp_percent="set pages 0
set head off
whenever sqlerror exit sql.sqlcode;
select name from Test_table where age=100;
/
exit 99"
age=$(print "${temp_percent}"|sqlplus -s scott/tiger@testdb ; return $?)

Stefan
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top