How to connect Database and run query inside a shell script? - oracle

I am trying to connect to DB from a shell script, but I am getting below errors for this.
Database output: ERROR:
ORA-12154: TNS:could not resolve the connect identifier specified
SP2-0306: Invalid option.
Usage: CONN[ECT] [logon] [AS {SYSDBA|SYSOPER}]
where ::= [/][#] | /
SP2-0306: Invalid option.
Usage: CONN[ECT] [logon] [AS {SYSDBA|SYSOPER}]
where ::= [/][#] | /
Trail code:
#!/bin/bash
LogDirectory='/users/users-06/p6***8/scripts/dir'
ORACLE_HOME=/tools/ver/oracle-10.2.0.1-64
export ORACLE_HOME
DBUSER='p6*02*1'
DBUSERPASSWORD='R****07'
DB='O**XDA3'
var=`$ORACLE_HOME/bin/sqlplus -S ${DBUSER}/${DBUSERPASSWORD}#${DB} << EOD
spool ${LogDirectory}/query.txt
set linesize 32767
set feedback off
set heading off
SELECT * FROM Omi.ESP_FEED_REQUEST WHERE FEED_NAME='PSAR_TRANSACTION_FEED' AND REQUEST_ID='3694707322503' AND AS_OF='04-Jan-2017' ORDER BY 1 DESC;
spool off
exit;
EOD`
echo $var > ${LogDirectory}/DB_output.txt
Could you please suggest me how I will get the sql output in "var" variable, please? Thanks a lot !

The output of your query is getting spooled at below path
{LogDirectory}/query.txt
var will only have a status of code 1 or 0 . If the statement is executed successfully then var status will be 0 else 1.

It's working fine here:
#!/bin/bash
LogDirectory='/home/oracle'
ORACLE_HOME=/u01/app/oracle/product/11.2.0/dbhome_1
export ORACLE_HOME
DBUSER='scott'
DBUSERPASSWORD='scott'
DB='db11g'
var=`$ORACLE_HOME/bin/sqlplus -S ${DBUSER}/${DBUSERPASSWORD}#${DB} << EOD
spool ${LogDirectory}/query.txt
set linesize 32767
set feedback off
set heading off
select 5 from dual;
exit;
EOD`
echo "Database output: ${var}"
$ ./stack.sh
Database output:
5
Is your database up and running? check:
ps -ef | grep pmon
This will show a process if it's running. When it's not you get the error you're getting:
SQL> shu immediate;
Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> exit
Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
With the Partitioning, Oracle Label Security, OLAP, Data Mining,
Oracle Database Vault and Real Application Testing options
$ ./stack.sh
Database output: ERROR:
ORA-12514: TNS:listener does not currently know of service requested in connect
descriptor
SP2-0306: Invalid option.
Usage: CONN[ECT] [{logon|/|proxy} [AS {SYSDBA|SYSOPER|SYSASM}] [edition=value]]
where <logon> ::= <username>[/<password>][#<connect_identifier>]
<proxy> ::= <proxyuser>[<username>][/<password>][#<connect_identifier>]
SP2-0306: Invalid option.
Usage: CONN[ECT] [{logon|/|proxy} [AS {SYSDBA|SYSOPER|SYSASM}] [edition=value]]
where <logon> ::= <username>[/<password>][#<connect_identifier>]
<proxy> ::= <proxyuser>[<username>][/<password>][#<connect_identifier>]
SP2-0157: unable to CONNECT to ORACLE after 3 attempts, exiting SQL*Plus
edit for XING:
I changed the code to:
select * from t1;
$ ./stack.sh
Database output:
A
B
and select * from user_tables
$ ./stack.sh
Database output:
DEPT USERS VALID 10 1 255 65536 1048576 1 2147483645 YES N 4 5 0 0 0 20 0 0 1 1 N ENABLED 4 07-OCT-14 NO N N NO DEFAULT DEFAULT DEFAULT DISABLED YES NO DISABLED YES DISABLED DISABLED NO NO YES DEFAULT
SALGRADE USERS VALID 10 1 255 65536 1048576 1 2147483645 YES N 5 5 0 0 0 10 0 0 1 1 N ENABLED 5 07-OCT-14 NO N N NO DEFAULT DEFAULT DEFAULT DISABLED YES NO DISABLED YES DISABLED DISABLED NO NO YES DE

echo "SELECT * FROM Omi.ESP_FEED_REQUEST WHERE FEED_NAME='PSAR_TRANSACTION_FEED' AND REQUEST_ID='3694707322503' AND AS_OF='04-Jan-2017' ORDER BY 1 DESC;" | sqlplus -s $DBUSER#$DB/$DBUSERPASSWORD >> dboutput.txt

Related

How to call the filename of running SQL script?

I'm trying to run a series of script files but I would like for each script file to print its filename, for reporting.
So, the intent is to call each SQL file from a general script:
#SQL_File_1;
#SQL_File_2;
#SQL_File_n;
But I need each SQL to print it's results, so I need each to print:
DBMS_OUTPUT.PUT_LINE({Filename} || ' updated ' || {Number of records});
How to retrieve the filename? Can it be easily done?
If you are running SQL*Plus, then it can be done as per the comment but only if you've set APPINFO, eg
SQL> select module from v$session where sid = sys_context('USERENV','SID');
MODULE
----------------------------------------------------------------
SQL*Plus
SQL> host cat x:\temp\myfile.sql
select module from v$session where sid = sys_context('USERENV','SID');
SQL> #x:\temp\myfile.sql
MODULE
----------------------------------------------------------------
SQL*Plus
SQL> SET APPINFO ON
SQL> #x:\temp\myfile.sql
MODULE
----------------------------------------------------------------
01# x:\temp\myfile.sql
That will also work with SQLcl.
I haven't used TOAD for a while but I think it also supports appinfo
The utility executes all sql files in the specified directory and complements the calls to sql files with prompt commands to display the sql file name.
For example input file
C:\upwork\powershell-oracle_git\sql
31.12.2020 11:42 28 SQL_FILE1.sql
31.12.2020 11:42 28 SQL_FILE2.sql
31.12.2020 11:43 28 SQL_FILE3.sql
31.12.2020 11:43 28 SQL_FILE4.sql
31.12.2020 11:43 28 SQL_FILE5.sql
For example output log
SET session NLS_LANG: AMERICAN_AMERICA.CL8MSWIN1251
===========================================================================================
Script start time : 2020-12-31 11:50:11
Found SQL file C:\upwork\powershell-oracle_git\sql\SQL_FILE1.sql
Found SQL file C:\upwork\powershell-oracle_git\sql\SQL_FILE2.sql
Found SQL file C:\upwork\powershell-oracle_git\sql\SQL_FILE3.sql
Found SQL file C:\upwork\powershell-oracle_git\sql\SQL_FILE4.sql
Found SQL file C:\upwork\powershell-oracle_git\sql\SQL_FILE5.sql
-------------------------------------------------------------------------------------------
For example output sqlplus short log, if set termout OFF
SQL*Plus: Release 11.2.0.4.0 Production on Thu Dec 31 11:48:58 2020
Copyright (c) 1982, 2013, Oracle. All rights reserved.
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
SQL> SQL> SQL> SQL> SQL> SQL> SQL> SQL> SQL> SQL> SQL> SQL> SQL> SQL> SQL> SQL>
Session altered.
Elapsed: 00:00:00.00
SQL>
Session altered.
Elapsed: 00:00:00.00
SQL> SQL> SQL> Start script: #C:\upwork\powershell-oracle_git\sql\SQL_FILE1.sql
SQL> SQL> Stop script: #C:\upwork\powershell-oracle_git\sql\SQL_FILE1.sql
SQL> SQL> > --------------------------------------------------------------------------------------------------------
SQL> Start script: #C:\upwork\powershell-oracle_git\sql\SQL_FILE2.sql
SQL> SQL> Stop script: #C:\upwork\powershell-oracle_git\sql\SQL_FILE2.sql
SQL> SQL> > --------------------------------------------------------------------------------------------------------
SQL> Start script: #C:\upwork\powershell-oracle_git\sql\SQL_FILE3.sql
SQL> SQL> Stop script: #C:\upwork\powershell-oracle_git\sql\SQL_FILE3.sql
SQL> SQL> > --------------------------------------------------------------------------------------------------------
SQL> Start script: #C:\upwork\powershell-oracle_git\sql\SQL_FILE4.sql
SQL> SQL> Stop script: #C:\upwork\powershell-oracle_git\sql\SQL_FILE4.sql
SQL> SQL> > --------------------------------------------------------------------------------------------------------
SQL> Start script: #C:\upwork\powershell-oracle_git\sql\SQL_FILE5.sql
SQL> SQL> Stop script: #C:\upwork\powershell-oracle_git\sql\SQL_FILE5.sql
SQL> SQL> > --------------------------------------------------------------------------------------------------------
SQL> SQL> Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
For example sqlplus output full log, if set termout ON
SQL*Plus: Release 11.2.0.4.0 Production on Thu Dec 31 11:50:12 2020
Copyright (c) 1982, 2013, Oracle. All rights reserved.
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
SQL> SQL> SQL> SQL> SQL> SQL> SQL> SQL> SQL> SQL> SQL> SQL> SQL> SQL> SQL> SQL>
Session altered.
Elapsed: 00:00:00.00
SQL>
Session altered.
Elapsed: 00:00:00.00
SQL> SQL> SQL> Start script: #C:\upwork\powershell-oracle_git\sql\SQL_FILE1.sql
SQL> SQL> select 1, sysdate from dual;
1 SYSDATE
---------- -------------------
1 31.12.2020 11:50:09
1 row selected.
Elapsed: 00:00:00.00
SQL> Stop script: #C:\upwork\powershell-oracle_git\sql\SQL_FILE1.sql
SQL> SQL> > --------------------------------------------------------------------------------------------------------
SQL> Start script: #C:\upwork\powershell-oracle_git\sql\SQL_FILE2.sql
SQL> SQL> select 2, sysdate from dual;
2 SYSDATE
---------- -------------------
2 31.12.2020 11:50:09
1 row selected.
Elapsed: 00:00:00.00
SQL> Stop script: #C:\upwork\powershell-oracle_git\sql\SQL_FILE2.sql
SQL> SQL> > --------------------------------------------------------------------------------------------------------
SQL> Start script: #C:\upwork\powershell-oracle_git\sql\SQL_FILE3.sql
SQL> SQL> select 3, sysdate from dual;
3 SYSDATE
---------- -------------------
3 31.12.2020 11:50:09
1 row selected.
Elapsed: 00:00:00.00
SQL> Stop script: #C:\upwork\powershell-oracle_git\sql\SQL_FILE3.sql
SQL> SQL> > --------------------------------------------------------------------------------------------------------
SQL> Start script: #C:\upwork\powershell-oracle_git\sql\SQL_FILE4.sql
SQL> SQL> select 4, sysdate from dual;
4 SYSDATE
---------- -------------------
4 31.12.2020 11:50:09
1 row selected.
Elapsed: 00:00:00.00
SQL> Stop script: #C:\upwork\powershell-oracle_git\sql\SQL_FILE4.sql
SQL> SQL> > --------------------------------------------------------------------------------------------------------
SQL> Start script: #C:\upwork\powershell-oracle_git\sql\SQL_FILE5.sql
SQL> SQL> select 5, sysdate from dual;
5 SYSDATE
---------- -------------------
5 31.12.2020 11:50:09
1 row selected.
Elapsed: 00:00:00.00
SQL> Stop script: #C:\upwork\powershell-oracle_git\sql\SQL_FILE5.sql
SQL> SQL> > --------------------------------------------------------------------------------------------------------
SQL> SQL> Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
This powershell script adds sqlplus command PROMPT sql file names to sql file before call sql script.
<# .SYNOPSIS
This script adds PROMPT sql file names to sql file before call sql script.
Author: Dmitry Demin dmitrydemin1973#gmail.com
.DESCRIPTION
This script adds PROMPT sql file names to sql file before call sql script.
.PARAMETER sql_file_input
Specify the input sql script.
.PARAMETER sql_file_output
Specify the output sql script.
.PARAMETER log_file
Specify the log file.
.EXAMPLE
This script adds PROMPT sql file names to sql file before call sql script.
.\add_prompt_file_names.ps1 -sql_file_input .\sql\start.sql -sql_file_output .\sql\start_prompt.sql -log_file log_file.log
#>
param(
[string]$sql_file_input="C:\upwork\powershell-oracle_git\sql\start.sql",
[string]$sql_file_output="C:\upwork\powershell-oracle_git\sql\start_prompt.sql",
[string]$log_file="log_add_prompt.log"
)
$upper_line = "PROMPT ""Start script: "
$bottom_line = "PROMPT ""---------------------------------------------------------------------------------------------------------"""
$date_time_start = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Write-host "Script start time : $date_time_start "
try
{
echo "Script start time : $date_time_start ">>$log_file
}
catch {
Write-Host "Log File $log_file. Other type of error was found:"
Write-Host "Exception type is $($_.Exception.GetType().Name)"
exit
}
echo "===========================================================================================" | tee-object -Append -filepath $log_file
echo "Input sql file: $sql_file_input" | tee-object -Append -filepath $log_file
echo "Output sql file: $sql_file_output" | tee-object -Append -filepath $log_file
$data_file = Get-Content $sql_file_input
$null | Set-Content -Path $sql_file_output
foreach ($line_file in $data_file)
{
if ($line_file.TrimStart().StartsWith("#"))
{
$start_prompt_line= $upper_line + $line_file.TrimStart().replace("#","") + """"
Out-File -filepath $sql_file_output -append -inputobject $start_prompt_line -encoding default
Out-File -filepath $sql_file_output -append -inputobject $line_file.TrimStart() -encoding default
Out-File -filepath $sql_file_output -append -inputobject $bottom_line -encoding default
}
else
{
Out-File -filepath $sql_file_output -append -inputobject $line_file -encoding default
}
}
For example
C:\upwork\powershell-oracle_git>powershell .\add_prompt_file_names.ps1 -sql_file_input ./sql/start.sql -sql_file_output ./sql/start_output.sql
Script start time : 2021-01-03 16:32:41
============================================================================
Input sql file: ./sql/start.sql
Output sql file: ./sql/start_output.sql
Input file ./sql/start.sql
REM
REM
REM
---
rem start 1
#SQL_FILE1.sql
rem start 2
#SQL_FILE2.sql
rem start 3
#SQL_FILE3.sql
rem start 4
#SQL_FILE4.sql
rem start 5
#SQL_FILE5.sql
REM
REM
---
Output sql file: ./sql/start_output.sql
REM
REM
REM
---
rem start 1
PROMPT "Start script: SQL_FILE1.sql"
#SQL_FILE1.sql
PROMPT "---------------------------------------------------------------------------------------------------------"
rem start 2
PROMPT "Start script: SQL_FILE2.sql"
#SQL_FILE2.sql
PROMPT "---------------------------------------------------------------------------------------------------------"
rem start 3
PROMPT "Start script: SQL_FILE3.sql"
#SQL_FILE3.sql
PROMPT "---------------------------------------------------------------------------------------------------------"
rem start 4
PROMPT "Start script: SQL_FILE4.sql"
#SQL_FILE4.sql
PROMPT "---------------------------------------------------------------------------------------------------------"
rem start 5
PROMPT "Start script: SQL_FILE5.sql"
#SQL_FILE5.sql
PROMPT "---------------------------------------------------------------------------------------------------------"
REM
REM
---

How to connect to Oracle DB using batch file

I am automating a process where I have to connect to Oracle database and run a script automatically.
Can somebody help me in achieving this.
I have written a script but when I am executing the below scripts it's not returning any output.
Code :
#echo off
set user_name=<username>
set password=<password>
set net_service_name= <tns_name>
echo exit | sqlplus -s %user_name%/%password%#%net_service_name% #f:\test.sql
pause
I am using Oracle 11g. I am connecting to database of a specific region.
Also, I need to connect to database as an admin user.
I think the problem is in the space in net_service_name. "-S" is silent mode for sqlplus. For diagnostics, remove this key and add rem #echo off.
For example 1. The space in net_service_name.
rem #echo off
set user_name=scott
set password=tiger
set net_service_name= esmd
echo exit | sqlplus -s %user_name%/%password%#%net_service_name% #C:\upwork\stackoverflow\bat_sql\sqltest.sql
pause
output:
C:\upwork\stackoverflow\bat_sql>echo exit | sqlplus -s scott/tiger# esmd #C:\upwork\stackoverflow\bat_sql\sqltest.sql
Usage: SQLPLUS [ [<option>] [<logon>] [<start>] ]
where <option> ::= -H | -V | [ [-L] [-M <o>] [-R <n>] [-S] ]
<logon> ::= <username>[/<password>][#<connect_string>] | / | /NOLOG
<start> ::= #<URI>|<filename>[.<ext>] [<parameter> ...]
"-H" displays the SQL*Plus version banner and usage syntax
"-V" displays the SQL*Plus version banner
"-L" attempts log on just once
"-M <o>" uses HTML markup options <o>
"-R <n>" uses restricted mode <n>
"-S" uses silent mode
C:\upwork\stackoverflow\bat_sql>pause
For example 2.
rem #echo off
set user_name=scott
set password=tiger
set net_service_name=esmd
echo exit | sqlplus -s %user_name%/%password%#%net_service_name% #C:\upwork\stackoverflow\bat_sql\sqltest.sql
pause
output:
C:\upwork\stackoverflow\bat_sql>echo exit | sqlplus -s scott/tiger#esmd #C:\upwork\stackoverflow\bat_sql\sqltest.sql
SYSDATE
--------
24.01.19
Elapsed: 00:00:00.00
C:\upwork\stackoverflow\bat_sql>pause
For example 3. Connect as sysdba.
rem #echo off
set user_name=sys
set password=manager
set net_service_name=esmd as sysdba
echo exit | C:\oracle\instantclient_11_2\sqlplus.exe -s %user_name%/%password%#%net_service_name% #C:\upwork\stackoverflow\bat_sql\sqltest.sql
pause
output:
C:\upwork\stackoverflow\bat_sql>echo exit | C:\oracle\instantclient_11_2\sqlplus.exe -s sys/manageresmd#esmd as sysdba #C:\upwork\stackoverflow\bat_sql\sqltest.sql
SYSDATE
--------
24.01.19
C:\upwork\stackoverflow\bat_sql>pause
For example 4. Connect as sysdba.
rem #echo off
set user_name=sys
set password=manager
set net_service_name=esmd as sysdba
rem
(
echo conn %user_name%/%password%#%net_service_name%
echo #C:\upwork\stackoverflow\bat_sql\sqltest.sql
echo exit
)| sqlplus -s /nolog
pause
output:
C:\upwork\stackoverflow\bat_sql>(
echo conn sys/manageresmd#esmd as sysdba
echo #C:\upwork\stackoverflow\bat_sql\sqltest.sql
echo exit
) | sqlplus -s /nolog
Connected.
SYSDATE
--------
24.01.19
Elapsed: 00:00:00.00
For example sqltest.sql.
C:\upwork\stackoverflow\bat_sql>more sqltest.sql
select sysdate from dual;

Assign output of an oracle sql query to a variable in shell script

im trying to save the output of a query in a variable. I followed some answers here in stackoverflow but no luck. Currently i'm using this
billerrors=$(sqlplus -s $username/$password#$SID << EOF
set pagesize 0 feedback off verify off heading off echo off;
SELECT ERROR from temp_table
exit;
EOF
)
echo $billerrors
The output i always get is
SQLPlus: Release 11.2.0.1.0 Production Copyright (c) 1982, 2009,
Oracle. All rights reserved. Use SQLPlus to execute SQL, PL/SQL and
SQL*Plus statements.
The output of the above query SELECT ERROR from temp_table will be in the below format
Bill payment errors in the last 30 minutes: XX : 70. YY : 20.
Incase of no bill errors, the output will be
Bill payment errors in the last 30 minutes: 0.
I would really appreciate if someone could help
You use the wrong names in the script of the variable username and password.
If you use the correct names in the script for the variables username and password, then your script must work.
Exapmple 1. Correct names in the script for the variables $username and $password.
#!/bin/sh
username=SCOTT
password=Tiger
## esmd is TNS alias in tnsnames.ora
SID=esmd
echo username: $username
echo password: $password
echo tns: $SID
billerrors=$(sqlplus -s $username/$password#$SID << EOF
set pagesize 0 feedback off verify off heading off echo off;
show user;
SELECT 'Date: '||to_char(sysdate,'DD-MM-YYYY HH24:MI')||' The test is passed' from dual;
exit;
EOF
)
echo $billerrors
oracle#esmd:~> ./test.sh
username: SCOTT
password: Tiger
tns: esmd
USER is "SCOTT" Date: 25-01-2018 08:32 The test is passed
Example 2.
I make an error in the name of the variable $UserName, when I call sqlplus
#!/bin/sh
username=SCOTT
password=Tiger
## esmd is TNS alias in tnsnames.ora
SID=esmd
echo username: $username
echo password: $password
echo UserName: $UserName
echo tns: $SID
billerrors=$(sqlplus -s $UserName/$password#$SID << EOF
set pagesize 0 feedback off verify off heading off echo off;
show user;
SELECT 'Date: '||to_char(sysdate,'DD-MM-YYYY HH24:MI')||' The test is passed' from dual;
exit;
EOF
)
echo $billerrors
oracle#esmd:~> ./test.sh
username: SCOTT
password: Tiger
UserName:
tns: esmd
SQL*Plus: Release 11.2.0.3.0 Production Copyright (c) 1982, 2011, Oracle. All rights reserved. Use SQL*Plus to execute SQL, PL/SQL and SQL*Plus
statements. Usage 1: sqlplus -H | -V -H Displays the SQL*Plus version and the
usage help. -V Displays the SQL*Plus version. Usage 2: sqlplus [ [<option>] [{logon | /nolog}] [<start>] ] <option> is: [-C <version>] [-L] [-M "<options>"]
[-R <level>] [-S] -C <version> Sets the compatibility of affected commands to the version specified by <version>. The version has the form "x.y[.z]".
For example, -C 10.2.0 -L Attempts to log on just once, instead of reprompting
on error. -M "<options>" Sets automatic HTML markup of output. The options have the form: HTML [ON|OFF] [HEAD text] [BODY text] [TABLE text] [ENTMAP {ON|OFF}]
[SPOOL {ON|OFF}] [PRE[FORMAT] {ON|OFF}] -R <level> Sets restricted mode to disable SQL*Plus commands that interact with the file system. The level can be
1, 2 or 3. The most restrictive is -R 3 which disables all user commands
interacting with the file system. -S Sets silent mode which suppresses the
display of the SQL*Plus banner, prompts, and echoing of commands. <logon> is:
{<username>[/<password>][#<connect_identifier>] | / } [AS {SYSDBA | SYSOPER | SYSASM}] [EDITION=value] Specifies the database account username, password and connect identifier for the database connection. Without a connect identifier, SQL*Plus connects to the default database. The AS SYSDBA, AS SYSOPER and AS SYSASM options are database administration privileges. <connect_identifier> can be in the form of Net Service Name or Easy Connect. #[<net_service_name> | [//]Host[:Port]/<service_name>] <net_service_name> is a simple name for a service that resolves to a connect descriptor. Example: Connect to database using Net Service Name and the database net service name is ORCL. sqlplus myusername/mypassword#ORCL Host specifies the host name or IP address of the database server computer. Port specifies the listening port on the database server. <service_name> specifies the service name of the database you want to access. Example: Connect to database using Easy Connect and the Service name is ORCL. sqlplus myusername/mypassword#Host/ORCL The /NOLOG option starts SQL*Plus without connecting to a database. The EDITION specifies the value for Session Edition. <start> is: #<URL>|<filename>[.<ext>] [<parameter> ...] Runs the specified SQL*Plus script from a web server (URL) or the local file system (filename.ext) with specified parameters that will be assigned to substitution
variables in the script. When SQL*Plus starts, and after CONNECT commands, the
site profile (e.g. $ORACLE_HOME/sqlplus/admin/glogin.sql) and the user profile
(e.g. login.sql in the working directory) are run. The files may contain
SQL*Plus commands. Refer to the SQL*Plus User's Guide and Reference for more
information.
Example 3.
I make an error in the name of the variable $Password, when I call sqlplus
#!/bin/sh
username=SCOTT
password=Tiger
## esmd is TNS alias in tnsnames.ora
SID=esmd
echo username: $username
echo password: $password
echo UserName: $UserName
echo Password: $Password
echo tns: $SID
billerrors=$(sqlplus -s $username/$Password#$SID << EOF
set pagesize 0 feedback off verify off heading off echo off;
show user;
SELECT 'Date: '||to_char(sysdate,'DD-MM-YYYY HH24:MI')||' The test is passed' from dual;
exit;
EOF
)
echo $billerrors
oracle#esmd:~> ./test.sh
username: SCOTT
password: Tiger
UserName:
Password:
tns: esmd
SQL*Plus: Release 11.2.0.3.0 Production Copyright (c) 1982, 2011,
Oracle. All rights reserved. Use SQL*Plus to execute SQL, PL/SQL and SQL*Plus
statements. Usage 1: sqlplus -H | -V -H Displays the SQL*Plus version and the
Example 4
I make an error in the name of the variable $Sid, when I call sqlplus
#!/bin/sh
username=SCOTT
password=Tiger
## esmd is TNS alias in tnsnames.ora
SID=esmd
echo username: $username
echo password: $password
echo SID: $SID
echo Sid: $Sid
billerrors=$(sqlplus -s $username/$password#$Sid << EOF
set pagesize 0 feedback off verify off heading off echo off;
show user;
SELECT 'Date: '||to_char(sysdate,'DD-MM-YYYY HH24:MI')||' The test is passed' from dual;
exit;
EOF
)
echo $billerrors
oracle#esmd:~> ./test.sh
username: SCOTT
password: Tiger
SID: esmd
Sid:
SQL*Plus: Release 11.2.0.3.0 Production Copyright (c) 1982, 2011, Oracle. All rights reserved. Use SQL*Plus to execute SQL, PL/SQL and SQL*Plus
Example 5
I make an error in the value of the variable $password=tiger, when I call the sqlplus program
#!/bin/sh
username=SCOTT
## True password is Tiger
password=tiger
## esmd is TNS alias in tnsnames.ora
SID=esmd
echo username: $username
echo password: $password
echo SID: $SID
billerrors=$(sqlplus -s $username/$password#$SID << EOF
set pagesize 0 feedback off verify off heading off echo off;
show user;
SELECT 'Date: '||to_char(sysdate,'DD-MM-YYYY HH24:MI')||' The test is passed' from dual;
exit;
EOF
)
echo $billerrors
oracle#esmd:~> ./test.sh
username: SCOTT
password: tiger
SID: esmd
ERROR: ORA-01017: invalid username/password; logon denied SP2-0306: Invalid
option. Usage: CONN[ECT] [{logon|/|proxy} [AS {SYSDBA|SYSOPER|SYSASM}]
[edition=value]] where <logon> ::= <username>[/<password>]
[#<connect_identifier>] <proxy> ::= <proxyuser>[<username>][/<password>]
[#<connect_identifier>] SP2-0306: Invalid option. Usage: CONN[ECT]
ORACLE after 3 attempts, exiting SQL*Plus
Example 6
I make an error in the value of the variable $SID=esm.
#!/bin/sh
username=SCOTT
password=tiger
## esmd is TNS alias in tnsnames.ora
## True is esmd
SID=esm
echo username: $username
echo password: $password
echo SID: $SID
billerrors=$(sqlplus -s $username/$password#$SID << EOF
set pagesize 0 feedback off verify off heading off echo off;
show user;
SELECT 'Date: '||to_char(sysdate,'DD-MM-YYYY HH24:MI')||' The test is passed' from dual;
exit;
EOF
)
echo $billerrors
oracle#esmd:~> ./test.sh
username: SCOTT
password: tiger
SID: esm
ERROR: ORA-12154: TNS:could not resolve the connect identifier specified
SP2-0306: Invalid option. Usage: CONN[ECT] [{logon|/|proxy} [AS
YSDBA|SYSOPER|SYSASM}] [edition=value]] where <logon> ::= <username>[<username>]
[/<password>][#<connect_identifi>] SP2-0157: unable to CONNECT to ORACLE after 3
attempts, exiting SQL*Plus
Example 7
If the Username is case sensitive.
#!/bin/sh
username=\"Scott\"
password=TigeR
## esmd is TNS alias in tnsnames.ora
SID=esmd
echo username: $username
echo password: $password
echo SID: $SID
billerrors=$(sqlplus -s $username/$password#$SID << EOF
set pagesize 0 feedback off verify off heading off echo off;
show user;
SELECT 'Date: '||to_char(sysdate,'DD-MM-YYYY HH24:MI')||' The test is passed' from dual;
exit;
EOF
)
echo $billerrors
oracle#esmd:~> ./test.sh
username: "Scott"
password: TigeR
SID: esmd
USER is "Scott" Date: 25-01-2018 09:20 The test is passed
oracle#esmd:~> ./test.sh
username: "Scott"
password: TigeR
SID: esmd
USER is "Scott" Date: 25-01-2018 09:23 The test is passed

Error while connecting the sqlplus from shell script

REQ_OUTPUT1=`echo $XXOLA_TOP/log/Inv/xxola_inv_item_conv_int`
echo Connecting in sqlplus
sqlplus -s $1#$TWO_TASK <<+ > $REQ_OUTPUT1
SET VERIFY OFF
WHENEVER SQLERROR EXIT FAILURE ROLLBACK;
SET LINESIZE 500;
SET SERVEROUTPUT ON SIZE 1000000;
SELECT 1 FROM DUAL;
exit;
Above is my code to connect sqlplus from shell program.
But when i am running this i am getting below error..
line 36: warning: here-document at line 29 delimited by end-of-file (wanted `+')
You are not ending the here document properly. Don't use symbols like + for here document delimiters. Use proper meaningful strings.
REQ_OUTPUT1=`echo $XXOLA_TOP/log/Inv/xxola_inv_item_conv_int`
echo Connecting in sqlplus
sqlplus -s $1#$TWO_TASK <<INP > $REQ_OUTPUT1
SET VERIFY OFF
WHENEVER SQLERROR EXIT FAILURE ROLLBACK;
SET LINESIZE 500;
SET SERVEROUTPUT ON SIZE 1000000;
SELECT 1 FROM DUAL;
exit;
INP

Error Handling of SQLPlus from Bash - not working

I have read every relevant link on this issue and similar questions/answers, preveland answer is to first set whenever SQLERROR EXIT SQL.SQLCODE;
Only then do the query, and then inspect the SQL Plus return code using: ERRORCODE=$?
Here is a sample script:
GetAmountOfChunks()
{
export CHUNK_AMOUNT=`sqlplus -s $CONSTR<<SQL
set heading off;
set trim on;
set feed off;
whenever SQLERROR EXIT SQL.SQLCODE;
select 1/0 from dual;
--SELECT COUNT(*) FROM CNV_CHUNKS_PROC_STATUS;
/
SQL`
When ran it debug mode, it gives:
++ sqlplus -s USER/PASS#HOST/DB
+ export 'CHUNK_AMOUNT= select 1/0 from dual
*
ERROR at line 1:
ORA-01476: divisor is equal to zero'
+ CHUNK_AMOUNT=' select 1/0 from dual
*
ERROR at line 1:
ORA-01476: divisor is equal to zero'
+ ERRORCODE=0
+ '[' 0 -ne 0 ']'
As you can see, returned code is 0!
I expected if not 1476, then at least 196 (right most 8 bytes), but not 0 which indicates success!
Please help...
Thanks.
Your ERRORCODE is being set to zero because that's the exit code from the subshell you're running SQL*Plus is, viq the backticks. The exit code of the SQL*Plus process is 196 but you aren't capturing that, and it's not that easy to do that within a heredoc. The stdout from the process - which is what you are capturing - is not that exit code, it's the query and error message being printed. And even if you could capture it, I'm not sure how you'd distinguish between the 196 coming from an error, or from your actual query.
You could do something like running the query in a block that hides the error and prints either a default value or the actual calculated value, or only look at the last line of output and try to interpret that; but you'll still be fighting against it showing the command being run. SQL*Plus has set echo off but that doesn't do anything with an interactive session, which this still is with input redirection.
Another way to go is to create a script file and temporarily store the output:
echo "
set pages 0
set trim on
set feed off
set echo off
whenever SQLERROR EXIT FAILURE
select 1/0 from dual;
--SELECT COUNT(*) FROM CNV_CHUNKS_PROC_STATUS;
exit 0;
" > /tmp/GetAmountOfChunks_$$.sql
sqlplus -s -l $CONSTR #/tmp/GetAmountOfChunks_$$.sql > /tmp/GetAmountOfChunks_$$.out
if [[ $? -eq 0 ]]; then
export CHUNK_AMOUNT=`cat /tmp/GetAmountOfChunks_$$.out`
else
# whatever you want to do on error; show output file? set default?
cat /tmp/GetAmountOfChunks_$$.out
fi
rm -f /tmp/GetAmountOfChunks_$$.sql /tmp/GetAmountOfChunks_$$.out
This creates a (process-specific) .sql file; executes that write the output (minus the statement, via set echo off) to a .out file; checks the SQL*Plus exit code; and if that is zero gets the result from the file.
As you hinted relying on SQL.SQLCODE to detect an error from your shell script is dangerous as you could get an error that wraps to zero, so I've used the generic FAILURE. If you need the real error code you can get it from the output file.
Another approach using a PL/SQL block:
set -f
CHUNK_AMOUNT=`sqlplus -s $CONSTR <<SQL
set heading off;
set trim on;
set feed off;
whenever SQLERROR EXIT FAILURE;
set serveroutput on;
declare
chunk_amount number;
begin
select 1/0 into chunk_amount from dual;
--SELECT COUNT(*) INTO chunk_amount FROM CNV_CHUNKS_PROC_STATUS;
dbms_output.put_line(chunk_amount);
exception
when others then
dbms_output.put_line(sqlcode);
end;
/
exit 0
SQL
exit $?`
ERRORCODE=$?
If the PL/SQL block runs then ERRORCODE will be zero and CHUNK_AMOUNT will be the calculated value if it's successful, or the SQL code if it throws an exception; since that will be negative (-1476 in your example) you can test that to see if it's expected, if you're only expecting positive values.
If the block can't run because of a syntax error or invalid credentials (notice the -l flag I snuck in) then ERRORCODE will be 1 and CHUNK_AMOUNT will have the error text, e.g. ERROR: ORA-12154: TNS:could not resolve the connect identifier... or whatever actually went wrong. The set -f stops a * in the error message being expanded into a file list from the current directory.
Or even more simply and closer to your original:
set -f
CHUNK_AMOUNT=`sqlplus -s $CONSTR <<SQL
set heading off;
set trim on;
set feed off;
whenever SQLERROR EXIT FAILURE;
select 1/0 from dual;
--SELECT COUNT(*) FROM CNV_CHUNKS_PROC_STATUS;
exit 0
SQL
exit $?`
ERRORCODE=$?
and now ERRORCODE is 0 on success and CHUNK_AMOUNT has the calculated value on any error ERRORCODE is 1, you can test that directly, and the actual error is always in CHUNK_AMOUNT - but only as a string, you don't get -1476 this way.

Resources