How to call the filename of running SQL script? - oracle

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
---

Related

How to check the Success Or Failed status of the External job Via oracle Apex

My database version is R11.2 and Apex 19.2.I am calling a external job(shell script) using DBMS_SCHEDULER.All are working fine.my issue is that how to get the status of the external job(shell script:0-success 1-Error) in oracle apex page and is it possible to download the external shell script log file or display log message of external shell script in same apex page?
The query SELECT * FROM dba_scheduler_job_log WHERE job_name = 'MYJOBNAME' showing "SUCCEEDED" even the external job failed.
DBMS_SCHEDULER.CREATE_JOB(
job_name => 'APEXDATA.myJobName',
job_type => 'EXECUTABLE',
job_action => '/tmp/1.sh',
enabled => FALSE,
repeat_interval => NULL);
Executing below command from Apex page
begin
dbms_scheduler.run_job(job_name => 'APEXDATA.myJobName', use_current_session=> TRUE);
end;
The EXECUTABLE type of DBMS_SCHEDULER needs the credential name of the user who runs the shell script. As long as the shell script is handling the error, the API of the Scheduler will exit with error. But you won't get the error itself of the script, but a generic message of DBMS_SCHEDUELER.
Let me show you with a 12.2 and type EXTERNAL_SCRIPT
SQL> select credential_name from dba_credentials ;
CREDENTIAL_NAME
--------------------------------------------------------------------------------
ORA_FTPFDM
ORA_FTPCPL
SQL> begin
2 dbms_scheduler.create_job ( job_name => 'MY_TEST' , job_type => 'EXTERNAL_SCRIPT' , job_action => '/home/ftpcpl/test.sh' ,
3 credential_name => 'ora_ftpcpl' , enabled => false );
4* end;
SQL> /
PL/SQL procedure successfully completed.
SQL> ! vi /home/ftpcpl/test.sh
SQL> host chmod +x /home/ftpcpl/test.sh
SQL> host cat /home/ftpcpl/test.sh
#!/bin/bash
var=1
echo $var
# control error
return=$?
if [[ $return -eq 0 ]]; then exit 0; else exit 99; fi
We run the script from sqlplus and it works, as well as the scheduler job
SQL> host /home/ftpcpl/test.sh
1
SQL> host echo $?
0
SQL> exec dbms_scheduler.run_job ( 'MY_TEST' ) ;
PL/SQL procedure successfully completed.
Now let's change the script again to force an error.
SQL> host cat /home/ftpcpl/test.sh
#!/bin/bash
var=1
echo $var
# control error
return=99
if [[ $return -eq 0 ]]; then exit 0; else exit 99; fi
SQL> host vi /home/ftpcpl/test.sh
SQL> host /home/ftpcpl/test.sh
1
SQL> exec dbms_scheduler.run_job ( 'MY_TEST' ) ;
BEGIN dbms_scheduler.run_job ( 'MY_TEST' ) ; END;
*
ERROR at line 1:
ORA-27369: job of type EXECUTABLE failed with exit code: Cannot assign
requested address
ORA-06512: at "SYS.DBMS_ISCHED", line 238
ORA-06512: at "SYS.DBMS_SCHEDULER", line 568
ORA-06512: at line 1
Conclusion: DBMS_SCHEDULER using job types EXECUTABLE or EXTERNAL_SCRIPT ( 12c onwards ) relays in the subsystem in charge to run the job. In this case the STDERR or standard error from Linux is giving back the error to the Scheduler API.
I was myself in a situation where APEX is triggering jobs run by the DBMS_SCHEDULER. In order to show the real error, I designed a process to upload the logfile to a table and parsing the column in order to deliver the log message to the APEX front end. To make it user-friendly,so to speak.

UNIX: log into DB in SQLPLUS on background, use that background conection for query execution

Is it possible in Unix to login Oracle DB via sqlplus (everything in bash), stay connected (just login into DB, don't execute any query) in background and use that process (connection) in other processes to execute SQL queries?
So use that connection as "pipe" to Oracle?
Example 1.
You can run script pipe.sh in the background. And in another session, send sql files or sql. With reconnect after run sql.
more pipe.sh
#!/bin/bash
rm /tmp/sqlplus_pipe.sql
mknod /tmp/sqlplus_pipe.sql p
while :
do
$ORACLE_HOME/bin/sqlplus "system/manager" <<EOF
#/tmp/sqlplus_pipe.sql
EOF
sleep 1
done
run this script in backgroud
nohup ./pipe.sh >pipe_log.log 2>&1 &
In other bash session you can send sql file or sql to this backgroud process.
oracle#esmd:/tmp> cat test2.sql >>/tmp/sqlplus_pipe.sql
oracle#esmd:/tmp> cat test2.sql >>/tmp/sqlplus_pipe.sql
oracle#esmd:/tmp> echo "select to_char(sysdate,'DD-MM-YYYY HH24:MI:SS') from dual;" >>/tmp/sqlplus_pipe.sql
oracle#esmd:/tmp> echo "select to_char(sysdate,'DD-MM-YYYY HH24:MI:SS') from dual;" >>/tmp/sqlplus_pipe.sql
oracle#esmd:/tmp> more test2.sql
select to_char(sysdate,'DD-MM-YYYY HH24:MI:SS') from dual;
oracle#esmd:~> more pipe_log.log
SQL*Plus: Release 11.2.0.3.0 Production on Thu Aug 8 14:50:35 2019
Copyright (c) 1982, 2011, Oracle. All rights reserved.
Connected to:
Oracle Database 11g Release 11.2.0.3.0 - 64bit Production
SQL>
TO_CHAR(SYSDATE,'DD
-------------------
08-08-2019 14:50:46
SQL> Disconnected from Oracle Database 11g Release 11.2.0.3.0 - 64bit Production
SQL*Plus: Release 11.2.0.3.0 Production on Thu Aug 8 14:50:47 2019
Copyright (c) 1982, 2011, Oracle. All rights reserved.
Connected to:
Oracle Database 11g Release 11.2.0.3.0 - 64bit Production
SQL>
TO_CHAR(SYSDATE,'DD
-------------------
08-08-2019 14:50:48
SQL> Disconnected from Oracle Database 11g Release 11.2.0.3.0 - 64bit Production
SQL*Plus: Release 11.2.0.3.0 Production on Thu Aug 8 14:50:49 2019
Copyright (c) 1982, 2011, Oracle. All rights reserved.
Connected to:
Oracle Database 11g Release 11.2.0.3.0 - 64bit Production
SQL>
TO_CHAR(SYSDATE,'DD
-------------------
08-08-2019 14:50:49
SQL> Disconnected from Oracle Database 11g Release 11.2.0.3.0 - 64bit Production
Update.
Example 2.
You can run script pipev2.sh in the background on the Oracle database server. And in another session, send sql files or sql. Without reconnect after run sql.
nohup ./pipev2.sh >output.log 2>&1 &
#!/bin/bash
rm /home/trs/db2Toora/sql/sqlplus_pipe.sql
mknod /home/trs/db2Toora/sql/sqlplus_pipe.sql p
$ORACLE_HOME/bin/sqlplus "system/manager" <<EOF
SET SERVEROUTPUT ON
BEGIN
RUN_SQL;
END;
/
EOF
CREATE OR REPLACE DIRECTORY TEMP_DIR_CHANGE AS '/home/trs/db2Toora/sql'
/
GRANT READ ON DIRECTORY TEMP_DIR_CHANGE TO SYSTEM
/
GRANT WRITE ON DIRECTORY TEMP_DIR_CHANGE TO SYSTEM
/
CREATE OR REPALCE PROCEDURE RUN_SQL
is
sql_text VARCHAR2(2000);
file_sql_name VARCHAR2(100):='sqlplus_pipe.sql';
sql_delimiter VARCHAR2(1):=';';
stop_script VARCHAR2(10):='%QUIT%';
sql_output VARCHAR2(2000);
InFile utl_file.file_type;
vNewLine VARCHAR2(4000);
k pls_integer :=0;
BEGIN
dbms_output.enable;
while k <>1
loop
InFile := utl_file.fopen('TEMP_DIR_CHANGE', file_sql_name,'r');
LOOP
BEGIN
utl_file.get_line(InFile, vNewLine);
if vNewLine like '%'||sql_delimiter||'%' then
sql_text:=sql_text||vNewLine;
dbms_output.put_line(sql_text);
begin
execute immediate replace(sql_text,sql_delimiter,'' ) into sql_output;
EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line('!---!--Error--!---!');
dbms_output.put_line(substr(sqlerrm, 1, 500));
end;
dbms_output.put_line(sql_output);
dbms_output.put_line('---------------------------------------------------------------');
sql_text:='';
elsif vNewLine like stop_script then
dbms_output.put_line('---!--QUIT--!---');
EXIT;
else
sql_text:=sql_text||vNewLine;
end if;
EXCEPTION
WHEN NO_DATA_FOUND THEN
EXIT;
END;
END LOOP;
if vNewLine like stop_script then
exit;
end if;
end loop;
utl_file.fclose(InFile);
END;
Test
oracle#esmd:/home/trs/db2Toora/sql> cat test2.sql >sqlplus_pipe.sql
oracle#esmd:/home/trs/db2Toora/sql> cat test2.sql >sqlplus_pipe.sql
oracle#esmd:/home/trs/db2Toora/sql> cat test2.sql >sqlplus_pipe.sql
oracle#esmd:/home/trs/db2Toora/sql> cat test2.sql >sqlplus_pipe.sql
oracle#esmd:/home/trs/db2Toora/sql> cat test2.sql >sqlplus_pipe.sql
oracle#esmd:/home/trs/db2Toora/sql> cat test2.sql >sqlplus_pipe.sql
oracle#esmd:/home/trs/db2Toora/sql> cat test2.sql >sqlplus_pipe.sql
oracle#esmd:/home/trs/db2Toora/sql> cat test2.sql >sqlplus_pipe.sql
oracle#esmd:/home/trs/db2Toora/sql> cat test2.sql >sqlplus_pipe.sql
oracle#esmd:/home/trs/db2Toora/sql> cat test2.sql >sqlplus_pipe.sql
oracle#esmd:/home/trs/db2Toora/sql> cat test2.sql >sqlplus_pipe.sql
oracle#esmd:/home/trs/db2Toora/sql> cat test2.sql >sqlplus_pipe.sql
oracle#esmd:/home/trs/db2Toora/sql> echo 'QUIT' >sqlplus_pipe.sql
oracle#esmd:/home/trs/db2Toora/sql>
oracle#esmd:/home/trs/db2Toora/sql> more test2.sql
select to_char(sysdate,'DD-MM-YYYY HH24:MI:SS')
from dual
;
select to_char(sysdate,'DD-MM-YYYY HH24:MI')
from dual
;
nohup: ignoring input
SQL*Plus: Release 11.2.0.3.0 Production on Tue Aug 13 10:11:23 2019
Copyright (c) 1982, 2011, Oracle. All rights reserved.
Connected to:
Oracle Database 11g Release 11.2.0.3.0 - 64bit Production
SQL> SQL> 2 3 4 select to_char(sysdate,'DD-MM-YYYY HH24:MI:SS') from dual;
13-08-2019 10:11:34
---------------------------------------------------------------
select to_char(sysdate,'DD-MM-YYYY HH24:MI') from dual;
13-08-2019 10:11
---------------------------------------------------------------
select to_char(sysdate,'DD-MM-YYYY HH24:MI:SS') from dual;
13-08-2019 10:11:35
---------------------------------------------------------------
select to_char(sysdate,'DD-MM-YYYY HH24:MI') from dual;
13-08-2019 10:11
---------------------------------------------------------------
select to_char(sysdate,'DD-MM-YYYY HH24:MI:SS') from dual;
13-08-2019 10:11:35
---------------------------------------------------------------
select to_char(sysdate,'DD-MM-YYYY HH24:MI') from dual;
13-08-2019 10:11
---------------------------------------------------------------
select to_char(sysdate,'DD-MM-YYYY HH24:MI:SS') from dual;
13-08-2019 10:11:36
---------------------------------------------------------------
select to_char(sysdate,'DD-MM-YYYY HH24:MI') from dual;
13-08-2019 10:11
---------------------------------------------------------------
select to_char(sysdate,'DD-MM-YYYY HH24:MI:SS') from dual;
13-08-2019 10:11:36
---------------------------------------------------------------
select to_char(sysdate,'DD-MM-YYYY HH24:MI') from dual;
13-08-2019 10:11
---------------------------------------------------------------
select to_char(sysdate,'DD-MM-YYYY HH24:MI:SS') from dual;
13-08-2019 10:11:37
---------------------------------------------------------------
select to_char(sysdate,'DD-MM-YYYY HH24:MI') from dual;
13-08-2019 12:19
---------------------------------------------------------------
---!--QUIT--!---
PL/SQL procedure successfully completed.
SQL> Disconnected from Oracle Database 11g Release 11.2.0.3.0 - 64bit Production

call a procedure with date parameter in sqlplus oracle using shell script

I want to call a procedure in sqlplus oracle using shell script,
my procedure name is getdate_proc with two parameters, startdate and enddate.
I want to set startdate = sysdate and enddate = sysdate + 5 days
for example :execute getdate_proc(to_date('05/05/2015', 'MM-DD-YYYY'),to_date('05/09/2015','MM-DD-YYYY'))
below is my code:
#!/usr/bin/ksh
sqlplus -s /nolog << EOF
connect scott/tiger
--execute procedure with parameter
execute getdate_proc(to_date(sysdate, 'MM-DD-YYYY'),to_date(sysdate + 5days,'MM-DD-YYYY'))
--set spooling to save in csv
set underline off
SET RECSEP OFF
set verify off
set colsep ','
set linesize 300
set trimspool on
spool /home/user/project/samp.csv
select * from att2;
spool off
set verify off
i solved my problem with this code:
#!/usr/bin/ksh
date1='date'
date1=$(/bin/date --date="$date1" -d "+0 day" +"%F")
date2=$(/bin/date --date="$date1" -d "+4 day" +"%F")
echo $date1
echo $date2
sqlplus -s /nolog << EOF
connect scott/tiger
--execute procedure with parameter
execute attendance(to_date('$date1', 'YYYY-MM-DD'),to_date('$date2','YYYY-MM-DD'))
--set spooling to save in csv
set underline off
SET RECSEP OFF
set verify off
set colsep ','
set linesize 300
set trimspool on
spool /home/user/project/samp.csv
select * from att2;
spool off
set verify off
:) cheers

Iteration of batch script based on search string

I've a Program2.bat having Oracle query, which generates a file log.txt having content-structure either like:
SQL> SELECT SID, SERIAL#, STATUS, USERNAME, LOGON_TIME FROM GV$SESSION WHERE USERNAME = 'DBADMIN' and status in ('ACTIVE','INACTIVE','KILLED') ;
no rows selected
SQL> spool off;
OR like:
SQL> SELECT SID, SERIAL#, STATUS, USERNAME, LOGON_TIME FROM GV$SESSION WHERE USERNAME = 'DBADMIN' and status in ('ACTIVE','INACTIVE','KILLED') ;
SID SERIAL# STATUS USERNAME LOGON_TI
---------- ---------- ---------- ---------- -------------
2388 54 Active DBADMIN 28-FEB-14
2391 37 Active DBADMIN 17-FEB-14
2395 111 Inactive DBADMIN 28-FEB-14
2780 325 Killed DBADMIN 26-FEB-14
2790 111 Killed DBADMIN 8-FEB-14
5 rows selected.
SQL> spool off
I'm trying to achieve following things:
Action-1: Call Program2.bat, which will generate log.txt
Action-2: Search for the string "no rows selected" in log.txt
Action-3: If string found then call program1.bat
Action-4: If string not found then do below:
call program2.bat again and
Do Action-2 again at an interval of 5 mins (means keep searching for string "no rows selected" in log.txt on an interval of 5 mins untill string "no rows selected" got found ).
#echo off
setlocal
Call Program2.bat
>nul findstr /c:"no rows selected" log.txt && (
call program1.bat
) || (
call program2.bat
)
How Point-2 of Action-4 can be achieved in above script or do we have any other way to achieve all in the easiest way?

How to store multiple output columns returned by stored proc in shell using sqlplus

I have o read values returned by sql stored proc to variables in shell script. I was able to achieve this with single variable but not for two variables.
Oracle stored proc
PROCEDURE get_values (ip_var IN NUMBER,
op_var1 OUT VARCHAR2,
op_var2 OUT VARCHAR2)
IS
BEGIN
SELECT col1, col2
INTO op_var1, op_var2
FROM emp
WHERE emp_id = ip_var;
END;
Calling this proc in unix bash as
sql_status=`sqlplus -silent /nolog << END
whenever sqlerror exit sql.sqlcode
whenever oserror exit -2
set pagesize 0 feedback off verify off heading off echo off scan off serveroutput on
connect $DATABASE
declare
var1 VARCHAR2(20);
var2 VARCHAR2(20);
begin
get_values($input_val, var1, var2);
end;
/
exit;
END`
I need to assign var1 and var2 further in my program. So how can I achieve this?
I know not how to do this interface between PL/SQL (Oracle Server side language) and Unix. You may want to have a jdbc connector for more advanced use.
A solution for your problem is to build an output string directly from the query (or you could use a procedure, and output the result with dbms_output), and process the string in your shell.
Here is how (without procedure):
COL_SEP="%"
RETURN_STRING=`sqlplus -silent /nolog << END
whenever sqlerror exit sql.sqlcode
whenever oserror exit -2
set pagesize 0 feedback off verify off heading off echo off scan off serveroutput on
connect $DATABASE
SELECT col1 ||'${COL_SEP}'|| col2
FROM emp
WHERE emp_id = ip_var;
exit;
END`
echo "RETURN CODE IS: $? "
echo "RETURN STRING : ${RETURN_STRING} "
v1=`echo ${RETURN_STRING} | cut -d${COL_SEP} -f1 `
v2=`echo ${RETURN_STRING} | cut -d${COL_SEP} -f2 `
echo "Variables set: V2:${v2} and V1:${v1}"
And you can do it with dbms_output.put_line in a pl/sql block:
declare
v varchar2(100) := '00';
begin
select 'a'||'${COL_SEP}'||'b' into v from dual;
dbms_output.put_line(v);
end;
/
Hope it helps

Resources