How to Rollback an Uncommitted DML in SQL*Plus

Goal In SQL*Plus, by default the DML (data manipulation language) transaction is committed to the database upon exit. Is there a way to rollback the transaction upon exit or prior to exiting the SQL*Plus session if the commit has not been explicitly defined? Solution From a SQL*Plus standpoint, there are 1 of 2 options: OPTION 1: 1. Use the following command prior to issuing any DML: SQL> set transaction use rollback segment test1; ... where test1 = a name you wish to rollback to should you want to reverse the changes back to this point 2. Before exiting, issue the rollback command: SQL> rollback; OPTION 2: 1. In the glogin.sql located in the $ORACLE_HOME/sqlplus/admin directory, add the below: Set transaction use rollback segment &rollback_segment; 2. When entering SQL*Plus, you will be prompted for a name -Enter value for rollback_segment: test1 NOTE: If you do not want to be prompted, then set a static name in place of the &rollback_segment in step 1, like: set termout off set transaction use rollback segment test1; set termout on 3. Then, if you wish to reverse the DML that has not been committed, then before exiting issue the rollback command: SQL> rollback;

How to Delete Line Feeds and Carriage Returns from Varchar2 Data?
Goal How to delete carriage returns and line feeds contained within the varchar2 field data? Solution You can perform the following nested replace sql statement using the replace command to delete the linefeeds and the carriage returns. SELECT REPLACE (REPLACE (column name, CHR (13), ‘’), CHR (10), '') FROM tablename;

How to Setup Date Format or Specific Variables in iSQL*Plus 9i?
Goal How to set NLS_DATE_FORMAT in iSQL* plus 9.2? Solution A- For a session you can user command: alter session set NLS_DATE_FORMAT... B- To set it permanently: 1- Modify the $ORACLE_HOME/sqlplus/admin/isqplus.conf file to add -initial-env for NLS_LANG and NLS_DATE_FORMAT as follow: <IfModule mod_fastcgi.c> FastCgiServer /emea/rdbms/32bit/app/oracle/product/9.2.0/bin/isqlplus -initial-env SHLIB_PATH -initial-env LD_LIBRARY_PATH -initial-env ORACLE_HOME -initial-env ORACLE_SID -initial-env TNS_ADMIN -initial-env NLS_LANG -initial-env NLS_NCHAR -initial-env NLS_LANG -initial-env NLS_DATE_FORMAT -initial-env iSQLPlusNumberOfThreads=20 -initial-env iSQLPlusTimeOutInterval=30 -initial-env iSQLPlusLogLevel=off -initial-env iSQLPlusAllowUserEntMap=none -idle-timeout 3600 </IfModule> 2- Set ENV variable at UNIX level NLS_LANG and NLS_DATE_FORMAT. 3- Restart apache. 4- Start sqlplus and the Date format will match NLS_DATE_FORMAT value.

What Is the Command that Replaces ''Spool'' in iSQL*Plus?
Goal Spool command is no longer a valid command in iSQL*Plus. What is the new command to replace it? Solution iSQL*Plus works in a different way to generate the output to file. The file output is html instead of text. Review iSQL*Plus -> Help -> The iSQL*Plus User Interface -> Output. It states: File: when the contents of the input area are executed, the resulting output is saved to a file. You are

prompted to enter the name of the file. As the output is in HTML format, it is useful to give the saved output file a .htm or .html extension. Steps to generate the output to file: 1) Invoke iSQL*Plus: http://host:port/isqlplus 2) In the User Interface, select output=file. 2) Select 'Execute' button. 3) Save the file. This is an html file. 4) Open the html file using your browser.

Commands Not Supported in iSQL*Plus
Goal This article lists SQL*Plus commands not supported in the iSQL*Plus user interface. Attempting to use any of the following unsupported commands or command options raises an SP2-0850 error message. Solution The following commands have no context in iSQL*Plus and have not been implemented. ACCEPT CLEAR SCREEN PASSWORD PAUSE

The following SET command variables have no context in iSQL*Plus and have not been implemented. SET EDITFILE SET FLUSH SET NEWPAGE SET PAUSE SET SHIFTINOUT SET SHOWMODE SET SQLBLANKLINES SET SQLCONTINUE SET SQLNUMBER SET SQLPREFIX SET SQLPROMPT SET SUFFIX SET TAB SET TERMOUT SET TIME SET TRIMOUT SET TRIMSPOOL

The following commands have security issues on the middle tier and have not been implemented. GET HOST SPOOL STORE

The following commands are SQL buffer editing commands which are not relevant in iSQL*Plus and have not been implemented. APPEND DEL INPUT

CHANGE

EDIT

SAVE

List/Table of General SQL*Plus 9.2 Limits
Goal The purpose of this article is to provide a list of general SQL*Plus limits. The limits shown are valid for most operating systems. Solution Item filename length username length user variable name length user variable value length command-line length LINESIZE LONGCHUNKSIZE value output line size line size after variable substitution number of characters in a COMPUTE command label number of lines per SQL command maximum PAGESIZE total row width maximum ARRAYSIZE maximum number of nested scripts maximum page number maximum PL/SQL error message size maximum ACCEPT character string length maximum number of DEFINE variables Limit system dependent 30 bytes 30 bytes 240 characters 2500 characters system dependent system dependent system dependent 3,000 characters (internal only) 500 characters 500 (assuming 80 characters per line 50,000 lines 60,000 characters for VMS; otherwise, 32,767 characters 5000 rows 20 for VMS, CMS, Unix; otherwise, 5 99,999 2K 240 Bytes 2048

length of a LONG value entered through SQL*Plus LINESIZE value

How to Get US Eastern Time No Matter of the Time Zone Location?
Goal The goal of this document is to provide one way of getting US Eastern Time No Matter of the Time Zone Location. Solution

If Oracle 9i or later is used then use the following sql statement: SELECT CURRENT_TIMESTAMP AT TIME ZONE '-5:00' AS eastern_time FROM dual; That gives you a TIMESTAMP. If a regular DATE is needed then CAST it as shown below: SELECT CAST (CURRENT_TIMESTAMP AT TIME ZONE '-5:00' AS DATE) AS eastern_time FROM dual;

How to Retrieve the Select Statement Used to Create a View?
Problem Description How can you see the SELECT statement used to create a view? When you try selecting the TEXT field from USER_VIEWS, you are not able to see the entire SELECT statement. Problem Solution In SQL*Plus, you must first execute SET LONG n, where n is an integer value greater than or equal to the value of the TEXT_LENGTH field in USER_VIEWS. For example: SQL> set long 999 SQL> select text from user_views where view_name like 'MYVIEW'; You should now be able to see a complete SELECT statement used to create MYVIEW.

How to Restrict User Access to Database Instances in iSQL*Plus?
Goal The article is intended to provide information about how to restrict user database instance access from iSQL*Plus. You may want to limit the databases instances that users can access in iSQL*Plus to a restricted list. When restricted database access has been enabled, a dropdown list of available databases is displayed in place of the Connection Identifier text field on the Login screen. This enables greater security for iSQL*Plus Servers in hosted environments. Solution Connection identifiers are listed in the order defined in iSQLPlusConnectIdList. Edit the $ORACLE_HOME/oc4j/j2ee/oc4j-applications/applications/isqlplus/isqlplus/WEB-INF/web.xml

xml .). database access is not restricted through iSQL*Plus.<param-value>ora10g. For example. or if the one given does not match an entry in iSQLPlusConnectIdList.ora file. Change the following entry to include a new paramvalue element which contains the list of databases to which you want to restrict access.<param-name>iSQLPlusConnectIdList</param-name> .<description>The database(s) to which iSQL*Plus users are restricted. Connection identifiers are listed in the order defined in iSQLPlusConnectIdList. and each connection identifier listed in the argument should be identical to an alias in the tnsnames. If there are no entries. separated by a semicolon (.file to restrict database access to iSQL*Plus users. Connection identifiers are case insensitive. the database connection is refused and the following error occurs: SP2-0884: Connection to database database_name is not allowed How to Output Two Records from a Single Record Depending on the Column Value? Goal . For Oracle 9i release 2 make the following changes in $ORACLE_HOME/sqlplus/admin/isqlplus. If no connection identifier is given.</description> . to only have ora10g and ora9i instance available: NOTE: A period is added to the text for readability. Do not include in the web. The list should contain the Oracle SIDs or SERVICE_NAMEs.<init-param> .Ora10gDB -idletimeout 3600 Restart iSQL*Plus for your changes to take effect.ora file.ora9i</param-value> .conf file Change the following line FastCgiServer <ORACLE_HOME>\bin\isqlplus -port 8228 -initial-env iSQLPlusNumberOfThreads=20 -initial-env iSQLPlusTimeOutInterval=2 -initial-env iSQLPlusLogLevel=off -initial-env iSQLPlusAllowUserEntMap=none -idle-timeout 3600 To FastCgiServer <ORACLE_HOME>\bin\isqlplus -port 8228 -initial-env iSQLPlusNumberOfThreads=20 -initial-env iSQLPlusTimeOutInterval=2 -initial-env iSQLPlusLogLevel=off -initial-env iSQLPlusAllowUserEntMap=none -initial-env iSQLPlusConnectIdList=Ora9iDB.</init-param> Entries in the param-value element should be identical to the alias for SERVICE_NAMEs or SIDs set in your $ORACLE_HOME/network/admin/tnsnames.

But for value = 3.-------721 1 722 2 723 3 and the required output is as follows : ID CELL ----. 2 from <your_table> where cell = 3 How to Exit with a Rollback from SQL*Plus Goal How to exit sqlplus with a rollback? Fix To prevent SQL*Plus from automatically committing all changes. you want to create two records that display values 1 and 2 (value for cell). column value (name: cell) is 1. you can use the 'ROLLBACK' or 'EXIT ROLLBACK' command before exiting. 3. such as INSERT. decode(cell.One of the column in a table has three valid values e. When you select the records along with other values. Actual output with standard select is as follows: ID CELL ----.-------721 1 722 2 723 1 723 2 How to split and resolve this in SQL? Fix The following SQL statement to achieves the desired output: select id. UPDATE. 2 and 3) in select statement. cell) cell from <your_table> union all select id. Now in the output value = 1 or 2 the single is ok.g. you will get all the three values (1. The SQL*Plus User Guide and Reference states the following: EXIT Purpose Terminates SQL*Plus and returns control to the operating system. 2 and 3. . The value 3 indicates that the record is both 1 and 2. 1. or DELETE command.

Syntax {EXIT|QUIT} [SUCCESS|FAILURE|WARNING|n|variable|:BindVariable] [COMMIT|ROLLBACK] By default the exit is with commit. Fix 1.1.1.1. connected as user2 you need to execute a script querying objects from Scott's schema like select * from dept.1.1.1)) where rownum<&maxlimit+2 The logic behind this query is that the CUBE is generating 2^n rows where n is the number of arguments to the CUBE function. It will display the prompt "Password: ". select rownum-1 from ( select 1 from dual group by cube (1.1. 64 rows which means you can generate numbers up to 63. Create hide_pswd. 128 rows.1)) where rownum<&maxlimit+2 The range can be increased by increasing the number of arguments to the CUBE function. How to Hide the Password Running a Script as a Different User? Goal How to hide a password to execute a script? For example. place the reply in a char variable named hide_password. To rollback you must do: exit rollback How to Generate Numbers 0 to N from a Query without PL/SQL? Goal How to generate numbers 0 to N from a query without any PL/SQL Fix select rownum-1 from ( select 1 from dual group by cube (1.sql script using hide option.1.1.1.e. In case you want to generate numbers beyond this range.e. and suppress the display: accept hide_password char prompt 'Password: ' hide connect scott/&&hide_password@aliasdb / select * from dept . then you need to add one more argument to the CUBE which would increase it to 2^7 rows i. In this case the inner subquery generates 2^6 rows i.

') .csv SQL> select * from emp.------------10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON How to Generate A Delimiter in Spool Output (Excel CSV file)? Goal How to generate a delimiter in spool output (Excel . be aware to include the delimiter.'||ename||'&'||mgr from X. Other option is using: SQL> set colsep '. comma.-------------. Example: select empno|| '. SQL> / DEPTNO DNAME LOC ---------. This will prompt for user password and will show it in hide mode (* instead of password): SQL> start hide_pswd.sql SQL> accept hide_password char prompt 'Enter password: ' hide Enter password: ***** SQL> connect scott/&&hide_password@aliasdb Connected. Change some of the default SQL*Plus parameters. you need to concatenate columns using the desired delimiter i.'./ 2. that will be garbage for Excel: feedback=off newpage=none termout=off header=off If some columns are empty.' SQL> spool c:\testexcel.e. too: nvl(to_char(col2).csv files)? Fix In order to generate a delimited file output.

.select the 5th lowest salary record from the EMP table. Fix Given the following data: SQL>SELECT SAL FROM EMP ORDER BY SAL DESC.Bottom 5th DISTINCT VALUE 1250 <--. the following can be used to find the 5th highest record from the EMP table: SELECT MIN(sal) from (select sal from emp order by sal desc) where rownum <= 5.select the 5th highest salary record from the EMP table. .Top 5th DISTINCT VALUE 1600 1500 1300 <--.Top 5th RECORD 2450 <--. MIN(SAL) . Also.select the 5th lowest salary DISTINCT value from the EMP table.How to Select N-th Highest Value from a Table? Goal This document provides the SQL statement which can be used to find the N-th highest or lowest value from a table column of NUMBER datatype. For example: . The general syntax to retrieve the TOP N-th record is : 1. SAL ---------5000 3000 3000 2975 2850 <--. For example.select the 5th highest salary DISTINCT value from the EMP table. .A.Bottom 5th RECORD 1250 1100 950 800 1. Select MIN(column_name) from (select column_name from table_name order by column_name desc) where rownum<= N. provides the N-th highest or lowest DISTINCT value of a table column.

sal) FROM EMP tmp WHERE temp.sal).A. Select MAX(column_name) from (select column_name from table_name order by column_name ) where rownum<= N. A method without using MIN () to find the top 5-th record is: SELECT distinct (temp. A method without using MAX() to find the lowest N-th DISTINCT VALUE is: . SAL ---------2850 2.---------2850 1. SAL ---------1250 4.B. For example.sal) FROM EMP temp WHERE 5= (SELECT COUNT (tmp. SAL ---------2450 3. The general syntax to retrieve the TOP N-th DISTINCT VALUE is : 2. For example.sal) FROM EMP temp WHERE 5 = (SELECT COUNT (DISTINCT (tmp. A method without using MAX () to find the bottom N-th RECORD is: SELECT distinct (temp. the following can be used to find the 5th highest distinct salary from the EMP table: Select MIN(sal) from (select distinct sal from emp order by sal desc) where rownum <= 5.sal). B.sal) FROM EMP temp WHERE 5 = (SELECT COUNT (tmp. A method without using MIN () to find the top N-th DISTINCT VALUE is: SELECT DISTINCT (temp.A. For example. the following can be used to find the 5th lowest DISTINCT value from the EMP table: Select MAX(sal) from (select distinct sal from emp order by sal) where rownum <= 5.sal>=tmp. B.sal).sal)) FROM EMP tmp WHERE temp. Select MIN(column_name) from (select distinct column_name from table_name order by column_name desc) where rownum<= N. The general syntax to retrieve the N-th DISTINCT VALUE from the BOTTOM is as follows: 4.sal<=tmp.B. The general syntax to retrieve the N-th RECORD from the BOTTOM is as follows: 3. Select MAX(column_name) from (select distinct column_name from table_name order by column_name ) where rownum<= N. the following can be used to find the 5th lowest RECORD from the EMP table: SELECT MAX(sal) from (select sal from emp order by sal) where rownum <= 5.A. MAX(SAL) ---------1250 3.sal) FROM EMP tmp WHERE temp. MAX(SAL) ---------1300 4. MIN(SAL) ---------2450 2.sal<=tmp.

you still get the connected message. It is the second connection that is echoed. If you need the /nolog. 2. How to stop the "Connected. 3.A.B.sal) FROM EMP temp WHERE 5 = (SELECT COUNT (DISTINCT (tmp. SAL ---------1300 HOW TO MAKE THE SELECT STATEMENTS ABOVE MORE DYNAMIC? In examples 1. 2. 3.SELECT DISTINCT (temp.A.sal>=tmp.A.sal). Instead start sqlplus as: sqlplus -s / 2. and 4..A.B. Example: sqlplus -S /nolog conn / Connected. then use grep to exclude the Connected line as follows: sqlplus -S /nolog | grep -v Connected ..B.. use the following modification to the query: From … WHERE 5 = (SELECT COUNT… To …WHERE &N = (SELECT COUNT… This change will cause the following prompt for the user: Enter value for n: <user puts in value> How to Stop 'Connected' Message when Running SQLPlus in Silent Mode? Goal When you start sqlplus in silent mode.. Do not use the "/nolog" option.." from appearing? Fix 1. use the following modification to the query: From … where rownum <= 5... This is causing 2 connections. In examples 1. and 4.sal)) FROM EMP tmp WHERE temp. To … where rownum <= &N..B.

in '&' substitution variables. There are four new predefined variables: Predefined Variables: _DATE. Date and/or Privileges? Goal To explain the new predefined variables introduced in 10g and how they can be used to make the SQL*PLUS Prompt display more informative. for example. _PRIVILEGE contains the privilege level of the current connect. They can used in your SQL*Plus command line prompt by using the SET SQLPROMPT command. This is the same as the output from the SHOW USER command. _PRIVILEGE. enter: SET SQLPROMPT "_USER'@'_CONNECT_IDENTIFIER > " You can view the predefined variable definitions in the same way as you view other DEFINE definitions. This will be either AS SYSDBA. or with the specific argument you wish to display. AS SYSOPER or blank to indicate a normal connection. _USER contains the username as supplied by the user to make the current connection. Fix You can now use substitution variables in the SQL*Plus command-line prompt to display. These variables are available only in 10g. _CONNECT_IDENTIFIER _DATE contains the current date or a user defined fixed string. For example. for example: Using DEFINE to display these variables: SQL> DEFINE DEFINE _DATE = "16-MAR-04" (CHAR) DEFINE _CONNECT_IDENTIFIER = "isc101" (CHAR) DEFINE _USER = "SYS" (CHAR) DEFINE _PRIVILEGE = "AS SYSDBA" (CHAR) . and then your connection identifier (_CONNECT_IDENTIFIER) during your session. These variables can be accessed like any other substitution variable. or other information available through a substitution variable you choose. they could be used in TTITLE. using the DEFINE command with no arguments. the database and server you are connected to.How to use New Predefined Variables to Set SQLPROMPT to Display the User. to make your prompt always show your username (_USER). the @ symbol. _USER. _CONNECT_IDENTIFIER contains the connection identifier information. For example.

You can use the notes referenced below for the same. enter: SQL> SET SQLPROMPT "_DATE _USER _PRIVILEGE> " 17-MAR-04 SCOTT > 4.----or to display on one variable: SQL> DEFINE _PRIVILEGE DEFINE _PRIVILEGE = "AS SYSDBA" (CHAR) Uses UNDEFINE to remove variable definitions. You need the 'Select Any Table' privilege to successfully run the following example scripts.Enterprise Edition 8 fact: MS Windows NT . How to use these variables with SQLPROMPT? SET SQLP [ROMPT] {SQL> | text} Note: SET SQLPROMPT is not supported in iSQL*Plus Variable substitution occurs each time SQLPROMPT is SET. Since text in nested quotes is not parsed for substitution.Enterprise Edition 7 fact: Oracle Server . followed by "@". the current user and the users privilege level. 1. How To Interpret The Time Format • • • • goal: How To Interpret The Time Format fact: Oracle Server . enter: SQL> SET SQLPROMPT "_USER'@'_CONNECT_IDENTIFIER > " SCOTT@isc101 > At present there is no predefined variable to display the database you are connected to. To set the SQL*Plus command prompt to show the current user. To change your SQL*Plus prompt to display your the current date. enter SQL> SET SQLPROMPT "_USER > " SCOTT > 3. to have a SQL*Plus prompt of your username. then substitution variables in SQLPROMPT are refreshed with each login or connect. To change your SQL*Plus prompt to display your connection identifier. and then your connection identifier.sql. If SQLPROMPT is included in glogin. enter: SQL> SET SQLPROMPT "_CONNECT_IDENTIFIER > " isc101 > 2. enter: SQL> DEFINE Instance = Prod SQL> SET SQLPROMPT Instance> " Prod> 5. To change your SQL*Plus prompt to display a variable you have defined.

the Hours and Minutes must be removed from the total. But here we use outer join to achieve this.SLEEP VALUES GREATER THAN 1 MINUTE The seconds overflow (60 seconds = 1 minute) will not reset the seconds counter so it's possible that the seconds field gets more than 2 digits (>60)! Example: Elapsed: 01:05:3909.35 . Above example: hours: 1 minutes: 5 seconds: 3909. Interpretation: Elapsed: 00:00:00.(5*60) = 9.• fact: SqlPlus Fix: SQL> set timing on After the SQL statement is executed the time needed for processing the statement is printed into the next line.32 ^ ^ ^ ^ | | | | | | | milliseconds | | seconds | minutes hours SPECIAL NOTE: The seconds field will represents the TOTAL TIME in seconds.(1*3600) . Abstract: ELAPSED TIME SHOWS INCORRECTLY FOR DBMS_LOCK.32 To find the actual seconds. SCOPE & APPLICATION .32 Converts to: hours: 1 minutes: 5 seconds: 9 milliseconds: 32 How to Display a Master Detail Relationship in One Row? PURPOSE How to display columns as rows? This is similar to other line-column transposition that may be in use.

insert insert insert insert insert insert into into into into into into parent parent parent parent parent parent values values values values values values ('E0001'. 'MOTHER-SALLY'). ('E0004'. 'FATHER-JOHN'). b.Developers and DBAs (For reporting) SQL> create table parent (ChildNo varchar2(5). ('E0002'. parent mother from parent where parent like 'MOTHER%') b. 'FATHER-WILLIAM'). parent father from parent where parent like 'FATHER%') a. 3 (select childno. ('E0002'. parent varchar2(20)). SQL> select * from parent. 4 parent c 5 where c.childno.childno(+) CHILD ----E0001 E0002 E0003 E0004 FATHER -------------------FATHER-JOHN FATHER-BLAKE FATHER-WILLIAM MOTHER -------------------MOTHER-NANCY MOTHER-SALLY MOTHER-JULIE How To Calculate The Number of Days betweeen Two Dates Excluding Weekends? • • Goal: How to calculate the number of days betweeen two dates excluding weekends fact: Embedded SQL Fix: A table called DATETABLE has two columns BEGDATE and ENDDATE:- .childno=a. ('E0003'.childno=b. ('E0001'. 'MOTHER-JULIE'). a.father.childno(+) 6* and c.mother from 2 (select childno. 'MOTHER-NANCY'). CHILD ----E0001 E0001 E0002 E0002 E0003 E0004 PARENT -------------------FATHER-JOHN MOTHER-NANCY FATHER-BLAKE MOTHER-SALLY FATHER-WILLIAM MOTHER-JULIE SQL> select distinct c. 'FATHER-BLAKE').

To successfully run the above script.trunc(begdate+6.0) + decode(to_number(to_char(begdate. rem rem (trunc(enddate.'D') .3. i.4.4.trunc(begdate+6.'D') .5.3.3.'D') .rem Calculates the difference between two dates and gives you a number excluding weekends.7.3. rem rem + decode(to_number(to_char(begdate.2.2. rem This part calculates the difference in whole weeks and then subtracts out the weekends.'D')). you need the Select Any Table privilege.5.0) days from datetable / Setting the SQL*Plus Prompt to Show Instance Name (SID) How to set the SQL*Plus prompt to show your SID.2.2.'D'))/7)*2) + decode(to_number(to_char(enddate.2.(((trunc(enddate. when you use the connect command to logon to another instance.'D')). NOTE: from version 9.5.'D'))/7)*2) rem rem This part calculates the number of work days in the end week.5. select (trunc(enddate.e.1.3.4. set sqlprompt '&y SQL> ' set termout on Remember this is NOT dynamic.'D')).6.5. set termout off col x new_value y select rtrim(instance.3.6.'D')) .3.chr(0)) x from v$thread.4.5.0) rem days eg.6.'D')).1.5.3.4. rem rem + decode(to_number(to_char(enddate. You need to reset it when you change instances.4.5.6.4.2 this syntax can be used to SET SQLPROMPT "&_CONNECT_IDENTIFIER>" How to Insert a Carriage Return in the Middle of a Select Statement .trunc(begdate+6.4.1.'D') .1.2.trunc(begdate+6.7.(((trunc(enddate.'D')) rem .0) rem rem This part calculates the number of work days in the start week rem minus Sunday start day workaround.

'||chr(10)||job 2* from emp SQL> / TESTCASE DETAILS: TESTCASE 1: SQL> ed Wrote file afiedt.'||ename||'. Pipes will be used instead of comma delimiters and the output will need to be looked like this: D|val1|val2|valx| F|val1|val3|valx| A|val1|val4|valx| Fix Basically. val3.'^M'.val4.buf 1 select empno||chr(10)||ename||chr(10) 2* from emp SQL> / EMPNO||CHR(10)||ENAME||CHR(10)||JOB -----------------------------------------7369 SMITH CLERK 7499 ALLEN SALESMAN 7521 WARD SALESMAN EMPNO||CHR(10)||ENAME||CHR(10)||JOB ------------------------------------------ .buf 1 select empno||'.'^M' from value_table. carriage return --> CHR(10) but has to be used with the concatenate symbol '||'. 'F'.'A'. val2. For Example: Select 'D'.val1. '^M'.Goal Trying to do a long select that will ultimately result in 3 lines of output separated by carriage returns.val1.val1. TESTCASE 3 below is probably the closest to what you are looking for: For Example: SQL> ed Wrote file afiedt.

MARTIN.PRESIDENT 7844.WARD..MANAGER 7788.SCOTT.CLERK 7499.'||job||chr(10) 2* from emp SQL> / EMPNO||'.CLERK .'||JOB||CHR(10) -------------------------------------------------------7369.KING. etc TESTCASE 2: ========== SQL> ed Wrote file a 1 select empno||'.ALLEN.SALESMAN 7566.JAMES.7566 JONES MANAGER 7654 MARTIN SALESMAN 7698 BLAKE EMPNO||CHR(10)||ENAME||CHR(10)||JOB -----------------------------------------MANAGER 7782 CLARK MANAGER 7788 SCOTT ANALYST .JONES.ANALYST 7839.'||ENAME||'.CLARK.'||ENAME||'.'||ename||'.SMITH.SALESMAN 7521.BLAKE.ADAMS.MANAGER 7782..CLERK EMPNO||'.TURNER.SALESMAN 7876.SALESMAN 7698.'||JOB||CHR(10) -------------------------------------------------------7900.MANAGER 7654.

.'||chr(10)||job 2* from emp SQL> / EMPNO||'.buf 1 select empno||'.WARD. 2) Profit of the company in the current quarter and Next quarter in same row. etc How to show the values of a column in a row for both previous/current record Goal How To show the values of a column in a row for both previous/current record ? Suppose a customer wants to show the 1) Profit of the company in the current quarter and Last quarter in same row.'||ENAME||'.. Fix Let us assume customer has the following table structure.MILLER.7902. SQL> desc QR_Profit Name Null? Type ----------------------------------------.'||ename||'.------------------- . MANAGER .would be something like this: SQL> ed Wrote file afiedt. CLERK 7499.-------.ANALYST 7934.D|val1|val2|valx| -. ..SMITH. TESTCASE 3: Closest to the format -.CLERK 14 rows selected.'||CHR(10)||JOB ---------------------------------------------------------7369.FORD.ALLEN.JONES. SALESMAN 7521. SALESMAN 7566.

lag(profit.-----------31-DEC-02 10 0 31-MAR-03 11 10 30-JUN-03 12 11 30-SEP-03 12 12 Following query will show "Profit in the current quarter and Next quarter in same row. YRQR PROFIT NEXT_QUARTER --------.lead(profit.0) over (order by yrqr) Last_Quarter from QR_Profit.1. SQL> select yrqr. the datas are represented as row format.---------. YRQR PROFIT LAST_QUARTER --------.---------31-DEC-02 10 31-MAR-03 11 30-JUN-03 12 30-SEP-03 12 Following query will show the " profit for current quarter and Last quarter in same row " SQL> select yrqr .e. profit. to represent in rectangular format ( popularly know as matrix format ) Where you will have a row attribute. ".0) over (order by yrqr) Next_Quarter from QR_Profit. But to analyze the data the above format would not be enough .---------.YRQR DATE PROFIT NUMBER SQL> select * from QR_Profit.1. . profit. YRQR PROFIT --------. there you need data in 3-dimensional format i. column attribute and cell which shows the values for the corresponding row and column attribute . . That means each record in the table is represented in row.-----------31-DEC-02 10 11 31-MAR-03 11 12 30-JUN-03 12 12 30-SEP-03 12 0 How to Create a Matrix Report in SQLPLUS Goal When you query any table in relational database.

--------7369 20 17-DEC-80 7499 30 20-FEB-81 7521 30 22-FEB-81 7566 20 02-APR-81 7654 30 28-SEP-81 7698 30 01-MAY-81 7782 10 09-JUN-81 7788 20 19-APR-87 7839 10 17-NOV-81 7844 30 08-SEP-81 7876 20 23-MAY-87 EMPNO DEPTNO HIREDATE ---------. EMPNO DEPTNO HIREDATE ---------.'RRRR'). select deptno. "1981".---------.deptno.1.'1981'. Fix Here I am showing an example shows the no.0)) sum(decode(to_char(hiredate.The same output format can be easily designed thru Oracle Reports writer . "1987" .0)) sum(decode(to_char(hiredate.hiredate from emp.1. sum(decode(to_char(hiredate. The query is based on Scott.Eg.'RRRR').'1982'. "1982".'RRRR').---------.'1987'.'1980'.of people joined in a department on year basis. Now the same query represented in matrix format .1.--------7900 30 03-DEC-81 7902 20 03-DEC-81 7934 10 23-JAN-82 14 rows selected.'RRRR').0)) from emp group by deptno "1980".1.EMP table. SQL> select empno. Col1 Col2 Col3 Col4 Row1 Row2 Row3 Row4 How to achieve the same in sqlplus without using any other tools? Note :.0)) sum(decode(to_char(hiredate.

We want to check the column CUSTID with a particular format like 99 .DEPTNO 1980 1981 1982 1987 ---------.---------. of employee joined to departments in the above years. CUSTID ---------IN-CTC-001 IN-BNG-001 . then the column need to be defined in query.column in the same format.-------CUSTID VARCHAR2(10) SQL> select * from customer.So that we can update all records of the table. '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-'. Note: .Write the query to get the result SQL> SELECT custid FROM customer where TRANSLATE(CUSTID. Fix Let us take an example for table Customer SQL> desc customer Name Null? Type ----------------------------------------. How to Check a Particular Format for Any Field thru SQL Goal How to validate the data saved in a column ? Let us assume a table CUSTOMER with lot of records saved. CUSTID ---------IN-CTC-001 IN-BNG-001 IN-BNG-12 IN-MUM-01 We need to check if any of these records keeps the format 'XX-XXX-999'' . '9999999999XXXXXXXXXXXXXXXXXXXXXXXXXX-') ='XX-XXX-999'. That means for each column and corresponding cell values to display.The only drawback here is the column can not be added automatically.---------.---------10 0 2 1 0 20 1 2 0 2 30 0 6 0 0 Which shows the no.--------.

. This way. The example uses the dept table: SELECT * FROM dept a WHERE ROWID <>(SELECT MAX(ROWID) FROM dept b WHERE a.dname = b. To allow the User to just view the source code of the Procedure. 2) Grant select on the View created above. The following statement will delete all duplicate rows in a table.deptno = b. How to Find or Delete Duplicate Rows in a Table PROBLEM DESCRIPTION: How do you find or delete duplicate rows in a table? SOLUTION DESCRIPTION: The following SELECT statement will find and display all duplicate rows in a table.dname = b. try the following: 1) Create a view like: create view view_name as select text from all_source where type='PROCEDURE' and name='PROCEDURE-NAME'.dname AND a.dname AND a.View the Source Code Of A Procedure Goal Is it possible to provide a Grant such that User can view only the source code of Procedure but not execute it.loc).deptno = b. Fix A Grant option would allow the user to execute the Procedure. except the row with the maximum ROWID: DELETE FROM dept a WHERE ROWID <> (SELECT MAX (ROWID) FROM dept b WHERE a.loc).loc = b. the user can do a select of the View.loc = b. except the row with the maximum ROWID.deptno AND a. and see the source code of the Procedure.deptno AND a.

How do I create a flat ASCII file without rows wrapping? PROBLEM DESCRIPTION: You want to create a flat file with the output from a SQL query.loc = b. Duplicate rows which contain only null columns. On most hosts it is LST or LIS. will not be identified by either of the two methods above. The default varies with the host operating system.dname = b.Alternatively: DELETE FROM dept a WHERE 1 < (SELECT COUNT (deptno) FROM dept b WHERE a.deptno = b. simply: DELETE FROM dept WHERE deptno IS NULL AND dname IS NULL AND loc IS NULL. SPOOL adds a default file extension to the filename to identify it as an output file.deptno AND a. How can you prevent this wrap-around? SOLUTION DESCRIPTION: To store the SQL query results in a file. When you execute the query. however.dname AND a. you need to enter the SPOOL command in SQL*Plus: SQL> SPOOL file_name If you do not follow the filename with a period and an extension. ROWID represents a unique storage identification number for a single row in a table (Note: Two rows on different tables but stored in the same cluster may have the same rowid value). In such a case.loc). EXPLANATION Using the pseudo column ROWID is the fastest way to access a row. you first must enter the following: SET commands in SQL*Plus: SET SET SET SET NEWPAGE O SPACE 0 LINESIZE 80 PAGESIZE 0 . the rows are wrapped around. To create a flat file in SQL*Plus.

'hh:mi:ss'). then displays in hh:mm:ss select to_char(sysdate. 10). If you do this. (If the line size is too small. How do I create an output file with commas between the columns? You will need to produce a . The following SELECT gives you the seconds past midnight. date is the same.1. 'sssss'). Solution Description: Use a format mask without characters. . 1. to_char(sysdate. 'sssss'). substr(trunc(mod(to_char(sysdate. 10). 'hh:mm:ss') from dual. substr(trunc(to_char(sysdate. 2. The following SELECT will convert the seconds past midnight back to display as hh:mm:ss select substr(to_char(sysdate.8). Solution Explanation: 1. How do I calculate an average date with time component? Problem Explanation: You want to calculate the difference between two average timestamps.SET ECHO OFF SET FEEDBACK OFF SET HEADING OFF After entering these commands. you may set it to a larger number. use the SPOOL command as above to create the flat file. substr(to_char(sysdate.3600)/60).8). AVG(TO_NUMBER(TO_CHAR(A.1.'MMDDYYHHMI') ) ) from x. 'sssss')/3600).'MMDDYYHHMI'))) --------------------------------------101960115 The average time of 1:10 and 1:20 gives 1:15 for the hours. 'sssss'). If a table (x) has a date field (a) with two rows 01-jan-96 01:10 01-jan-96 01:20 SQL> select avg( to_number( to_char(a. you may need to use another command 'SET BUFFER xxxx' where xxxx is the same size as the line size).SQL file for the table so that the table output will have commas between the columns. 1.

then SQL*Plus will understand the special character following the escape symbol is to be treated as a regular character. 10) from dual.3600). fact: Oracle Server . 'sssss'). How to embed Single Quote in a string . • • goal: How to insert & character or special character into Database using SQL*Plus. Example: SQL>set escape on SQL>show escape escape "\" (hex 5c) SQL> INSERT INTO temp_table VALUES ('select * from emp where ename = \& 1'). 1. 1 row created. set the substitution character to one which will not be encountered when inserting data. Solution 3: If you precede the special character with a backslash and the ESCAPE setting in SQL*Plus is set to ON.Enterprise Edition Fix: Solution 1: If you are not using substitution variables (&1 &2 &3 etc. Example: SQL> SET DEFINE OFF SQL> INSERT INTO <table_name> VALUES ('AT&T').) you can do a "SET DEFINE OFF" or "SET SCAN OFF" to turn off the definition of the ampersand as a substitution variable. Example: SQL> SET DEFINE % SQL> INSERT INTO <temp_table> VALUES ('AT&T') / 1 row created.60).substr(mod(mod(to_char(sysdate. / 1 row created Solution 2: If you are using substitution variables. How to insert & character or special character into Database using SQL*Plus.

Problem Description: How do you embed single quotes ( ' ) into a character string? How do you concatenate a quote in SQL? How do you place quotes around a character string in a SQL query? How do you store an apostrophe into a character variable in PL/SQL? Problem Explanation: Example 1 When you issue either of the following SELECT statements: SQL> SELECT ' FROM dual. Example 1 --------SQL> SELECT 'test' || CHR(39) || 'case' result 2> FROM dual. RESULT --------test'case Example 2 --------SQL> SELECT CHR(39) FROM dual. C ' . the following error occurs: ORA-00923: FROM keyword not found where expected quoted string not properly terminated CONCATENATE CHR(39) TO CREATE LITERAL SINGLE QUOTE Solution Description: To create a single quote. the following error occurs: ORA-0xxx: Example 2 When you issue the following SELECT statement: SQL> SELECT ''character string in quotes'' FROM dual. concatenate CHR(39) to the string. SQL> SELECT ''' FROM dual.

The single quote is a string delimiter. ---> test'case ---> test''case . ' ' Example 3 --------SQL> SELECT 'test' || '''' || 'case' result 2> FROM dual. concatenate 4 single quotes: '''' The two single quotes in the middle define the single quote. Example 2 --------SQL> SELECT '''' FROM dual. Inside a string literal. Example 1 --------6 single quotes: 'test' || '''''' || 'case' ---> test''case 8 single quotes: 'test' || '''''''' || 'case' ---> test'''case You can also implement the above in the following way: 'test''case' 'test''''case' Hence: a. To create a single quote. Enclose every character string in single quotes. ASCII('''') ----------39 USE 2 SINGLE QUOTES TO CREATE 1 SINGLE QUOTE Solution Description: Keep the following two rules in mind: 1. The outside single quotes are the single quotes that must surround a string.Solution Explanation: To return the ASCII value of the single quote ( ' ): SQL> SELECT ASCII('''') FROM dual. use two consecutive single quotes to create a literal single quote. 2.

To place single quotes around a character string. it is the other single quote that surrounds the string. The third single quote closes the character string. The second and third single quotes define the literal single quote. enclose the character string within 3 single quotes: ''' At the start of a character string: the first single quote defines the start of the character string. q CHAR(1) := ''''. NULL. this is the SELECT statement sent to the database: SELECT DECODE(dname.DO_SQL('SELECT DECODE(dname.RESULT --------test'case b. At the end of the character string: the first and second single quotes define the literal single quote. String "a" stores: 'this is a 'quoted' string' How to do a case insensitive search using the 'LIKE' operator? . BEGIN a := '''this is a ' || q || 'quoted'' string' || q. NULL. 'A') FROM dept WHERE deptno = 10 Example 6 --------DECLARE a VARCHAR2(200). As a result. RESULT ---------------------------'character string in quotes' Solution Explanation: More examples: Example 5 --------SRW. Example 4 --------SQL> SELECT '''character string in quotes''' result 2> FROM dual. ''A'') FROM dept WHERE deptno = 10'). END. ''NONE''. 'NONE'. It is one of the two single quotes that surround the string.

'MacDonald' and MACDONALD' how can a single SQL query using the LIKE operator find all occurrences of the name MacDonald. or extra characters embedded ). For example. CONCATENATE COLUMN SEPARATOR IN QUERY AND SPOOL Solution Description: Concatenate the desired column separator into the query. For example the strings 'smith' and 'Smith' and 'SMITH' will all become 'SMITH'. Solution Explanation: The UPPER function converts the ename field results in the searched column to upper case. DEPTNO||CHR(9)||DNAME ------------------------------------------------------10 ACCOUNTING 20 RESEARCH . headings. for example. it is sometimes necessary to use a "flat" file ( an operating system file with no escape characters. Solution Description: You can use the UPPER () function to perform a case insensitive match as in the following condition.Problem Description: How can a user perform a case insensitive match using the LIKE comparison operator? Problem Explanation: The field in a table may be entered in different cases. For example: To delineate column text with TABs: ----------------------------------SQL> select DEPTNO || CHR(9) || DNAME FROM DEPT. to find an employee name in a string beginning with the letters 'SM' SQL > select * from emp where UPPER (ename) like 'SM%' . How to Create Column Delimited Flat File Problem Description: How can SQL*Plus be used to create a delimited flat file? Problem Explanation: When moving data between different software products.

30 40 SALES OPERATIONS The CHR() SQL character function is used to embed the TAB in the query text.ACCOUNTING 20. To delineate column text with COMMAs: ------------------------------------SQL> select DEPTNO || '.x do not have a SET command to specify a column separator to delineate text between columns. the result has datatype VARCHAR2 and is limited to a maximum result of 2000 characters.'||DNAME ------------------------------------------------------10.2. DEPTNO||'. If either string is VARCHAR2. use the following SQL*Plus SET commands before running your query: SET TERMOUT OFF SET NEWPAGE 0 SET SPACE 0 SET LINESIZE 80 SET PAGESIZE 0 SET ECHO OFF SET FEEDBACK OFF SET HEADING OFF SPOOL file_name < your query> SPOOL OFF SET TERMOUT ON Solution Explanation: SQL*Plus versions 3.SALES 40.RESEARCH 30. If both character strings are of datatype CHAR.OPERATIONS To send your query results to a file.x and 3.x COLSEP SET command.0.1. the result has datatype CHAR and is limited to a maximum result of 255 characters. Solution Description: Use the SQL*Plus 3.' || DNAME FROM DEPT. NOTE: The result of concatenating two character strings is another character string. For example: .

x has the COLSEP SET command. use the following SQL*Plus commands: SET TERMOUT OFF SET NEWPAGE 0 SET SPACE 0 SET LINESIZE 80 SET PAGESIZE 0 SET ECHO OFF SET FEEDBACK OFF SET HEADING OFF SET COLSEP '. e. with the text printed between the SELECTed columns as specified by the SET COLSEP command. Method to create .g. you must enclose the text with single quotes.SQL REM extension supplied automatically REM ********************************************************************* * . % for all) REM outputfilename: Target SQL file name (no extension.SQL file for the table so that the listed table output will have comma's between the columns. . Previous versions of SQL*Plus did not have COLSEP. REM ********************************************************************* ***** REM COMMA.SQL file with comma-delimited output. This solution will send the query results to a file.2. SOLUTION DESCRIPTION: The SQL script below when executed will produce a second . If the COLSEP variable contains blanks or punctuation characters.SQL REM -----REM Generate SELECT statements using Catalog tables REM REM Usage: @COMMA tablename outputfilename REM REM tablename: Any table name (standard SQL wildcards accepted.To send your query results to a comma delimited flat file.' SPOOL file_name < your query> SPOOL OFF SET TERMOUT ON Solution Explanation: SQL*Plus 3.

3 SPOOL &2. column_id seq2 . 0 seq2 .sql // SPOOL OFF SET SET SET SET FEEDBACK ON VERIFY ON TERMOUT ON HEADING ON . 3 seqno .'||''.SET SET SET SET SET FEEDBACK OFF VERIFY OFF TERMOUT OFF PAGES 999 HEADING OFF COL tabname NOPRINT COL seqno NOPRINT COL seq2 NOPRINT SELECT table_name tabname .'' .1..2.table_name = user_tab_columns. 1 seqno .table_name ) UNION SELECT table_name . DECODE(column_id . 'SELECT ' txt FROM user_tables WHERE table_name LIKE UPPER('&1') UNION SELECT table_name tabname . 0 seq2 .' txt FROM user_tables WHERE table_name LIKE UPPER('&1') ORDER BY 1.''||')||column_name txt FROM user_tab_columns WHERE table_name LIKE UPPER('&1') and exists ( select 1 from user_tables where user_tables. 2 seqno . 'FROM '||table_name||'.

The query returns the first "n" ordered rows. second SELECT statement controls the condition.column >= A.column) ORDER BY column DESC.column) ORDER BY column DESC.g. Hence. Specifying DISTINCT return all rows whose column (e. If n=10 and Rows 8-12 share the same column value.column >= A. "table" is the name of the table and "column" is the name of the column. sal) value falls into one of the top "n" values. create a query similar to the following: SELECT * FROM table A WHERE n >= (SELECT COUNT(*) FROM table B WHERE B.How to Query top "N" rows ordered by a column Problem Description: What SQL SELECT statement do you use to retrieve the top "n" rows ordered by a particular "column"? Problem Explanation: Solution Description: To return exactly "n" rows ordered by a column. create a query similar to the following: SELECT * FROM table A WHERE n >= (SELECT COUNT (DISTINCT column) FROM column B WHERE B. this only return Rows 9 and 10. while the nested. How do you convert a character field into a date format without losing the century data? Problem Description: . The above SELECT statement does not take duplicate column values into consideration. The first SELECT statement controls the number of rows. the query returns more than "n" rows when several rows share the same column value. Solution Explanation: To return any row whose column value is one of the top "n" ordered column values. where "n" is the number of rows to be retrieved and ordered.

Example: SQLPATH = C:\ORANT\DBS. 'DD-MON-YYYY'). each separated by a semicolon. In Windows environment.C:\MYSCRIPTS. SELECT SYSDATE INTO mydate FROM DUAL.ini How do I get the system date and time over DBLINK? You cannot use SYSDATE or USER.When you convert a character field into a date field. END. CREATE TABLE db_table (mydate DATE). if you are using 32-bit SQL*Plus then set this variable in the Registry. USER.'DD-MON-YYYY') --------------------------------------------------------------------------17-NOV-1981 How do I set the SQL*Plus search path for SQL scripts? Answer Set SQLPATH environment variable. . How do you convert a character field into date format without losing the century data? Solution Description: To retain the four digit century information. INSERT INTO db_table VALUES (mydate).C:\APPS\SCRIPTS. For example the query is: SQL> select TO_CHAR (HIREDATE. you can use the following workaround: Step-1: On the remote machine. or if you are using 16-bit SQL*Plus then set this variable in the file Oracle. 'DD-MON-YYYY') from EMP Where HIREDATE = TO_DATE ('17-NOV-1981'. populate a table with the SYSDATE. the century information is lost. Add all the directories you want SQL*Plus to search for the SQL scripts. values using a stored procedure on the remote machine. For this. BEGIN DELETE FROM db_table. CREATE OR REPLACE PROCEDURE db_date as mydate date. The results of the query which show the full four character century are: TO_CHAR (HIREDATE. USER over DBLINK due to a known restriction with these functions. you must convert the date field back into a character string. to get the SYSDATE.

fld2 ORDER BY fld1.tab2 WHERE x=y GROUP BY fld1. host dir/p EXIT. Suppose the contents of script. COMPUTE SUM OF Y ON X.sql will execute the script script. Executing the above example command will display the emp records in the SQL*Plus window and would list the directory in a command window. The data returns in the following format: 01-SEP-94 15:01:01 How do you skip a page in a SQL*Plus report? You can skip a page in SQL*Plus reports by making use of the following statement: BREAK ON X SKIP PAGE. use the TO_CHAR function with a format mask. :global.fld2 FROM tab1. 'DD-MON-YY HH24:MI:SS') FROM mytable.sql on 'c' drive. . EXECUTE db_date@dblink SELECT mydate FROM db_table@dblink. How do I execute SQL scripts in batch? You can execute any SQL script using the SQL*Plus command in a batch file. SELECT fld1. 'DD-MON-YY HH:MI:SS'). How do I display the time component of a date column? To retrieve the time information.Step-2: On local machine.hi := To_Char(:time1. Examples: SELECT To_Char(datecolumn. The 'exit' command in the last line will close the SQL*Plus session.sql is as follows: SELECT * FROM emp. The format of the command is as follows: SQL*Plus-Executable USERNAME/PASSWORD@CONNECT_STRING Sql-script For Example: Plus31 scott/tiger@orcl @c: \script. select the data from the table which has been populated using the stored procedure.

*/) EX: SQL> select ename /*this is a comment delimiter example*/ from /*This is another example*/ emp. get rem. To get the time.99 heading 'Monthly|salary' Compute sum od sal on deptno Rem This sql script will total the salaries Rem of all employees in each department Select deptno. How To Trim Lines When Spooling To remove trailing blanks at the end of each line enter the following statement on the command prompt before the spool command: SQL> set trimspool on How to insert ‘&’ character or special character into Database using SQL*Plus .. REMARK - For example: 1 2 3 4 5 6 7 8 Rem This is an example of how REM is used.. COLUMN SYSDATE new_value today SELECT To_Char(SYSDATE..sql 2.999. Column sal format $99. sal from emp order by deptno. SQL comment delimiters (/*.. It can be used to display various data in the title of a report. A line cannot contain both a remark and a command.Is there a way to document my SQL command and file? You can do this in two ways : 1..'mm/dd/yy') "sysdate" FROM DUAL / TTITLE left today center 'MY HEADING OR TITLE' skip 2 The use of "new_value" shown here applies in general to any value selected into a column specified in the COLUMN xxx NEW_VALUE command. ename.. Must appear at the beginning of a line and ends at the end of the line.. How do I include the current date and time in a SQL*Plus report heading? The following SQL*Plus command file segment shows how to put the current date into a variable and then include that variable in the title. Begins a remark in a command file. just change the mask in the to_char function to include that as well.

set the substitution character to one which will not be encountered when inserting data. -Ob?''!#*)EBK+`#a"^?#c\QH' To be able to do this. 1 row created. That means you have to check if the special character is included in your database characterset. Here just an example how to insert these special characters: Assume you want to insert the following sample string.If just two ''(two single quotes) signs have to be inserted use four '''' (four single quotes): .Solution 1: If you are not using substitution variables (&1 &2 &3 etc. then SQL*Plus will understand the special character following the escape symbol is to be treated as a regular character. / 1 row created Solution 2: If you are using substitution variables. How to Insert Special Characters Into Database First pay attention the database you use is able to deal with the special characters you want to insert. Example: SQL> SET DEFINE % SQL> INSERT INTO <temp_table> VALUES ('AT&T') / 1 row created. mask each single ' (single quote) with just one preceeding '(single quote). consisting of several single characters. which are concated to one string.) you can do a "SET DEFINE OFF" or "SET SCAN OFF” to turn off the definition of the ampersand as a substitution variable. Example: SQL>set escape on SQL>show escape escape "\" (hex 5c) SQL> INSERT INTO temp_table VALUES ('select * from emp where ename = \& 1'). Solution 3: If you precede the special character with a backslash and the ESCAPE setting in SQL*Plus is set to ON. Example: SQL> SET DEFINE OFF SQL> INSERT INTO <table_name> VALUES ('AT&T').

How To Create a Flat File In SQL*Plus Without Showing Statement or ''Spool Off'' Create a script. with the following contents: set NEWPAGE 0 set SPACE 0 set LINESIZE 80 set PAGESIZE 0 set ECHO OFF set FEEDBACK OFF set HEADING OFF spool report.sql How to SELECT Columns as Rows Using SQL Example: Using a UNION and VIEW should do the transformation like: create table p ( product varchar(16). 'att_12'. 'attr_13'). attr2 from p union (select product . 'attr_11'. attr1 from p union (select product . insert into p values ( 'product_1'. 'attr_21'. attr3 from p ). A --------------------------Ob?''!#*)EBK+`#a"^?#c\QH' Be aware of the characters (' at the beginning and the characters ') at the end of the string you want to insert.The following will work: SQL>insert into test VALUES ('-Ob?''''!#*)EBK+`#a"^?#c\QH'''). 'attr_33'). 1 row created. insert into p values ( 'product_3'. SQL> select * from test.sql. . create view vv as select * from (select product . spool off <--.txt select sysdate from dual. insert into p values ( 'product_2'. 'attr_23'). attr1 varchar(16). 'attr_31'. attr2 varchar(16).your SQL statement here Run the script from SQL*Plus: SQL> @report. attr3 varchar(16) ). report. 'att_22'. 'att_32'.g. e. commit.

Changes only affect a SQL*Plus Windows GUI started from the associated Oracle installation. NewValue #1 is created at the bottom of the right pane of the Registry Editor. HOME0 is the registry entry for an Oracle installation.Output: SQL> select * from vv. Click Modify from the Edit menu or press Enter again to display the Edit String dialog. you can edit the name by selecting Rename from the Edit menu. Enter the font name you want to use. PRODUCT ---------------product_1 product_1 product_1 product_2 product_2 product_2 product_3 product_3 product_3 ATTR1 ---------------att_12 attr_11 attr_13 att_22 attr_21 attr_23 att_32 attr_31 attr_33 How to Change the Displayed Font in SQL*Plus (GUI) To Change the Windows GUI Font: 1. The default name of the new string value is selected ready for you to replace with the name you want. A new string value. you must select the HOME entry associated with the Windows GUI you want to change. A subsequent Oracle installation will have the registry entry HOME1 and the next HOME2 and so on. SQL*Plus will use the new font the next time you start the SQL*Plus Windows GUI. Click New String Value in the Edit menu. 3. in the Value Data: field. Modify Password and Suppressing Typed Password in SQLPLUS Use sqlplus functionality passw just enter on sqlplus prompt: SQLPLUS> passw and new password wil not be echoed. Enter SQLPLUS_FONT as the name of the new font face string value. 6. Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\HOME0. so you can use different settings for each Oracle installation.If you miskey the name or inadvertently enter it in mixed or lower case. 4. 2. Note:If you have more than one Oracle installation. How to Select and Display a Certain Number of Records . Select Run from the the Start menu and then enter regedit in the Open field and Click OK to start the registry Editor. with the default name. 5. such as Courier New.

from very simple to slightly complex Solution 1 (simple) SQL> select empno from emp where empno like '%7%' and rownum <= 10. close emp_cursor. end loop.empno%type. EMPNO --------7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 10 rows selected.put_line(v_empno ||' ' || v_counter). but only display the first 10 or what ever. Solution 2 SQL> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18* SQL> 7369 7499 7521 7566 7654 7698 7782 l declare v_counter number(3):=+0.Problem Description Customer needs to select from a table and display only a limited number of records. begin open emp_cursor. fetch emp_cursor into v_empno. / 1 2 3 4 5 6 7 . v_counter := v_counter +1. v_empno emp. dbms_output. Example would be select all Smiths from address table. cursor emp_cursor is select empno from emp where empno like '7%'. loop exit when emp_cursor%notfound. Solution Description Several solutions are available. end. exit when emp_cursor%notfound or v_counter > 10.

fetch emp_cursor into v_&select_info. ENAME ROWNUM ---------. v_counter := v_counter +1. dbms_output. begin open emp_cursor. end. Solution 3 set serveroutput on accept select_info prompt 'please enter select: ' accept where_info prompt 'please enter where: ' declare v_counter number(3):=+0.put_line(v_&select_info ||' ' || v_counter). loop exit when emp_cursor%notfound.---------ALLEN 1 JONES 2 BLAKE 3 CLARK 4 KING 5 ADAMS 6 JAMES 7 . / How to Number Rows After They Have been Sorted Problem description SQL*Plus users sometimes want to have rows numbered in a sorted order. v_&select_info emp. close emp_cursor. The first selection shows the unsorted selection of ename and rownum from emp. cursor emp_cursor is select &select_info from emp where &select_info like &where_info. end loop. This is illustrated in the following example. exit when emp_cursor%notfound or v_counter > 10.7788 8 7839 9 7844 10 PL/SQL procedure successfully completed. and the second selection illustrates how ROWNUM is useless as a numbering device for ordered selections because the values of ROWNUM are assigned before the ordering is performed.&select_info%type. rownum from emp. since the ordering is done after the values for ROWNUM had been assigned to rows as they were selected in random order. This can't be achieved using the ROWNUM pseudo column. SQL> select ename.

emp B A.ename A.ename.FORD 8 SQL> select ename.ename > B.ename.empno A. ENAME ROWNUM ---------. A. Another alternative is to create an index on the order column. count(*) position emp A.---------ADAMS 1 ALLEN 2 BLAKE 3 CLARK 4 FORD 5 JAMES 6 JONES 7 KING 8 This method works by counting the number of records that a particular record is superior than (or equal to) in alphabetical order of employee name.empno >= B.---------ADAMS 6 ALLEN 1 BLAKE 3 CLARK 4 FORD 8 JAMES 7 JONES 2 KING 5 Solution Explanation The following select statement achieves the desired ordering/numbering: SQL> 2 3 4 5 6 select from where or group by order by A. SQL> create index sort on emp (ename). and include a meaningless where clause to force use of the index. This would not be an efficient method against tables with large numbers of rows. A.ename = B.ename and A. SQL> select ename. rownum from emp where ename > ' '. ENAME ROWNUM ---------. Index created. The empno column acts as a unique key to discern between records in case identical names occur in the table.---------ADAMS 1 ALLEN 2 BLAKE 3 . ENAME POSITION ---------.empno.empno. rownum from emp order by ename.ename A.

DNAME. suppose you do the following in SQL*Plus: SQL> break on report SQL> compute count of deptno on report SQL> select * from dept.dummy (+).CLARK FORD JAMES JONES KING 4 5 6 7 8 The where clause in the query forces SQL*Plus to use the index created on the ename column. In other words. ename 2 from emp . This happens in report breaks where the computation is performed on the first column. the compute labels for a report break always appear in the first column. Missing Label when Computing is Done on the First Column PROBLEM: Your label is missing when doing computes of the first column on a report break. it cannot be used to return rows numbered in descending order. SQL> select rownum. For example. I would have gotten: SQL> clear computes . and since the index is used. DEPTNO ---------10 20 30 40 ---------4 DNAME -------------ACCOUNTING RESEARCH SALES OPERATIONS LOC ------------NEW YORK DALLAS CHICAGO BOSTON Notice the lack of the 'count' label. the rows are returned in ascending order.ename = dual. The last method presented takes advantage of a feature of the database kernel optimizer. if I had performed the count computation on the second column. which results in the desired sorted order. ROWNUM ---------1 2 3 4 5 6 7 8 ENAME ---------ADAMS ALLEN BLAKE CLARK FORD JAMES JONES KING The optimizer evaluates the outer join in this example by using a sort/merge join. Normally. dual 3 where emp. Since this method depends on the inherent order of the index.

Notice that as the first element of the SELECT list we specify the constant expression ' ' (a blank string) and give it a column alias of SUMMARY. no computation is performed on the first column so SQL*Plus is free to place the "count" label in the first column.g. DEPTNO ---------10 20 30 40 count DNAME -------------ACCOUNTING RESEARCH SALES OPERATIONS -------------4 LOC ------------NEW YORK DALLAS CHICAGO BOSTON In this case. SUMMARY DEPTNO ------. Purpose The purpose of this article is to demonstrate how to make only one connection attempt to the database and then exit so SQL*Plus does not bring up the username prompt again. . How to exit multiple connection attempts to DB from SQL*Plus when first connection attempt fails. dept.---------10 20 30 40 ---------count 4 DNAME -------------ACCOUNTING RESEARCH SALES OPERATIONS LOC ------------NEW YORK DALLAS CHICAGO BOSTON Thus.Computes cleared SQL> compute count of dname on report SQL> select * from dept.* from dept. we create a dummy left most column named SUMMARY (or whatever is appropriate) to hold the "count" label. In backup scripts or batch jobs. Here's how it works with our original example: SQL> clear computes computes cleared SQL> clear breaks breaks cleared SQL> break on report SQL> compute count of deptno on report SQL> col summary format a7 SQL> select ' ' summary. RESOLUTION: The following approach was proposed: use a "dummy" first column to hold the compute label when you want a compute of the first column on a report break. This technique can then be used in scripts or batch files to automatically handle failing SQL*Plus connections e.

REVOKE. RENAME. NULL. VALIDATE. How to Get a Heading After Set Pagesize 0 When setting PAGESIZE to 0 then the column headings will be suppressed. 'SELECT'. CREATE. GRANT. Example To disable the SELECT statement for SCOTT: 1. NULL. When the user SCOTT tries to execute the command SELECT he will obtain the error: SP2-0544: Invalid command: SELECT.SQL*Plus example from Unix Prompt sqlplus /nolog <<EOF whenever sqlerror exit connect scott/tiger@notthere EOF SQL*Plus example for Windows Create a SQL Script connect.sql How to restrict SQL commands using PRODUCT_USER_PROFILE It is possible to disable the following commands: ALTER. Start this script as follows: sqlplus /nolog @connect. . 'DISABLED'. NOAUDIT. NULL). 'SCOTT'. DROP. 2. UPDATE. DELETE.sql as follows: whenever sqlerror exit connect scott/tiger@notthere From DOS Prompt. LOCK. Insert in the table PRODUCT_USER_PROFILE the next row: SQL> insert into product_user_profile values ('SQL*Plus'. AUDIT. SELECT. NULL. INSERT.

Removes all whitespace between columns. select empno.sql) set pagesize 0 set feedback off select 'Number Name' from dual.removes headings Set pagesize 0 .------7369 SMITH 7499 ALLEN 7521 WARD 7566 JONES How to Include a New Line Character in an Insert Statement from SQL*Plus Concatenate the ASCII value CHR (10) in between the data where the carriage return is required. The carriage return is placed at the end of the record length.---------------------------COL1 NUMBER COL2 VARCHAR2(20) SQL> select concat(ltrim(to_char(col1)).-------. Name Null? Type -------------------------------------.-------' from dual. Set heading off . ename from emp / SQL> @t1 => Result: Number Name ---------.Use the following example to generate a heading: SQL-script (t1.removes pagebreaks How To Append a Carriage Return To the End of a Record In a Spooled File A typical scenario would be if a file is created with multiple columns piped together placing a carriage return (CHR(10)) at the end of each record.G. E.ltrim(col2)) from test. . select '---------. SQL> desc test. INSERT INTO <TABLE NAME> VALUES ('HELLO'||CHR (10) ||'HOW ARE YOU') The above insert statement will insert into the table as two separate lines. How to remove whitespace when spooling a select statement Example:Create table test as below.

set by LINESIZE. Example: spool <filename> set linesize 100. set heading off. --carriage return after last ¿|¿ character spool off How To Pass Parameters Containing Spaces To SQL*PLUS On Unix the parameter(s) follow on command line and have to be quoted SQLPLUS scott/tiger @test "This is a test. ON VMS that has to happen as follows: SQLPLUS scott/tiger @test "'This is a test.'" SQLPLUS scott/tiger @test """This is a test""&quot.dual. --carriage return set at position 100 set trimspool on select dname||'|'||loc||'|'||chr(10) from dept. use the following SET commands in SQL*Plus: SQL> SQL> SQL> SQL> SQL> SQL> SQL> SET SET SET SET SET SET SET NEWPAGE O SPACE 0 LINESIZE 80 PAGESIZE 0 ECHO OFF FEEDBACK OFF HEADING OFF Use the SPOOL command to store query result in a file: . Use SET TRIMSPOOL ON to have the carriage return follow the last column. set trimspool off select dname||'|'||loc||'|'||chr(10) from dept. instead of immediately following the last column." They then can be selected with SELECT '&1' FROM sys. How To Display a Long Column in Oracle SQL*Plus Use the SET command SET Long xxxx How to Create a Flat ASCII File From SQL*Plus To create a flat file from within SQL*Plus.

SQL> SPOOL <file_name> SQL*Plus stores all information displayed on the screen after the SPOOL command is entered. usually LIS or LST. do not truncate rows. in the specified file. Example: SQL> SET LONG 500 . where <n> is the max length of the column that will be showed. SPOOL add a default file extension to the filename to identify it as an output file. Use this command before executing the SELECT statement: SET COLSEP '' NOTE: Do not leave space between the single quote symbols. SQL*Plus continues to spool information to the file until spooling is turned off using the following command: SQL> SPOOL OFF How To Remove The Default Single Space Between Fields From The Output Of a SELECT Statement In SQL*Plus This can be done using the SET COLSEP command. There are two solutions to circumvent this: 1. Enable wrapping. depending on host operating system. SQL> set wrap on How to Display the Entire Contents of Long Fields Use the command SET LONG <n>. How to Suppress The 'rows will be truncated' Message in SQL*Plus When the SQL*Plus setting WRAP is set to OFF and rows need to be displayed which are larger then the setting of LINESIZE the message 'rows will be truncated' will be reported. If no file extension is specified. SQL> set wrap off SQL> set linesize 32767 (32K is maximum value) 2. Set the SQL*Plus setting LINESIZE to a value larger than the maximum length of the rows to be selected.

Sign up to vote on this title
UsefulNot useful