I need to give the spool file name dynamically and I have to pass the parameters when I call sqlplus. Below is what I tried
echo exit | sqlplus "{{ Oracle_username }}/ {{ Oracle_pwd}} #(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(Host={{ Oracle_HostName }} )(Port=1521))(CONNECT_DATA=(SID= {{Oracle_SID }})))" #Script.sql 'AppName' 'DatabaseName' 'ObjectType'
Over here I tried to pass App Name, Database Name and Object Type dynamically. Prior to running SQLPLUS step, I create folders dynamically (App Name , Database Name , Object Type are all folders and it will vary depending on each application) .Below is how my script.sql looks like :
SPOOL &&AppName/&&DatabaseName/&&ObjectType/Output.csv
<<SQL Script>>
SPOOL OFF
This doenst work . Can someone tell me what needs to be changed.
You are passing the values you want to form your spool file path and name as arguments to your script, but you need to refer to them as positional parameters:
SPOOL &1/&2/&3/Output.csv
Or if you're going to reuse them for something else you could define your own variable, set from the positional parameters:
DEFINE AppName=&1
DEFINE DatabaseName=&2
DEFINE ObjectType=&3
SPOOL &&AppName/&&DatabaseName/&&ObjectType/Output.csv
The spool file path will be relative to the directory you're in when you run the script. If that isn't what you want then put the root before the first substitution variable in the spool command, whichever form you use.
You could also include the exit in your .sql file so you don't have to echo it in; and you could use a TNS alias instead of passing all of the connection information on the command line - or if you can use a service name instead of a SID, you could use the easy connect syntax which is a bit simpler:
sqlplus username/password#//hostname:1521/service_name #Script.sql 'AppName' 'DatabaseName' 'ObjectType'
set your appname,dbname,objecttype's as environmental variables and then Try like below
[oracle#ct-myhost-02 ~]$ export app_name=/stage
[oracle#ct-myhost-02 ~]$ export database_name=PSES
[oracle#ct-myhost-02 ~]$ sqlplus / as sysdba
SQL*Plus: Release 11.2.0.3.0 Production on Wed Feb 1 12:04:08 2017
Copyright (c) 1982, 2011, Oracle. All rights reserved.
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
SQL> spool $app_name/$database_name/out.csv
SQL> select * from dual;
D
-
X
SQL> spool off;
SQL> exit
Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
[oracle#ct-myhost-02 ~]$ ls -l /stage/PSES/out.csv
-rw-r-----. 1 oracle oinstall 286 Feb 1 12:04 /stage/PSES/out.csv
Related
I am trying to store the value of sql query output in a variable using shell script.
size=`${PATH_TO_CLIENT}sqlplus $IMPUSER/$IMPPWD#$ENDPOINT<< EOF
select owner, sum(bytes)/1024/1024/1024 Size_GB from dba_segments where owner = 'XXXX' group by owner;
exit;
EOF`
echo "Total data is ${size}"
The output I am getting is
**Total data is**
SQL*Plus: Release 21.0.0.0.0 - Production on Fri May 14 11:06:42 2021
Version 21.1.0.0.0
Copyright (c) 1982, 2020, Oracle. All rights reserved.
Last Successful login time: Fri May 14 2021 11:01:02 -04:00
Connected to:
Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production
Version 19.8.0.0.0
SQL>
OWNER
--------------------------------------------------------------------------------
SIZE_GB
----------
XXXXXXX
12.2345
SQL> Disconnected from Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production
Version 19.8.0.0.0
Inside the variable full connection string and sql query output all are getting stored. I just want to get value like $size=12.2345 Please tell me how to get that
The size value might be assigned to the current variable through use of the following code block
size=$(sqlplus -S /nolog << EOF
conn $IMPUSER/$IMPPWD#$ENDPOINT
whenever sqlerror exit sql.sqlcode
SET PAGES 0
SELECT SUM(bytes)/1024/1024/1024 FROM dba_segments WHERE owner = 'XXXX';
EOF
)
echo "Total data is "$size
where
keeping owner column and group by clause are redundant as
returning only one column value for a single schema
no need to alias the calculated value as not needed for the returning result while hiding the column title through use of SET PAGES 0 command
using direct connection is not safe, but use sqlplus -S /nolog before
schema connection in order to hide the password while listed by
anbody through ps command.
You can use this:
size=`${PATH_TO_CLIENT}sqlplus -s $IMPUSER/$IMPPWD#$ENDPOINT <<EOF
set echo off
set feedback off
set heading off
set pages 0
select sum(bytes)/1024/1024/1024 Size_GB from dba_segments where owner = 'SYS';
exit;
EOF`
echo "Total data is ${size}"
If the output is consistent with newlines, you could use:
size=`${PATH_TO_CLIENT}sqlplus $IMPUSER/$IMPPWD#$ENDPOINT<< EOF | sed -n '/^\s*SIZE_GB$/{n;n;n;p}'
select owner, sum(bytes)/1024/1024/1024 Size_GB from dba_segments where owner = 'XXXX' group by owner;
exit;
EOF`
It will return the third line after line which contains 'SIZE_GB'.
I'm trying to read a file of type txt from c:\Dir and insert the content on the table Oracle Sql
set SERVEROUTPUT ON
CREATE OR REPLACE DIRECTORY MYDIR AS ' C:\dir';
DECLARE
vInHandle utl_file.file_type;
eNoFile exception;
PRAGMA exception_init(eNoFile, -29283);
BEGIN
BEGIN
vInHandle := utl_file.Fopen('MYDIR','attachment.txt','R');
dbms_output.put_line('The File exists');
EXCEPTION
WHEN eNoFile THEN
dbms_output.put_line('The File not exists');
END;
END fopen;
/
i have the file not exists but i have this file
I don't know whether space you have in front of the directory name in the first statement you posted makes difference (or is it just a typo), but - nonetheless, here's how it is usually done.
Create directory on hard disk:
C:\>mkdir c:\dir
Connect to the database as SYS (as it owns the database, as well as directories); create directory (Oracle object) and grant privileges to user which will use that directory:
C:\>sqlplus sys as sysdba
SQL*Plus: Release 11.2.0.2.0 Production on ╚et O×u 5 18:34:43 2020
Copyright (c) 1982, 2014, Oracle. All rights reserved.
Enter password:
Connected to:
Oracle Database 11g Express Edition Release 11.2.0.2.0 - 64bit Production
SQL> create or replace directory mydir as 'c:\dir';
Directory created.
SQL> grant read, write on directory mydir to scott;
Grant succeeded.
SQL>
You don't need this, as you already have the file; I'll create it by spooling table contents.
SQL> connect scott/tiger
Connected.
SQL> spool c:\dir\example.txt
SQL> select * From dept;
DEPTNO DNAME LOC
---------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
SQL> spool off;
SQL> $dir c:\dir\*.txt
Volume in drive C is OSDisk
Volume Serial Number is 7635-F892
Directory of c:\dir
05.03.2020. 18:39 539 example.txt
1 File(s) 539 bytes
0 Dir(s) 290.598.363.136 bytes free
SQL>
Finally, reusing code you wrote:
SQL> set serveroutput on
SQL>
SQL> DECLARE
2 vInHandle utl_file.file_type;
3 eNoFile exception;
4 PRAGMA exception_init(eNoFile, -29283);
5 BEGIN
6 BEGIN
7 vInHandle := utl_file.Fopen('MYDIR','example.txt','R');
8 dbms_output.put_line('The File exists');
9 EXCEPTION
10 WHEN eNoFile THEN
11 dbms_output.put_line('The File not exists');
12 END;
13 END fopen;
14 /
The File exists
PL/SQL procedure successfully completed.
SQL>
Works properly (congratulations, you wrote code that actually works!).
So, what have you done wrong?
as I said, space in front of c:\dir: CREATE OR REPLACE DIRECTORY MYDIR AS ' C:\dir';
database isn't on your computer but on a separate database server
it means that you probably created directory, but it points to c:\dir directory on the database server, not your own PC!
As Boneist commented, it is possible to create a directory (Oracle object) on computer which is NOT a database server, but that's not something we usually do. If you opt to choose this option, you'll have to use UNC (Universal Naming Convention) while creating directory.
Another option you might want to consider is to use SQL Loader. It is an operating system utility, installed along with the database or (full, not instant) client software. Its advantage is that it runs on your local PC (i.e. you don't have to have access to the database server) and is extremely fast. You'd create a control file which tells Oracle how to load data stored in the source (.txt) file.
Another option, which - in the background - uses SQL Loader, is to use an external table. It is yet another Oracle object which points to the source (.txt) file and allows you to access it using a simple SQL SELECT statement. Possible drawback: it still requires access to the Oracle directory (just like your UTL_FILE option).
I need to execute the multiple script having one master sql file. Whenever I used to execute the master calling script named as calling_test.sql if anything error comes need to be rollbacked.
sqlplus USERNAME/PWD#SIR_NAME;
##calling_test.sql
here is content of calling_test.sql script.
SET echo ON;
SET define ON;
SET scan ON;
define PATH =/krishna/test
define AB_SCHEMA=AIM
spool Test_incremental.log
SET define ON;
##&&PATH/AUG/2019-08-28/test1.sql
SET define ON;
##&&PATH/AUG/2019-08-29/test2.sql
SET define ON;
##&&PATH /AUG/2019-08-30/test3.sql
SET define ON;
The scrip should contain something like this:
whenever sqlerror exit rollback
Example:
SQL> create table test (col number);
Table created.
SQL>
SQL script (named p.sql)
whenever sqlerror exit rollback
insert into test values (100);
insert into test values ('A');
Calling it:
M:\>sqlplus scott/tiger#orcl #p.sql
SQL*Plus: Release 11.2.0.1.0 Production on ╚et Ruj 26 13:38:50 2019
Copyright (c) 1982, 2010, Oracle. All rights reserved.
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
With the Partitioning, Real Application Clusters, Automatic Storage Management, OLAP,
Data Mining and Real Application Testing options
1 row created.
insert into test values ('A')
*
ERROR at line 1:
ORA-01722: invalid number
Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
With the Partitioning, Real Application Clusters, Automatic Storage Management, OLAP,
Data Mining and Real Application Testing options
M:\>
Result:
SQL> select * From test;
no rows selected
SQL>
You can rollback the actions from called scripts, but in addition to WHENEVER command you must also SET AUTOCOMMIT OFF. Normally when Sqlplus exits a script invoked in a separate file it commits. However the preceding overrides that action. See below: (save each script to the indicated file.)
---------------------------------------------------------------------------- -- script mst_0.sql
create table multi_script_test( id integer, description varchar2(50));
insert into multi_script_test values( 0, 'Initial before script.');
commit;
-- script mst_1.sql
insert into multi_script_test values( 1, 'Insert from script mst_1');
-- script mst_2.sql
insert into multi_script_test values ( 2, 'Insert from script mst_2');
-- script mst_3.sql
insert into multi_script_test values ( 3/0, 'oops');
-- script mst_4.sql
insert into multi_script_test values ( 4, 'Insert from script mst_4');
-- main script mst_main.sql
set echo on
set autocommit off
whenever sqlerror continue rollback
##c:/so/ora/mst_0.sql
##c:/so/ora/mst_1.sql
##c:/so/ora/mst_2.sql
-- following should display rows 0, 1, 2
select * from multi_script_test;
-- generate error and due to whenever directive 'rollback' discard rows 1,2
#c:/so/ora/mst_3.sql
-- continue script processing, also due to whenever directive 'contunue'
#c:/so/ora/mst_4.sql
commit;
----------------------------------------------------------------------------
sqlplus -- complete the signon
-- run main script
#mst_main
-- following show show display 0, 4
select * from multi_script_test;
exit
I'm trying to create a new PL/SQL Procedure in Oracle DB. The Procedure is to be created by a BASH script. Later-on the Procedure will be executed from the same BASH script.
There are ways to execute the stored procedure from bash script but none explains how to create a stored procedure form a bash script.
backup_procedure_string="CREATE OR REPLACE
PROCEDURE BACKUP_TABLE_PROCEDURE(
.
.
END BACKUP_TABLE_PROCEDURE;"
backup_procedure_execution_string="BACKUP_TABLE_PROCEDURE('${param1}', '${param2}', '${param3}');"
sqlplus -S "${ofca_connect_string}" << EOF >> "${current_directory}/query.log"
WHENEVER SQLERROR EXIT 1
SET SERVEROUTPUT ON
SET TERMOUT OFF
$backup_procedure_string
EXECUTE $backup_procedure_execution_string
SET SERVEROUTPUT OFF
EXIT;
EOF
The Procedure "BACKUP_TABLE_PROCEDURE" should be created in the Database and gets executed. However, there is no error/oracle error but the procedure is also not getting created.
Works for me, here's a complete code sample.
Note I used SQLcl not SQLPlus, but same concept.
No idea what you have in your . . code, so maybe problem is there?
Jeffreys-Mini:19.1 thatjeffsmith$ procedure_string="CREATE OR REPLACE PROCEDURE SO_BASH is BEGIN
> null;
> END SO_BASH;
> /
> "
Jeffreys-Mini:19.1 thatjeffsmith$ echo $procedure_string
CREATE OR REPLACE PROCEDURE SO_BASH is BEGIN null; END SO_BASH; /
Jeffreys-Mini:19.1 thatjeffsmith$ sql hr/oracle << EOF >> so.log
> $procedure_string
> EXIT;
> EOF
Jeffreys-Mini:19.1 thatjeffsmith$ more so.log
SQLcl: Release 18.3 Production on Fri Jun 14 10:16:57 2019
Copyright (c) 1982, 2019, Oracle. All rights reserved.
Last Successful login time: Fri Jun 14 2019 10:16:58 -04:00
Connected to:
Oracle Database 18c Enterprise Edition Release 18.0.0.0.0 - Production
Version 18.3.0.0.0
Procedure SO_BASH compiled
Disconnected from Oracle Database 18c Enterprise Edition Release 18.0.0.0.0 - Production
Version 18.3.0.0.0
Jeffreys-Mini:19.1 thatjeffsmith$
And browsing my schema...
Can someone please help me here?
Looks like I setup the right values in the set variables, but it's returning lot of things. See below:
################################
# Main
################################
RETVAL=`sqlplus user/pass#DB <<EOF
SET PAGESIZE 0 FEEDBACK OFF VERIFY OFF HEADING OFF ECHO OFF
SELECT process_id, source, destination, type FROM table WHERE process_id IN ('12311','12322');
EXIT;
EOF`
if [ -z "$RETVAL" ]; then
echo "No rows returned from database"
exit 0
else
echo $RETVAL
fi
The output is:
SQL*Plus: Release 9.2.0.8.0 - Production on Thu Jun 27 19:37:39 2013 Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved. Connected to: Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production With the Partitioning, OLAP, Data Mining and Real Application Testing options SQL> SQL> 12311 ,AAA BBB ,2 12322 ,AAA BBB ,5 SQL> Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production With the Partitioning, OLAP, Data Mining and Real Application Testing options
I just would like:
12311, AAA, BBB, 2,
12322, AAA, BBB, 5,
*the commas is also not right
Use -s option of sqlplus to supress:
sqlplus -s user/pass#DB