Pass Parameters from a batch file to sqlplus script - sql

I am trying to get one file with my user name and passwords for some scripts that I run every day. I have several scripts working now using a batch file that has my user names and passwords.
My Password Batch file looks like this.
parms.bat
Rem Oracle Db
set odbUsername=myUserName
set odbpassword=myPassword
My other scripts call that batch file and get the information ok. I have a couple sql scripts that I also need to use these usernames and passwords. I can't seem to get them to work. But I am fairly new to sqlplus scripting.
My Sql Scripts looks like this.
CONNECT myusername#Oracleddbname/mypassword
SET FEEDBACK OFF;
SET ECHO OFF;
SET TERMOUT OFF;
SET HEADING OFF;
SET PAGESIZE 0;
SET LINESIZE 500;
SET TIMING OFF;
SET TRIMSPOOL ON;
SET COLSEP ',';
SPOOL C:\FileTransfers\MeterData.csv
PROMPT CoopCode,MeterID,DateTime,Value
SELECT DISTINCT
a.coopcode
|| ','
|| a.meterno
|| ','
|| a.readdatetime
|| ','
|| a.usage
FROM temp_reconfigured a, temp_goodsence b
WHERE a.coopcode = b.coopcode AND a.meterno = b.meterno
;
Spool off;
EXIT;
I call this script with a batch file that runs through windows task scheduler.
It looks like this.
sqlplus /nolog #C:\FileTransfers\AutomationScripts\GoodSence\SpoolGoodSenceDataSet.sql
So I would like to pass the user name to the sql from the batch file. I have read several things and tried about 30 and none seem to work. Thank you for your help in advance.

You can pass a parameter this way:
script.sql:
select '&1' from dual;
the call:
D:\>sqlplus user/password#db #d:\script.sql 'value'
SQL*Plus: Release 11.2.0.2.0 Production on Lun Ott 3 17:02:10 2016
Copyright (c) 1982, 2014, Oracle. All rights reserved.
Connected to:
Oracle Database 11g Express Edition Release 11.2.0.2.0 - 64bit Production
old 1: select '&1' from dual
new 1: select 'value' from dual
'VALU
-----
value

Just typing that out made me think about passing it during the call vs inside the sql to connect. I then edited my SQL and took out the connect statement
So this worked...
echo Get Parameters
call C:\FileTransfers\AutomationScripts\parms.bat
echo %odbUsername%
echo %odbpassword%
sqlplus myusername#oracledb/%odbpassword%#C:\FileTransfers\AutomationScripts\GoodSence\SpoolGoodSenceDataSet.sql

Related

SQLPLUS script calling a function and executing the return String

I have an sqlplus script which needs to call a function. This function creates an SQL select dynamically and has already been compiled in the database.
My script needs to call this function, executes the SQL request it returns and then spool the data in a CSV file.
My SQLPLUS code is below:
SET HEAD OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET LINESIZE 32000
SET PAGESIZE 0
SET TERMOUT OFF
SET ECHO OFF
SET COLSEP ,
spool /a/b/rvibap/c/&1..csv
EXECUTE IMMEDIATE build_select(&1)
spool off;
/
However, I am getting the below error in my CSV file:
BEGIN IMMEDIATE build_select(TYPE); END;
*
ERROR at line 1:
ORA-06550: line 1, column 17:
PLS-00103: Encountered the symbol "BUILD_SELECT" when expecting one of the following:
:= . ( # % ;
The symbol ":=" was substituted for "BUILD_SELECT" to continue.
I am calling my SQL script in the following way :
#test.sql TYPE
I have also tested the build_select function and it functions correctly; return a query in String.
There are few issues with your code.
There is no BEGIN END block enclosing your EXECUTE IMMEDIATE
expression.
EXECUTE IMMEDIATE does not display the results of an sql select statement.
You are calling your execute script as #test.sql TYPE which will be parsed as EXECUTE IMMEDIATE build_select(TYPE) i.e plain TYPE without quotes - which will throw an error. You can resolve this however by running it as
#test.sql "'TYPE'"
As I said you cannot directly execute and view results from a dynamic SQL select statement in 11g and below. So you can use the technique used in the other answer which I am not clear about if it generates the select SQL neatly.
If you are in 12c, you can use something like
open a_ref_cursor for build_select(&1);
dbms_sql.return_result(a_ref_cursor);
For 11g and below , here are some of the techniques explained.
How to output result of SELECT statement which is executed using native dynamic SQL?
A better solution if you are ok not to use your function would be
Generating SQL*Plus script using SQL*Plus
Wrong syntax... Maybe you could call the spool you just created?
Here is what could work:
SET HEAD OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET LINESIZE 32000
SET PAGESIZE 0
SET TERMOUT OFF
SET ECHO OFF
SET COLSEP ''
spool /a/b/rvibap/c/&1..sql
prompt SET COLSEP ,
select build_select(&1) from dual;
spool off;
spool /a/b/rvibap/c/&1..csv
#/a/b/rvibap/c/&1
spool off;
Hope it helps.

Unix to Sqlplus - Log the SQL statement about to execute and result of execution

I am on AIX using ksh. Created a unix script which generates the CREATE OR REPLACE VIEW ... and GRANT .. statements, which are placed in a single .txt file. Now I need to execute the contents in the file (there are around 300 view creation and grant statements) in Oracle and I need to log the sql statement that is about to execute and the feedback of Oracle whether the view is created or not..
My excerpt goes as
sqlplus -s username/password#servername <<EOF
SET ECHO ON;
SET NEWPAGE 0;
SET PAGESIZE 0;
SET LINESIZE 200;
SET LONG 10000000;
SET TRIMSPOOL ON;
SET HEADING OFF;
SET FEEDBACK ON;
SET VERIFY ON;
SET TERMOUT OFF;
SET SQLBLANKLINES ON;
SPOOL ${drctry}/${v_timestamp}_sql_execution_log.txt
#${drctry}/${v_date}_sql_statements.txt
SPOOL OFF;
EXIT;
EOF
If the contents of the file _${v_date}sql_statements.txt is
CREATE OR REPLACE VIEW V_TABLE1 AS SELECT * FROM TABLE1;
GRANT SELECT ON V_TABLE1 TO USER1;
...
CREATE OR REPLACE VIEW V_TABLE300 AS SELECT * FROM TABLE300;
GRANT SELECT ON V_TABLE300 TO USER300;
Expected output:
CREATE OR REPLACE VIEW V_TABLE1 AS SELECT * FROM TABLE1;
View created
GRANT SELECT ON V_TABLE1 TO USER1;
Grant succeeded
...
CREATE OR REPLACE VIEW V_TABLE300 AS SELECT * FROM TABLE300;
View created
GRANT SELECT ON V_TABLE300 TO USER300;
Grant succeeded
After some search, noticed List option; But it only records only the last statement that was executed if we have more than 1 statement, which doesn't fit here. In Teradata Bteq the ECHOREQuired attribute can be set to ON for this task. But I am not sure in Oracle. Also tried
sqlplus -s username/password#servername <<EOF > ${drctry}/${v_timestamp}_unix_sql_log.txt But still no luck. Will change the password hardcode once I overcome this issue;
The -s[ilent] option:
Suppresses all SQL*Plus information and prompt messages, including the command prompt, the echoing of commands, and the banner normally displayed when you start SQL*Plus.
So by including the -s flag you are overriding the set echo on directive.
If you omit that then the commands are echoed in the spool file, but (a) you also see the banner on stdout and (b) you see the SQL> prompt and the script name spool off echoed too. You can fix the first part by redirecting output, with the risk you may miss something you care about if there is a problem, by changing your shell command to do:
sqlplus -s username/password#servername >/dev/null <<EOF
And you can partly fix the spooled output by changing the prompt, adding:
SET SQLPROMPT ""
With those changes the shell sees no output, and the spool file contains:
#/path/to/v_date_sql_statements.txt
CREATE OR REPLACE VIEW V_TABLE1 AS SELECT * FROM TABLE1;
View created.
GRANT SELECT ON V_TABLE1 TO USER1;
Grant succeeded.
...
SPOOL OFF;
You could potentially post-process that to remove the first and last line, and (if you want) blank lines. You can also hide the script name by including the text file in the heredoc instead of using start/#:
SPOOL ${drctry}/${v_timestamp}_sql_execution_log.txt
`cat ${drctry}/${v_date}_sql_statements.txt`
SPOOL OFF;
I made a sqplus bash script to do that.
link to github: https://github.com/javierB-/ORACLE.git
It create two files, one with the sql sentences, and the other with the sql sentences and their output.
The script core is:
tee -a $FOUT $FOUT_TRAZA | sqlplus $# | tee -a $FOUT
I use the script throught the alias:
alias sqlpluss='$ADMIN_HOME/oracle/sqlpluss.sh'
it's in spanish, i have traslated the output to write here:
sqlpluss
USE ONLY INTERACTIVELY:
sqlplus enriched to save input and output trace.
Use:
sqlpluss [-f fout] user/password#conection #scripts ...
(fout will be opened in add mode and it will default to yyyymmdd.log)
summary:
tee -a fout | sqlplus $# | tee -a fout
the full script its too long to paste here, but if someone want, i'll do it.

How to output oracle sql result into a file in windows?

I tried
select * from users
save D:\test.sql create;
But SQL plus gives me "no proper ended"
How to specify path in oracle sql in windows?
Use the spool:
spool myoutputfile.txt
select * from users;
spool off;
Note that this will create myoutputfile.txt in the directory from which you ran SQL*Plus.
If you need to run this from a SQL file (e.g., "tmp.sql") when SQLPlus starts up and output to a file named "output.txt":
tmp.sql:
select * from users;
Command:
sqlplus -s username/password#sid #tmp.sql > output.txt
Mind you, I don't have an Oracle instance in front of me right now, so you might need to do some of your own work to debug what I've written from memory.
Very similar to Marc, only difference I would make would be to spool to a parameter like so:
WHENEVER SQLERROR EXIT 1
SET LINES 32000
SET TERMOUT OFF ECHO OFF NEWP 0 SPA 0 PAGES 0 FEED OFF HEAD OFF TRIMS ON TAB OFF
SET SERVEROUTPUT ON
spool &1
-- Code
spool off
exit
And then to call the SQLPLUS as
sqlplus -s username/password#sid #tmp.sql /tmp/output.txt
spool "D:\test\test.txt"
select
a.ename
from
employee a
inner join department b
on
(
a.dept_id = b.dept_id
)
;
spool off
This query will spool the sql result in D:\test\test.txt
just to make the Answer 2 much easier, you can also define the folder where you can put your saved file
spool /home/admin/myoutputfile.txt
select * from table_name;
spool off;
after that only with nano or vi myoutputfile.txt, you will see all the sql track.
hope is that help :)
Having the same chore on windows 10, and windows server 2012.
I found the following solution:
echo quit |sqlplus schemaName/schemaPassword#sid #plsqlScript.sql > outputFile.log
Explanation
echo quit | send the quit command to exit sqlplus after the script completes
sqlplus schemaName/schemaPassword#sid #plsqlScript.sql execute plssql script plsqlScript.sql in schema schemaName with password schemaPassword connecting to SID sid
> outputFile.log redirect sqlplus output to log file outputFile.log

I want to copy the output of unix and sqlplus into a file

I am using Solaris. I have to log into sql plus and run some queries, which give a huge result set.
I want to copy all that into a file. Is there any command for it in unix or sqlplus ?
Use the SPOOL command:
SQL> SPOOL /opt/output
SQL> SELECT ...
SQL> SPOOL OFF
setup Oracle environment
(there are ways around specifying username/password on the command line - not the best way especially when other users can 'ps' on the server and see your password)
sqlplus -s username/password <<-!!
set trimspool on trimout on pages 0 feedback off linesize 1000 echo off verify off
spool file.out
select sysdate from dual;
exit
!!
If you are on the command line then just use the > and 2> to redirect stdout and stderr respectively to log files
func > out.log

Favorite SQL*Plus tips and tricks [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
So many times I just need a quick connection to an Oracle DB, where SQLPLUS handles the job.
I imagine when people start using Oracle, the first thing they are told to do is to install Toad or SQLDeveloper. Even so, sometimes you don't want to wait for those tools to load, if you are performing some simple queries.
I have a script that I run when I start my shell so I get a better experience:
SET pagesize 2000
SET LONG 10000
SET linesize 1000
COLUMN last_name format a20
COLUMN total format 999,999,999
SET feedback ON
alter session set nls_date_format = 'yyyy-mm-dd hh:mi:ssPM';
I trimmed my "COLUMN" settings for this example, but basically, that helps the data fit on the screen.
Setting the date format really simplifies dealing with dates.
When the command window opens in Windows, I set the window layout properties so I can scroll, have a wider window, etc. and save the settings for future windows.
Does anybody else use SQL*Plus daily? Any tips?
You can use rlwrap to add readline support to sqlplus. Run sqlplus like this:
$ rlwrap -c sqlplus username#database
Now up/down will scroll through command history. Use ctrl-r to search backwards through history, etc. This makes sqlplus bearable.
Also, add this to your login.sql to set the linesize to whatever the width of your terminal is:
HOST echo "set linesize" $(stty -a|head -n1|cut -f7 -d' '|cut -f1 -d';') > .tmp.sql
#.tmp.sql
HOST rm -f .tmp.sql
Both of these tips only work on unix.
Yes, I use SQL Plus every day in preference to Toad or SQL Developer (though I also use SQL Developer to browse the database).
I have the following in my login.sql script (which SQL Plus runs automatically):
1) Replace default editor (Notepad) with one of my choice:
define _editor = "C:\Program Files\TextPad 5\TextPad.exe"
2) Make SQL prompt show database name so I know where I am (thanks to Tom Kyte for this):
COLUMN global_name new_value gname
SET TERMOUT OFF
SELECT LOWER(USER) || '#' || global_name||CHR(10)||'SQL> ' AS global_name
FROM global_name;
SET SQLPROMPT '&gname'
SET TERMOUT ON
... plus other setting similar to yours.
I also find Tom Kyte's print_table procedure very useful.
Remember that we can put these settings in the login.sql script which will be run automatically whenever we start SQL*Plus. Find out more.
The neat thing about this is, that since 10g, this script is run every time we connect rather just the first time we fire up SQL*Plus...
SQL> conn apc
Enter password:
Connected.
Running login script
Session altered.
SQL> conn scott
Enter password:
Connected.
Running login script
Session altered.
SQL>
I use SQL*Plus exclusively to work with Oracle. Other answers already give some very handy login.sql contents.
This is my login.sql. I copied some suggestions from Tom Kyte and William Robertson in there. Maybe you find some things you want to use as well.
set termout off
set serveroutput on size unlimited
set pagesize 50000
set linesize 135
set long 50000
set trimspool on
set tab off
def _editor = "C:\Progra~1\Notepad++\Notepad++.exe"
define gname=idle
column global_name new_value gname
select lower(user) || '#' ||
substr(global_name,1,decode(dot,0,length(global_name),dot-1)) global_name
from (select global_name,instr(global_name,'.') dot from global_name);
set sqlprompt '&gname> '
alter session set nls_date_format = 'dd-mm-yyyy hh24:mi:ss'
/
var sid number
var serial# number
var tracefile VARCHAR2(200)
DECLARE
v_audsid v$session.audsid%TYPE;
BEGIN
SELECT sid, serial#, audsid
INTO :sid, :serial#, v_audsid
FROM v$session
WHERE audsid = SYS_CONTEXT('USERENV','SESSIONID');
SELECT par.value ||
CASE WHEN par.value LIKE '%/%' THEN '/' ELSE '\' END ||
LOWER(th.instance) ||
'_ora_' || LTRIM(TO_CHAR(pro.spid,'fm99999')) || '.trc' AS filename
INTO :tracefile
FROM v$process pro
, v$session se
, v$parameter par
, v$thread th
WHERE se.audsid = v_audsid
AND pro.addr = se.paddr
AND par.NAME = 'user_dump_dest';
END;
/
BEGIN
IF :sid IS NULL THEN
SELECT sid
INTO :sid
FROM v$mystat
WHERE rownum = 1;
END IF;
END;
/
set termout on
set feedback off
exec DBMS_OUTPUT.PUT_LINE('Sessie: ' || :sid || CASE WHEN :serial# IS NULL THEN ' (no access to V$ tables)' ELSE ',' || :serial# END)
exec IF :tracefile IS NOT NULL THEN DBMS_OUTPUT.PUT_LINE('Eventueel trace-bestand: ' || :tracefile); END IF
prompt
set feedback on
I like to use sqlplus in off-line.
sqlplus -S user/password #query.sql> file.txt
where query.sql is
set feedback off verify off heading off pagesize 0
...here goes a query...
quit;
/
So i can get info from the database in my bat/script files in windows or unix.
I find it is handy to use SQL*Plus column variables within directives - for example, I'm often in a session and want to spool to a new file name to avoid overwriting another log that may already exist and do this (first three statements through an #file):
SQL> column spr new_value spoolref
SQL> select user||'_'||abs(dbms_random.random) spr from dual;
SQL> spool &spoolref
... do work here ...
SQL> spool off
I'll then find the new log by sorting by time - you could always use some strategy other than the random number if you prefer.