Favorite SQL*Plus tips and tricks [closed] - sql

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.

Related

Oracle SQLPlus: Echo without line numbers?

I'm working on a solution where several SQL and PL/SQL scripts are being run together, in a batch of sorts, via SQL*Plus.
I'm declaring SET ECHO OFF; and SET ECHO ON; at relevant points in the scripts so as to output relevant code.
Currently the output looks something like this:
SQL> DECLARE
2 ct number := 0;
3 ctChanges number := 0;
4
5 BEGIN
6 select count(*) into ct from ...
7 (...rest of code block...)
"some specific status message"
Commit executed.
We keep this output as a run-log in our build-environment, but can also access it as a plain text file.
One downside of this format however, is that if I'd like to copy a certain section of the code and run it again in an IDE (like Toad or SQL Developer), it's hard to exclude the line numbers.
Is it possible to tell SQL*Plus to output the code as above, but without including the line numbers?
You can use options sqlnumber and sqlprompt:
set sqlprompt ''
set sqlnumber off
SET SQLN[UMBER] {ON|OFF}
SET SQLNUMBER is not supported in iSQL*Plus
Sets the prompt for the second and subsequent lines of a SQL command or PL/SQL block. ON sets the prompt to be the line number. OFF sets the prompt to the value of SQLPROMPT.

Pass Parameters from a batch file to sqlplus script

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

What's the equivalent of clrscr(); in Oracle SQL?

I want to write a simple script file to display the employee name in a given department name the department name given is case insensitive ,after executing the script, the commands are not displayed.
I use SQL *PLUS and what I did so far is
EDIT script // script is the file name the default extension is .SQL
and inside the script file I wrote the following
SET VERIFY OFF
SELECT Ename, dname
FROM emp, dept
WHERE emp.deptno = dept.deptno
AND UPPER(Dname) = UPPER('&dname');
SET VERIFY ON
then on SQL *Plus
START script
The query works fine but I don't know how to do this part "after executing the script, the commands are not displayed.
"
Maybe are you looking for:
SET ECHO OFF
An other option would be to start SQL*Plus with the -S (silent) option on the command line. From the documentation:
-S[ILENT]
Suppresses all SQLPlus information and prompt messages, including the command prompt, the echoing of commands, and the banner normally displayed when you start SQLPlus.
As about the question as titled:
What's the equivalent of clrscr()
If you are using an ANSI terminal, using the ANSI escape sequence esc[2J should clear your screen:
SET ECHO OFF
SET SERVEROUTPUT ON
VAR ANSI_TERM_CLEAR VARCHAR2 (10)
BEGIN SELECT CHR(27)||'[2J' INTO :ANSI_TERM_CLEAR FROM DUAL; END;
/
PRINT :ANSI_TERM_CLEAR

Issues when user input data in sql command

I have a batch files which when i run calls a SQL file. This SQL file prompts user to input data which I store in MYPeriod( this accepts date as input ).the output of SQL file is a CSV file.
Here is my code for SQL file:
PROMPT Enter a period
ACCEPT MYPeriod PROMPT 'Period: '
SET LINESIZE 500 FEEDBACK OFF TRIMSPOOL ON TERMOUT OFF HEAD OFF PAGESIZE 0 TERM OFF
spool E:\abc\Test\File1_&MYPeriod.csv
select Account || ',' || Membername || ',' || GROUP || ',' || FUTURE1 from ACTUAL_V#UAT1_Test where Key=21 and period_name= '&MYPeriod' ;
spool off
exit
My queries :
When I run this , a file gets generated in location E:\abc\Test with a name File1_12-2012csv.Lst. I want a csv file .
If i hard code the file name(replace &MYPeriod by test) File1_Test.csv gets generated perfectly.Why the code is not able to create file with the name user has input..?
The output of this creates a csv file and retrieves the accounts from db but it prints two extra line at top. The new query and old query. How do I redefine my code, so that it gets remove automatically.
Appreciate your help guys.
Substitution variables are optionally terminated by a period to separate them from any characters that follow. If you want to use one in the string as well, you have to add that termination explicitly:
spool E:\abc\Test\File1_&MYPeriod..csv
For the two extra lines issue, add set verify off; at the moment it is set to on (by default) so it shows you the old and new value of any substitution variables you use.
The only way I know to get the date into the file name is to put it into a substitution variable first:
set termout off
column x_run_dt new_value y_run_dt
select to_char(sysdate, 'YYYYMMDDHH24MISS') as x_run_dt from dual;
set termout on
spool E:\abc\Test\File1_&MYPeriod._&y_run_dt..csv
The new_value clause lets you create a substitution variable, &y_run_dt in this case, with a value from a queried column, x_run_dt. Wrapping the select that generates that value between set termout clauses hides it from the normal output, when run as a script.

Clear Screen in SQL*Plus

I'm running the following report but getting an error
/* Simple table formatting */
clear screen;
accept Report_File char prompt 'Enter a file name for summary report ';
/*Set up column headers*/
col StoreCode format A8 heading 'Store Code';
col DESCRIPTION format A8 heading 'Item Description';
col PRICE format $999999.99 heading 'Price';
col QUANTITY format 999 heading 'Quantity';
col (Price*Quantity) format $999999.99 heading 'Value';
/*Format and title pages */
set Pause off;
set Feedback off;
set Space 6;
set newpage 2;
set pagesize 54;
set linesize 200;
set underline =;
title center 'Current Stock Value by Store' skip 2 left -
'prepared by Jason Kemeys' &Report_Officer right -
&Todays_Date skip4;
btitle center format 999 SQL.PNO;
/* Set breaks and computes */
break on StoreCode skip 2 on SuppCode skip 1 on Report;
compute sum of (Price*Quantity) on StoreCode;
compute sum of (Price*Quantity) on Report;
/*Select data & send to file*/
spool &Report_File;
select StoreCode, Description, Quantity, Price, (Price*Quantity)
from Stocks
order by StoreCode;
spool off;
/* Clear all settings */
clear breaks;
clear columns;
clear computes;
set Pause on;
Just need to know why its showing the error and how to get it running; first time doing a report in SQL.
This is the error I'm getting
clear screen;
* ERROR at line 2: ORA-00900: invalid SQL statement
cl scr is the command used to clear screen in SQL.
I suspect this is dependent on the version of Oracle you are using.
This should work in version 11.2 but to quote from the 10g documentation:
CLEAR SCREEN is not available in SQL*Plus.
The same note isn't there in the 11.1 documentation, which would imply that you're using Oracle 10g or earlier. If this supposition is true then there's little that you can do.
It's possible that you can utilise the host command in SQL*Plus to run cls, if you're using Windows, or clear, if you're using Linux, but I'm not certain that it would have exactly the same effect. If it were possible it would simply be:
host cls
host runs an operating system command from SQL*Plus, and so will appear to clear the screen.
simply use cl scr command to clear the SQL plus.
Very few occurances of ";" in your code is actually needed. For example, the "clear screen" command to start with, doesn't need a semicolon. It will work, when you add one, but I wouldn't be sure about all the subsequent commands in that same file. Commands that need them, are limited to INSERT, UPDATE, DELETE, COMMIT, ROLLBACK, and such.
Secondly, if you get weird feedback from SQL-files, and if you have written them outside of Linux/Unix, this often ends up in SQLPLUS complaining about invisible characters. Look at that file via both VI and CAT commands, and note anything weird.