DBeaver : Get dynamic path from script with SQL*Plus - oracle

I'm facing a problem with SQL*Plus and dynamic script path in DBeaver.
I'm using a script that calls another script for DDL (create, alter, drop, comment, grant, etc) operations. The first script spools into a log file in the \Logs sub-folder, and refers to a 2nd SQL file in the \Scripts sub-folder which contains all the DDL commands.
The 1st script :
UNDEFINE FILENAME_log;
DEFINE FILENAME_log = 'TABLE_NAME' --Change with the TABLE_NAME
spool Logs\Log_&FILENAME_log..txt APPEND;
PROMPT "############# START SCRIPT #############";
-- Timestamp at start
SELECT TO_CHAR(sysdate, 'YYYY-MM-DD HH24:MI:SS') as "Timestamp" FROM dual;
-- Schema where the script is executed
SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') as "Schema" FROM dual;
-- Service name (DEV/PROD)
SELECT SERVICE_NAME as "Service Name" FROM gv$session WHERE sid in (SELECT sid FROM V$MYSTAT);
-- User
SELECT SYS_CONTEXT('userenv', 'os_user') as "OS_User" FROM dual;
PROMPT "///// 01_FULL_&&FILENAME_log /////";
#Scripts\01_FULL.sql;
PROMPT "############# END SCRIPT #############";
PROMPT "";
spool off;
In DBeaver, I use "Execute in SQL Plus" (when connected, right click on connection > Tools > "Execute in SQL Plus").
I downloaded SQL*Plus from Oracle and referring to the executable path in the DBeaver Local Client (C:\instantclient_19_12).
Then I get the script from another folder (C:\test script) (Input)Execute Script windows, but when I try to spool or get the 2nd script I've an error.
SP2-0310: unable to open file "Scripts\01_FULL.sql"
Working path is 'C:\instantclient_19_12' when I'm expecting 'C:\test script'.
I tried these http://orasql.org/2015/06/26/sqlplus-tips-7-how-to-find-current-script-directory/ and https://dba.stackexchange.com/questions/17347/sqlplus-and-relative-paths but both scripts return me null for path...
Any ideas to solve this issue ?
PS : In SQL Developer I've used the following custom default path to look for script (Preferences > Database > Worksheet), scripts are working well.
"${file.dir}"

Related

Run sqlplus commands from multiple files with query logging or spool in Windows Batch File

I am quite new to batch scripting, and I am trying to run multiple sql files, which in turn may contain multiple sql DML/DDL queries from bat file. The output files must contain all the queries being executed and the query output. Unlike this example , I don't have spool command inside my sql file, and I can not edit the input sql files. The following command works for me in ksh file (thanks to here-document):
$sqlplus /nolog <<! >>$sqlLogs.lst
connect $USERNAME/$PASSWORD#${DBNAME}
set echo on timing on
spool ${SCRIPTRUNFILE_SPOOL}
select name from v\$database;
#${SCRIPTRUNFILE};
spool off
exit
!
I want the exact same in Windows bat file. I have tried using ^. I can't do combine all sql files into one, as I need logging for each sql file into different file. My attempt at the bat file script is as follows and I have played around this much, and it fails with spool command not recognized. I also prefixed below commands with sqlplus, but still unable to achieve something like above ksh file:
sqlplus -s username/pwd#DBName >> sqlLogs.lst
set echo on timing on
spool %RUNFILENAME%.lst
#%RUNFILENAME% > %RUNFILENAME%.lst
select name from v\$database;
spool off
quit
Following logic executes my scripts but does not log the query being executed. Also, I don't want to connect twice to the database.
echo select name from v$database; | sqlplus -s username/pwd#DBName >> sqlLogs.lst
echo quit | sqlplus -s username/pwd#DBName #%SCRIPTRUNFILE%>> %SCRIPTRUNFILE_SPOOL%.lst
Can someone here please help to spool to a file where I can log the queries as well, while maintaining a single DB Connection?
Pass your immediate SQL*Plus commands to your sqlplus via stdout, grouped together by Windows' ( and ) symbols...
(
echo.set echo on timing on
echo.spool %SCRIPTRUNFILE_SPOOL%
echo.select name from v$database;
echo.#%SCRIPTRUNFILE%
echo.spool off
echo.exit
) | sqlplus -s %USERNAME%/%PASSWORD%#%DBNAME% >> sqlLogs.lst

Run batch oracle queries in multiple database

I have 4 Database connection in SQL developer(oracle). At evening I have to regularly run some scripts in all the 4 connection on same server. Is there is any shortcut that I run script only once and is reflected in all connection which is connected to some DB.
(NOTE: All the 4 connection will hold exactly same info.)
Can anyone suggest how to do this?
Here's how I do that: using the command prompt capabilities, not GUI. The only prerequisite is to have SQL*Plus installed on your computer.
For example, create SQL script you're about to run and save it into C:\Temp directory; let's name it "my_script.sql". It can contain both SQL and PL/SQL (don't forget to terminate it with a slash in that case!).
Here's how it should look like:
connect &2
spool &1
set echo on
set define off
-- Your SQL statements go here:
select to_char(sysdate, 'dd.mm.yyyy hh24:mi') vrijeme from dual;
begin
pkg_payments.p_gimme_my_money;
commit;
end;
/
-- End of your SQL statements
spool off
exit
Then create a DOS batch script, let's name it "run_my_script.bat" and put such a code in there:
#echo on
set SCRIPT=C:\Temp\my_script.sql
set SCRIPT_LOG=C:\Temp\my_script
if not exist %SCRIPT% goto END
start sqlplus.exe /nolog #%SCRIPT% %SCRIPT_LOG%.site_1.log "username_1"/"password_1"#(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=host_1_name)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=service_name_1)))
start sqlplus.exe /nolog #%SCRIPT% %SCRIPT_LOG%.site_2.log "username_2"/"password_2"#(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=host_2_name)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=service_name_2)))
start sqlplus.exe /nolog #%SCRIPT% %SCRIPT_LOG%.site_3.log "username_3"/"password_3"#(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=host_3_name)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=service_name_3)))
start sqlplus.exe /nolog #%SCRIPT% %SCRIPT_LOG%.site_4.log "username_4"/"password_4"#(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=host_4_name)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=service_name_4)))
:END
As you can see, it
sets local variables (SCRIPT, which points to a .SQL file you
created) and SCRIPT_LOG which contains log information about script's
execution)
invokes SQL*Plus (in parallel; if you want them to execute
serially, just remove the START keyword), connecting to each database
and running the script
The simplest way to test it is to double-click the .BAT file; it'll open 4 "black" command prompt windows and terminate them once the SQL script finishes its job. Check the LOG files!
When you're satisfied with the outcome, schedule .BAT file's execution in Task Scheduler so that they are executed regularly & automatically.
That would be all, I presume.

Oracle SQL Developer, I keep getting the query in the .CSV file [duplicate]

I am wanting to output a Query to a CSV file and am using the below as a small test;
spool c:\test.csv
select /*csv*/ username, user_id, created from all_users;
spool off;
but the output has the actual select statment as the first line
> select /*csv*/ username user_id created from all_users
USERNAME USER_ID CREATED
REPORT 52 11-Sep-13
WEBFOCUS 51 18-Sep-12
Is there a way to prevent this? I tried SET Heading Off thinking that might do it, but it did not change. I am using SQL Developer an running as script.
Thanks
Bruce
Unfortunately SQL Developer doesn't fully honour the set echo off command that would (appear to) solve this in SQL*Plus.
The only workaround I've found for this is to save what you're doing as a script, e.g. test.sql with:
set echo off
spool c:\test.csv
select /*csv*/ username, user_id, created from all_users;
spool off;
And then from SQL Developer, only have a call to that script:
#test.sql
And run that as a script (F5).
Saving as a script file shouldn't be much of a hardship anyway for anything other than an ad hoc query; and running that with # instead of opening the script and running it directly is only a bit of a pain.
A bit of searching found the same solution on the SQL Developer forum, and the development team suggest it's intentional behaviour to mimic what SQL*Plus does; you need to run a script with # there too in order to hide the query text.
My shell script calls the sql file and executes it. The spool output had the SQL query at the beginning followed by the query result.
This did not resolve my problem:
set echo off
This resolved my problem:
set verify off
Just for anyone who stumbles upon this (after 7+ years) ...
This works for me ... adapt it to your way of invoking sqlplus.
sqlplus -s / as sysdba 2>&1 > /dev/null <<EOF
whenever sqlerror exit sql.sqlcode;
set echo off
set verify off
set feedback off
set term off
set head off
set pages 1000
set lines 200
spool /tmp/whatever.output
### Your_SQL_statement_here ###
example: select sysdate from dual;
example: select * from V\$LOGFILE;
spool off
EOF
-s flag here is the key to not displaying the SQL statements when runing a script.
set echo off
spool c:\test.csv
select /*csv*/ username, user_id, created from all_users;
spool off;
You can directly export the query result with export option in the result grig.
This export has various options to export. I think this will work.
Exec the query in TOAD or SQL DEVELOPER
---select /*csv*/ username, user_id, created from all_users;
Save in .SQL format in "C" drive
--- x.sql
execute command
---- set serveroutput on
spool y.csv
#c:\x.sql
spool off;

Spool Command: Do not output SQL statement to file

I am wanting to output a Query to a CSV file and am using the below as a small test;
spool c:\test.csv
select /*csv*/ username, user_id, created from all_users;
spool off;
but the output has the actual select statment as the first line
> select /*csv*/ username user_id created from all_users
USERNAME USER_ID CREATED
REPORT 52 11-Sep-13
WEBFOCUS 51 18-Sep-12
Is there a way to prevent this? I tried SET Heading Off thinking that might do it, but it did not change. I am using SQL Developer an running as script.
Thanks
Bruce
Unfortunately SQL Developer doesn't fully honour the set echo off command that would (appear to) solve this in SQL*Plus.
The only workaround I've found for this is to save what you're doing as a script, e.g. test.sql with:
set echo off
spool c:\test.csv
select /*csv*/ username, user_id, created from all_users;
spool off;
And then from SQL Developer, only have a call to that script:
#test.sql
And run that as a script (F5).
Saving as a script file shouldn't be much of a hardship anyway for anything other than an ad hoc query; and running that with # instead of opening the script and running it directly is only a bit of a pain.
A bit of searching found the same solution on the SQL Developer forum, and the development team suggest it's intentional behaviour to mimic what SQL*Plus does; you need to run a script with # there too in order to hide the query text.
My shell script calls the sql file and executes it. The spool output had the SQL query at the beginning followed by the query result.
This did not resolve my problem:
set echo off
This resolved my problem:
set verify off
Just for anyone who stumbles upon this (after 7+ years) ...
This works for me ... adapt it to your way of invoking sqlplus.
sqlplus -s / as sysdba 2>&1 > /dev/null <<EOF
whenever sqlerror exit sql.sqlcode;
set echo off
set verify off
set feedback off
set term off
set head off
set pages 1000
set lines 200
spool /tmp/whatever.output
### Your_SQL_statement_here ###
example: select sysdate from dual;
example: select * from V\$LOGFILE;
spool off
EOF
-s flag here is the key to not displaying the SQL statements when runing a script.
set echo off
spool c:\test.csv
select /*csv*/ username, user_id, created from all_users;
spool off;
You can directly export the query result with export option in the result grig.
This export has various options to export. I think this will work.
Exec the query in TOAD or SQL DEVELOPER
---select /*csv*/ username, user_id, created from all_users;
Save in .SQL format in "C" drive
--- x.sql
execute command
---- set serveroutput on
spool y.csv
#c:\x.sql
spool off;

Oracle External Job Error ORA-27369: job of type EXECUTABLE failed with exit code: Not owner

i have an Oracle scheduler job that run an executable shell script in Solaris environment. Job runs every 2nd Sunday each month, it runs in status failed in Scheduler Job log with error code : ORA-27369
here is my shell script :
#!/bin/bash
ORACLE_HOME=/app/oracle/10g;
export ORACLE_HOME;
ORACLE_SID=IBSDB;
export ORACLE_SID;
edate=`date "+%Y%m%d"`; export edate;
$ORACLE_HOME/bin/sqlplus "/ as sysdba" #/app/oracle/script/alter_all_index.sql
this shell script run sqlplus and execute alter_all_index.sql. alter_all_index.sql creates 2 file via spool command. first is ALTER_INDEX_REBUILD.sql, this file contain query to rebuild all index. and the second file is LOG_ALTER_INDEX_REBUILD.txt to store any error occurs while executing ALTER_INDEX_REBUILD.sql here is the code of alter_all_index.sql
set wrap off
set linesize 1000
set feedback off
set pagesize 0
set verify off
set termout off
spool ALTER_INDEX_REBUILD.sql;
prompt set linesize 1000
prompt set pagesize 0
prompt spool LOG_ALTER_INDEX_REBUILD.txt
PROMPT ------------------ START FROM HERE ---------------
--prompt varID nvarchar2(40):=sys_guid();;
--prompt insert into PCB_AGCM.QUERY_HK_MONITOR (ID, TASK_NAME, START_TIME, END_TIME, STATUS) values(varID, 'REBUILD INDEX', to_char(sysdate, 'Dy DD-Mon-YYYY HH24:MI:SS'), null, 'STARTING');;
--prompt commit;;
prompt ------------------ execute GCM_AGCM --------------
select 'ALTER INDEX '||owner||'.'||INDEX_NAME||' REBUILD ONLINE;'
from all_indexes where owner like 'PCB_AGCM%';
PROMPT ------------------ END OF SCRIPT ----------------------
--prompt update PCB_AGCM.QUERY_HK_MONITOR set end_time=to_char(sysdate, 'Dy DD-Mon-YYYY HH24:MI:SS'), status='COMPLETED' where ID = varID;;
prompt commit;;
prompt exec PCB_AGCM.GATHER_SCHEMA_STATS();;
PROMPT /
PROMPT ------------------- END OF SCRIPT ----------------------
prompt spool off
SPOOL OFF;
##ALTER_INDEX_REBUILD.sql
before the job run, both ALTER_INDEX_REBUILD.sql and LOG_ALTER_INDEX_REBUILD.txt are exist generated from previous manual run.
when i tested via Oracle Scheduler Job. first it run well, and i look its session through TOAD->session browser, it works well, query rebuild index was running, but after the last index done, job ended with error ORA-27369: job of type EXECUTABLE failed with exit code: Not owner.
i examine all the script. both ALTER_INDEX_REBUILD.sql and LOG_ALTER_INDEX_REBUILD.txt is not updated, Spool command will create and replace if existed by default, their last modification date is 13 April 2013. it should have changed into 9 May 2013.
i come with a conclusion, that there is a problem with spool command, but i got no idea how to solve this, i thought that it might concern their ownership and permission but both file owned by oracle. anyone got any idea why and how to solve this ?
i have browsed about ORA-27369 but none gives me any hints so far.
sincerely
There are a few Big Questions to ask about this:
Why run as an external job a sql*plus script that you could just run as a pl/sql procedure? As a general rule, if you do not need to involve the operating system in a task, then don't do it. Code kept on the file system is not backed up with the database and is more prone to error through connection problems or Some Damn Fool Just Deleting It.
Code like the index rebuild ought to be a procedure with code such as:
for indexes in (select owner,
index_name
from all_indexes
where owner like 'PCB_AGCM%'
order by owner,
table_name)
loop
sql := 'alter index '||indexes.owner||'.'||indexes.index_name||' rebuild online';
execute immediate sql;
end loop
Why are you regularly rebuilding all of your indexes? If you get an immediate measurable benefit to it then it's because you have compacted your indexes, but you're then going to incur more overhead through the index growing back to it's natural size. See many entries on Richard Foote's blog for more information.
As far as I know, external programs launched by DBMS_SCHEDULER run as a low-privileged user account (usually nobody, see Oracle forums).
To debug this issue, can you:
run a simple script that outputs the UID
check whether this user is allowed to create / overwrite files in /app/oracle/script/
Also, I'd recommend either specifying the absolute path for your SPOOL file instead of just the file name, or using cd before your SQL/Plus call to ensure the SPOOL file is created in the correct directory.

Resources