Clear Screen in SQL*Plus - sql

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.

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.

Need double quotes in each column while spooling data from oracle database to Excel file

I am automating a process wherein I run a SQL query through batch and the output is spooled into a csv file.
Requirement: Each field of csv file should have double quotes.
Ex :
Currently the output is PROJ_SHORT_NAME,WBS_SHORT_NAME
CGL1,CGL1
Required output is "PROJ_SHORT_NAME","WBS_SHORT_NAME"
"CGL1","CGL1"
SQL Query :
set verify off
set trimout off
set trimspool off
set feedback off
set linesize 22000
set pagesize 200
col csv_string FORMAT a1200
set colsep ','
SET UNDERLINE OFF
SET ECHO OFF
SPOOL E:\PDE_GPO\outputfile1.csv
select * from <tablename>;
SPOOL OFF
exit;
The || concatenates items together.
You can do:
SELECT '"'||col1||'","'||col2||'","'||...
FROM table
That would produce something like:
row 1: "col1val","col2val","col3val"...
row 2: ...
The down-side is you have to list/know every column you want to pull, but best coding practices would state you should specify the columns anyways (in case things are added/removed you want to be sure you get what you want).
-Jim
I got the solution for this.
I had to import set markup csv on and the issue got resolved.

which set command to display entire line in sql output to txt file

I am trying to output a query result to a txt file in Windows. The query is being executed in Oracle. I want to export the entire record one by one but gets cut off at the end, the query however displays the full line.
I thought the command:
SET linesize 2000 will do the trick but no luck:
Getting:
2702M11F13-XL 38550116-06 Test 3 325 http://www.test.com/clot
Should get (what shows in query output):
2702M11F13-XL 38550116-06 Text 3 325 http://www.test.com/clothing/outerwear/coats/test/hybridge-lite-vest/p/38550116 CAD
Please help.
Thanks in advance
It should be possible using set colsep
Refer to the Oracle Sql*Plus documentation for set colsep
Note that there's also set tab {on/off} which is used to convert tabs to spaces

Increase buffer size in JBSQL

I have some Oracle PL?SQL code that a user is trying to run using the JBSQL tool
There are a few dbms_output lines - when the user runs the code they get an error
ORA-06502: PL/SQL: numeric or value error: character string buffer too small
How do I increase the buffer size?
I've tried
SET SERVEROUTPUT ON SIZE 1000000;
but get "unknown option size". Is there a "default" command regardless of the tool to set the buffer size? Or can I add anything to my PL/SQL?
(Eventually I will write the lines to a table/text file but need to get this procedure up and running to show it is worthwhile - everything works absolutely fine - just the bit that notifies the user at the end!!!)
Any help gratefully received
Thanks
Mike
SET SERVEROUTPUT is a SQL*Plus command, it is not a SQL or PL/SQL command. It will only work in SQL*Plus or SQL*Plus-like tools (Toad, SQL developer...).
You can use DBMS_OUTPUT.enable(buffer_size) to increase the default output buffer size. Note however that your error could come from somewhere else: ORA-06502 is a generic error that can be raise by any assignment where the variable is too small.
SET SERVEROUTPUT ON SIZE n; is an SQL*Plus command, but many editors allow to use it. Anyways, can you try this instead:
BEGIN
DBMS_OUTPUT.ENABLE(BUFFER_SIZE => 1000000);
END;
What version of JBSql are you using? Normally, since version 1.1.0.2 the buffer size has been increased from 255 to 32767 characters. If it still fails with the latest version (1.3.0.0), then please provide a testcase to http://duofoto.be/mantis

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.