Tuesday, September 30, 2008

HTML Formatting


--+-----------------------------------------------------------------------------
--| Set Escape On To Use \&nbsp; (space) \&amp; (&) \&gt; (>) \&lt; (<)
--+-----------------------------------------------------------------------------

Set Markup Html On Entmap On Spool On Preformat Off
Set Feedback Off Term Off Echo Off Verify Off Linesize 2000 Escape On

--+-----------------------------------------------------------------------------
--| Define 's' to be a lot of spaces (makes the heading easier to read
--+-----------------------------------------------------------------------------

Define Xprogram = Html1.Sql
Define s = "\&nbsp; \&nbsp; \&nbsp; \&nbsp; \&nbsp; \&nbsp; \&nbsp; \&nbsp; \&nbsp; \&nbsp;"
Spool Emp.Htm

--+-----------------------------------------------------------------------------
--| Print the title (Entmap says: Dont Translate '<' Etc )
--+-----------------------------------------------------------------------------

Column Title1 Entmap Off Format A2000 Heading "<h1><i>HTML Test</i></h1>"

Select 'Program: <B>&xProgram</B> &s'
||To_Char(Sysdate,'FmMonth Dd, Yyyy Day')||To_Char(Sysdate,' Hh24:Mi')
||'&s User: <B>' || User || ' </b>'
As Title1
From V$Database;

--+-----------------------------------------------------------------------------
--| Print the actual report
--+-----------------------------------------------------------------------------
Column Job Entmap Off
Column Ename Entmap Off

Select Empno,
----------------------------------------
'<Center>'||Ename||'</Center>'
As
Ename,
----------------------------------------
'<Small>'||Job||'</Small>'
As
Job,
----------------------------------------
Mgr, Hiredate, Sal, Comm, Deptno
From Emp;

Spool Off
--+-----------------------------------------------------------------------------
--| clean up
--+-----------------------------------------------------------------------------
Set Markup Html Off Entmap Off Spool On Preformat Off
Set Term On Escape Off

Prompt ** Report Completed. Use Firefox To View Your Output: Emp.Htm **

Saturday, September 27, 2008

Create a New Instance on the PC

1) SQL> Shutdown
2) SQL> EXIT
3) Windows Start
Control Panel
Administrative Tools
Services
- Stop all Oracle Services
4) Start
All Programs
Oracle - OraDB10gHome
Configuration & Migration Tools
Database Configuration Assistant

5) Delete database (PC only supports one instance)
6) Create database
Ignore
OK
Yes
Database Name (no underscores allowed)
SID (same as database name)
Password
-File System

[x] Enable Archiving

Oracle charges clients for the number of processes running

Password Management
Change SYS password to SYS
Change System password to SYSTEM
Change SCOTT password to TIGER

Show Parameter db_name;

Tuesday, September 23, 2008

Deleted Data Stored in Rollback Segments

clear screen
set echo on feedback on heading on pagesize 50

variable emps refcursor

begin
open :emps for
select empno, ename
from emp
where empno > 7800;
end;
/
----------------------------------------------
-- deleted data is saved in a rollback segment
----------------------------------------------
delete from emp;

commit;

print emps

Monday, September 22, 2008

Lock Table

Allowed:Prohibited:Other Notes:ROW SHARE (SHARE UPDATE*)ROW EXCLUSIVESHARESHARE ROW EXCLUSIVEEXCLUSIVE
Concurrent accessLocking for exclusive access
YesYes---

Locking in SHARE modeAutomatically obtained for DML-Yes---
Concurrent queriesUpdates
--Yes--
Others to look at rowsOthers from locking w/SHARE. Updating rowsUsed to look at a whole table---Yes-
QueriesAnything else
----Yes



* kept for backward compatilibity



  • Some locks can be placed at the same time. Other locks allow only one. (??)
  • Remains locked until you commit or rollback.
  • Never prevents queries
  • 'View' locks the base tables of the view.
  • If view is part of a hierarchy, then it must be the root.

The table or view
  1. must be in your own schema or
  2. you have LOCK ANY TABLE or
  3. you have any object privilege on the table or view.
LOCK TABLE
[ schema. ] { table | view } [ { PARTITION (partition) | SUBPARTITION (subpartition) } | @ dblink ] [,
[ schema. ] { table | view } [ { PARTITION (partition) | SUBPARTITION (subpartition) } | @ dblink ] ]...
IN lockmode MODE
[ NOWAIT ] ;

If you specify [SUB]PARTITION, then an implicit lock of the same type is first acquired on the table except for:
  • SHARE: acquires an implicit ROW SHARE lock on the table.
  • EXCLUSIVE: acquires an implicit ROW EXCLUSIVE lock on the table.

dblink - only if distributed functionality(??). All must be on the same database.

NOWAIT a message returns if other locks. Otherwise, waits until table available, locks it before returning control.

Wednesday, September 17, 2008

DICT - Data Dictionary

This query actually generates two reports. The first shows all tables starting with 'User_' (indicated by the 'U'), 'All_' (indicated by the 'A') or 'DBA_' (indicated by the 'D'). The 'base_name' is what I consider the portion past User/All/DBA. The report is sorted by this name. A page break occurs based on the first letter. A line break occurs based on the second part of this name, although those with just one row will be grouped together. The comment displayed for that base name is a random selection of the three, as I selected the 'Max' from whichever ones were available.

The second report shows those tables that do not start with 'User_', 'All_' or 'DBA'.
rem +--------------------------------------------------------------------------+
rem | Script ID: Dic.sql
rem |
rem | Purpose: Display table names and comments based on User/All/DBA
rem |
rem | Developer: Lynn Tobias
rem | Script Date: 9/17/2008
rem | Oracle Ver: 10g
rem |
rem | Table(s) Used: Dict
rem |
rem | Output: Dic.Txt
rem |
rem | Revisions: Dvl Date Ver Comment/Change
rem | --- -------- --- -----------------------------------------+
rem +--------------------------------------------------------------------------+

Clear Screen
Set Recsep Off Heading Off Newpage 1 Feedback Off Echo Off Linesize 200 Pagesize 200

Break On First_Char Skip Page -
On Tbl_Cnt Skip 1

Column Comments Format A150
Column Userx Format A1 Heading U
Column Allx Format A1 Heading A
Column Dbax Format A1 Heading D
Column Base_Name Format A26

Column First_Char New_Value xFirst_Char Noprint
Column Tbl_Cnt Noprint

Ttitle Left 'U A D ' xfirst_Char ' Whichever of the three comments was considered ''Max'' ' skip 1-
'- - - -------------------------- -----------------------------------------------------------------------------------------------------------'
Spool Dic.Txt

Prompt Tables from DICT Which Begin with User (U), All (A) or DBA (D)

--+- 1 -----------------------------------------------------------------
--| Pad the base name. Expand First_Char for title. We'll line-break on
--| the combination Part2+count.
--+---------------------------------------------------------------------
Select Userx, Allx, Dbax,
Rpad(Base_Name,26,'.') As
Base_Name,
Rpad(First_Char,26,First_Char) As
First_Char,
Case When Tbl_Cnt = 1
Then ' '
Else Part2||Tbl_Cnt
End As
Tbl_Cnt,
Comments
From
--+- 1.1 --------------------------------------------------------
--| I want to bunch all the separate ones together without a line
--| break, so count to see how many there are of each 2nd division.
--+--------------------------------------------------------------
(
Select Userx, Allx, Dbax,
Base_Name,
First_Char,
Part2,
Count(Base_Name) Over (Partition By Part2)
Tbl_Cnt,
Comments
From
--+- 1.1.1 -----------------------------------------------
--| Max everything to get one line per base name. Pick up
--| a random comment (hopefully the 3 are similar).
--| To keep 'Tablespaces' and Tablespace' together, remove
--| any ending 'S' from part2.
--+-------------------------------------------------------
(
Select Max(Case When Part1 = 'USER' Then 'U' Else '.' End) As
Userx,
Max(Case When Part1 = 'ALL' Then 'A' Else '.' End) As
Allx,
Max(Case When Part1 = 'DBA' Then 'D' Else '.' End) As
Dbax,
Max(First_Char) As
First_Char,
Base_Name,
Max(Case When Part2 Like '%S'
Then Substr(Part2,1,Length(Part2)-1)
Else Part2
End) As
Part2,
Max(Comments) As
Comments
From
--+- 1.1.1.1 --------------------------------------
--| Part1 - User/All/DBA (and comments)
--| Base_Name - Name other than User/All/DBA
--| First_Char of Base - used for page breaks
--| Part2 - the 2nd portion used for line breaks
--+------------------------------------------------
(
Select Substr(Table_Name,1,U1-1) As
Part1,
Substr(Table_Name,U1+1) As
Base_Name,
Substr(Table_Name,U1+1,1) As
First_Char,
Substr(Table_Name,U1+1, U2-U1-1) As
Part2,
Comments
From
--+- 1.1.1.1.1 -----------------------------
--| Keep the table_name and comment and get
--| the position of the first two underscores.
--| Remove the random line break from the comments.
--+-----------------------------------------
(
Select Table_Name,
Instr(Table_Name,'_')
U1,
Instr(Table_Name||'_','_',1,2)
U2,
Replace(Comments,Chr(10),' ')
Comments
From Dict
Where (Table_Name Like 'DBA_%' Or
Table_Name Like 'ALL_%' Or
Table_Name Like 'USER_%')
And Nvl(Comments,' ') Not Like 'Synonym for V_$%'
And Nvl(Comments,' ') Not Like 'Synonym for GV_$%'
)
--+- 1.1.1.1 End ----------------------------------
Order By Base_Name
)
--+- 1.1.1 End -------------------------------------------
Group By Base_Name
Order By Base_Name
)
--+- 1.1 End ----------------------------------------------------
Order By Part2, Base_Name
)
--+- 1 End -------------------------------------------------------------
/
Ttitle Left 'Tables not starting with User, All or DBA' skip 2
Set Heading On
Column Comments Heading Comments
--+- 2 -----------------------------------------------------------------
--| Print the tables not starting with User/All/DBA
--+---------------------------------------------------------------------
Select Table_Name,
Replace(Comments,Chr(10),' ') As
Comments
From Dict
Where Upper(Comments) Not Like 'SYNONYM%'
And Table_Name Not Like 'DBA_%'
And Table_Name Not Like 'ALL_%'
And Table_Name Not Like 'USER_%'
Order by Table_Name
/
Spool Off
Clear Columns
Set Recsep Wrapped Newpage 1 Feedback On

Tuesday, September 16, 2008

Regular Expressions

--Regular Expression Operators and Metasymbols
--
----------------------------------
-- Anchor to:
----------------------------------
-- ^ the beginning of a string ^A finds Alice, Alan
-- $ the end of a string g$ finds dog, lag
----------------------------------
-- Match # times
----------------------------------
-- * >= 0 12*3 finds 13 123 1223 12223
-- + >= 1 ar*gh finds argh arrgh arrrrrgh
-- ? =0-1 t?hat finds hat that
-- {m} = m times bo(3) finds booo
-- {m,} >= m times bo(3,) finds booo boooo booooooooo
-- {m,n} >= m times <= n times bo(2,3) finds bo boo
----------------------------------
-- Classes
----------------------------------
--[:alpha:] Alphabetic
--[:lower:] Lowercase
--[:upper:] Uppercase
--[:digit:] Numeric digits
--[:alnum:] Alphanumeric
--[:space:] Space (nonprinting), carriage return, newline, form feed
--[:punct:] Punctuation
--[:cntrl:] Control (nonprinting)
--[:print:] Printable
--[:xdigit:] Hexadecimal characters
----------------------------------
-- Groups of things
----------------------------------
-- x|y alternative matches
-- ( ) a group - treated as a single subexpression (known as captures) i.e., cat(s|alog)
-- [ ] character matching list (most things her are taken as literals i.e.,
-- [^ ] nonmatching list (most things her are taken as literals
----------------------------------
-- Backslash
----------------------------------
-- \1 - \9 is a backreference to the \#th (subexpression)
-- \n newline
-- \\ Backslash character
-- \ Treat the next character as not a special charater
----------------------------------
-- Wildcard
----------------------------------
-- . any character except NULL h.t finds hot hat hit hut
----------------------------------
-- Need example
----------------------------------
-- [..] one collation element, and can be a multicharacter element
-- [==] equivalence classes. For example, [=a=] matches all characters having base letter 'a'.

---------------------------------------------------------------------------------------------------------------------------------
--RegExp_Count -- in 11G
---------------------------------------------------------------------------------------------------------------------------------
--Regexp_Like (
--String To Be Searched,
--Pattern To Be Found,
--Optional Parameter
--)
---------------------------------------------------------------------------------------------------------------------------------
--Regexp_Instr (
--String to be searched ,
--Pattern to be found
-- [, Start position /* If omitted then column 1 of string*/
-- [, Occurrence /* If omitted than first occurrence */
-- [, Return_option /* 0=return position of 1st character; 1=return position of next character */
-- [, Match_parameter ]
-- ]
-- ]
-- ]
--)
------------------------------------------------------------------------------------------------------------------------
--Regexp_Substr(
--String To Be Searched ,
--Pattern To Be Found
-- [, Start position /* If omitted then column 1 of string*/
-- [, Occurrence /* If omitted than first occurrence */
-- [, Match_Parameter ]
-- ]
-- ]
-- )
-------------------------------------------------------------------------------------------------------------
--Regexp_Replace(
--String to be searched ,
--Pattern to be found ,
-- [, Replace_String [, Position
-- [,Occurrence,
-- [Match_Parameter]
-- ]
-- ]
-- ]
--);
---------------------------------------------------------------------------------------------------------------------------------
-- Match Parameters:
-- * 'i' Case-Insensitive
-- * 'c' Case-Sensitive
-- * 'n' Matches Newline Character
-- * 'm' Source Treated As Multiple Lines
-- * 'x' Ignores Whitespace Characters



spool reg.txt
Column Name Format A10
Column Range Heading 1980|1981|1982
Column Specific Heading 1980||1982
Column White_House Format A45 Heading -
' 1 2 3 4 |123456789012345678901234567890123456789012345'
Column Instr1 Format 99
Column Instr2 Format 99
Column Instr3 Format 99
Column Instr7 Format 99
Column Invalid Format 99
Column Valid Format A5
Column RE1 Format A6
Column RE2 Format A6
Column RE3 Format A6
Column RE4 Format A6
Set NewPage 2 echo on recsep off pagesize 50 linesize 120 Feedback off

SQL> ttitle left '+=======================================================================================================================' skip 1-
> '| Begin Example: ' pno skip 1-
> '+=======================================================================================================================' skip 0
SQL>
SQL> repfooter left '+=======================================================================================================================' skip 1-
> '| End Example: ' pno skip 1-
> '+=======================================================================================================================' skip 3
SQL>
SQL> --------------------------------------------------------------------
SQL> -- create table
SQL> --------------------------------------------------------------------
SQL> Create Table Name_Birth (Name Varchar2(10), DOB Date) ;
SQL> Insert into Name_Birth Values ('KING' , '17-NOV-83');
SQL> Insert into Name_Birth Values ('Smyth' , '03-DEC-81');
SQL> Insert into Name_Birth Values ('SMITH' , '17-DEC-80');
SQL> Insert into Name_Birth Values ('Feeney', '09-DEC-82');
SQL> Insert into Name_Birth Values ('smath' , '23-JAN-82');
SQL>
SQL> Clear Screen
SQL> --------------------------------------------------------------------
SQL> Define PNo = 1;
SQL> -- Find Smith or Smyth
SQL> -- ^ start at the beginning of string
SQL> -- Sm find these characters then
SQL> -- (i|y) find either an 'i' or 'y'
SQL> -- th then find a 'th'
SQL> -- $' there should be nothing after the 'th' -- end of string
SQL> -- ,'i' optional parameters says be insensitive to case
SQL> --[^(i|y)] says 'not' either 'i' or 'y'
SQL> --------------------------------------------------------------------
SQL>
SQL> Select '|' ,
2 Name,
3 Case When Regexp_Like (Name, '^Sm(i|y)th$','i')
4 then Name
5 Else ' ' End As
6 Smith,
7 Case When Not Regexp_Like (Name, '^Sm(i|y)th$','i')
8 then Name
9 Else ' ' End As
10 Not_Smith,
11 Case When Regexp_Like (Name, '^Sm[^(i|y)]th$','i')
12 then Name
13 Else ' ' End As
14 "Sm?th"
15 from Name_Birth;

+=======================================================================================================================
| Begin Example: 1
+=======================================================================================================================
' NAME SMITH NOT_SMITH Sm?th
- ---------- ---------- ---------- ----------
| KING KING
| Smyth Smyth
| SMITH SMITH
| Feeney Feeney
| smath smath smath
+=======================================================================================================================
| End Example: 1
+=======================================================================================================================

SQL> --------------------------------------------------------------------
SQL> Define PNo = 2;
SQL> -- Find date of birth from 1980 and 1982
SQL> -- ^ search from the beginning
SQL> -- 198 for these 3 specific characters and then
SQL> -- [0-2] choose anything between zero and two
SQL> -- $ this is the end of the string
SQL> -- OR
SQL> -- [02] choose specifically 0 or 2
SQL> --------------------------------------------------------------------
SQL>
SQL> Select '|' ,
2 Name,
3 To_Char(DOB,'yyyy') As
4 DOB,
5 Case When Regexp_Like (To_Char(DOB,'yyyy'), '^198[0-2]$')
6 Then To_Char(DOB,'yyyy')
7 Else ' ' End As
8 Range,
9 Case When Regexp_Like (To_Char(DOB,'yyyy'), '^198[02]$')
10 Then To_Char(DOB,'yyyy')
11 Else ' ' End As
12 Specific,
13 Case When Not Regexp_Like (To_Char(DOB,'yyyy'), '^198[012]$')
14 Then To_Char(DOB,'yyyy')
15 Else ' ' End As
16 Other
17 From Name_Birth
18 Order By DOB;

+=======================================================================================================================
| Begin Example: 2
+=======================================================================================================================
1980 1980
1981
' NAME DOB 1982 1982 OTHE
- ---------- ---- ---- ---- ----
| SMITH 1980 1980 1980
| Smyth 1981 1981
| smath 1982 1982 1982
| Feeney 1982 1982 1982
| KING 1983 1983
+=======================================================================================================================
| End Example: 2
+=======================================================================================================================

SQL> --------------------------------------------------------------------
SQL> Define PNo = 3;
SQL> -- Find one or more occurrences of non-blanks
SQL> -- (there is no 8th occurrence, and it returns 0)
SQL> --------------------------------------------------------------------
SQL>
SQL> Select '|' , '1600 Penn Ave NW Wash, DC 20500' White_House,
2 Regexp_Instr('1600 Penn Ave NW Wash, DC 20500','[^ ]+', 1, 1) Instr1,
3 Regexp_Instr('1600 Penn Ave NW Wash, DC 20500','[^ ]+', 1, 2) Instr2,
4 Regexp_Instr('1600 Penn Ave NW Wash, DC 20500','[^ ]+', 1, 3) Instr3,
5 Regexp_Instr('1600 Penn Ave NW Wash, DC 20500','[^ ]+', 1, 7) Instr7,
6 Regexp_Instr('1600 Penn Ave NW Wash, DC 20500','[^ ]+', 1, 8) Invalid
7 From Dual ;

+=======================================================================================================================
| Begin Example: 3
+=======================================================================================================================
1 2 3 4
' 123456789012345678901234567890123456789012345 INSTR1 INSTR2 INSTR3 INSTR7 INVALID
- --------------------------------------------- ------ ------ ------ ------ -------
| 1600 Penn Ave NW Wash, DC 20500 1 6 11 27 0
+=======================================================================================================================
| End Example: 3
+=======================================================================================================================

SQL> ----------------------------------------------------------------------
SQL> Define PNo = 4;
SQL> -- Find position of words that start with P or W and 4 characters long
SQL> ----------------------------------------------------------------------
SQL>
SQL>
SQL> Select '|' , '1600 Penn Ave NW Wash, DC 20500' White_House,
2 Regexp_Instr('1600 Penn Ave NW Wash, DC 20500','[P|W][[:alpha:]]{3}',1,1,0, 'i') Instr_1,
3 Regexp_Instr('1600 Penn Ave NW Wash, DC 20500','[P|W][[:alpha:]]{3}',1,2,0, 'i') Instr_2,
4 Regexp_Instr('1600 Penn Ave NW Wash, DC 20500','[P|W][[:alpha:]]{3}',1,3,0, 'i') Instr_3
5 From Dual ;

+=======================================================================================================================
| Begin Example: 4
+=======================================================================================================================
1 2 3 4
' 123456789012345678901234567890123456789012345 INSTR_1 INSTR_2 INSTR_3
- --------------------------------------------- ---------- ---------- ----------
| 1600 Penn Ave NW Wash, DC 20500 6 18 0
+=======================================================================================================================
| End Example: 4
+=======================================================================================================================

SQL> --------------------------------------------------------------------
SQL> Define PNo = 5;
SQL> -- Backreferences: the ability to store subexpressions for reuse later.
SQL> -- The matched part of the subexpression is stored in a temporary buffer.
SQL> -- The buffer is numbered left to right and accessed with \1 to \9
SQL> -- ( => creates a subexpression
SQL> -- . => match anything
SQL> -- *) => 0 or more times
SQL> -- The spaces between (.*) will also be matched
SQL> -- bring back in new order (3) then comma then (1) then (2)
SQL> --------------------------------------------------------------------
SQL>
SQL> Select '|' ,
2 Regexp_Replace(
3 'Little Jack Horner',
4 '(.*) (.*) (.*)', '\3, \1 \2'
5 )
6 From Dual;

+=======================================================================================================================
| Begin Example: 5
+=======================================================================================================================
' REGEXP_REPLACE('LIT
- -------------------
| Horner, Little Jack
+=======================================================================================================================
| End Example: 5
+=======================================================================================================================

SQL> --------------------------------------------------------------------
SQL> Define PNo = 6;
SQL> -- Find duplicate words
SQL> --------------------------------------------------------------------
SQL>
SQL> Select '|' ,
2 Regexp_Substr(
3 'Now is the time for all all good folks to come to the aid of their country',
4 '([:alnum:]+)([[:space:]]+)\1'
5 ) As Substr
6 From Dual;

+=======================================================================================================================
| Begin Example: 6
+=======================================================================================================================
' SUBSTR
- -------
| all all
+=======================================================================================================================
| End Example: 6
+=======================================================================================================================

SQL> --------------------------------------------------------------------
SQL> Define PNo = 7;
SQL> -- Look for a valid phone number:
SQL> --------------------------------------------------------------------
SQL>
SQL> Create Table Phonenums ( Phone_Number Varchar2(30) Constraint C_Phonenums_Pnf
2 Check (Regexp_Like (Phone_Number, '^\(\d{3}\) \d{3}-\d{4}$')) );
SQL>
SQL> Insert Into Phonenums (Phone_Number) Values( '(650) 555-5555' );
SQL> Insert Into Phonenums (Phone_Number) Values( '(215) 555-3427' );
SQL> Insert Into Phonenums (Phone_Number) Values( '650 555-5555' );
Insert Into Phonenums (Phone_Number) Values( '650 555-5555' )
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.C_PHONENUMS_PNF) violated


SQL> Insert Into Phonenums (Phone_Number) Values( '(650)555-5555' );
Insert Into Phonenums (Phone_Number) Values( '(650)555-5555' )
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.C_PHONENUMS_PNF) violated


SQL> Select '|',
2 Phone_number
3 From PhoneNums;

+=======================================================================================================================
| Begin Example: 7
+=======================================================================================================================
' PHONE_NUMBER
- ------------------------------
| (650) 555-5555
| (215) 555-3427
+=======================================================================================================================
| End Example: 7
+=======================================================================================================================

SQL> --------------------------------------------------------------------
SQL> Define PNo = 8;
SQL> -- Before 111.222.3333 After (111) 222-3333
SQL> --------------------------------------------------------------------
SQL>
SQL> Select '|' ,
2 Regexp_Replace('111-222-3333',
3 '([[:digit:]]{3})\-([[:digit:]]{3})\-([[:digit:]]{4})',
4 '(\1) \2-\3')
5 Result
6 From Dual;

+=======================================================================================================================
| Begin Example: 8
+=======================================================================================================================
' RESULT
- --------------
| (111) 222-3333
+=======================================================================================================================
| End Example: 8
+=======================================================================================================================

SQL> --------------------------------------------------------------------
SQL> Define PNo = 9;
SQL> -- Double space words
SQL> --------------------------------------------------------------------
SQL>
SQL> Select '|' ,
2 Regexp_Replace('OKLAHOMA!', '(.)', '\1 ') Result
3 From Dual;

+=======================================================================================================================
| Begin Example: 9
+=======================================================================================================================
' RESULT
- ------------------
| O K L A H O M A !
+=======================================================================================================================
| End Example: 9
+=======================================================================================================================

SQL> --------------------------------------------------------------------
SQL> Define PNo = 10;
SQL> -- Kill extra spaces
SQL> --------------------------------------------------------------------
SQL>
SQL> Select '|' ,
2 Regexp_Replace(
3 'Mary, Mary, quite contrary. How does your garden grow?'
4 , '( ){2,}', ' ') Result
5 From Dual;

+=======================================================================================================================
| Begin Example: 10
+=======================================================================================================================
' RESULT
- ------------------------------------------------------
| Mary, Mary, quite contrary. How does your garden grow?
+=======================================================================================================================
| End Example: 10
+=======================================================================================================================

SQL> --------------------------------------------------------------------
SQL> Define PNo = 11;
SQL> -- Check for alpha only
SQL> --------------------------------------------------------------------
SQL>
SQL> CREATE TABLE Alpha_Table (c1 VARCHAR2(20), CHECK (REGEXP_LIKE(c1, '^[[:alpha:]]+$')));
SQL> Insert into Alpha_Table values ('Lynn');
SQL> Insert into Alpha_Table values ('ABC');
SQL> Insert into Alpha_Table values ('123');
Insert into Alpha_Table values ('123')
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.SYS_C008660) violated

SQL> Insert into Alpha_Table values (123);
Insert into Alpha_Table values (123)
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.SYS_C008660) violated

SQL>
SQL> Select '|',
2 c1
3 from Alpha_Table;

+=======================================================================================================================
| Begin Example: 11
+=======================================================================================================================
' C1
- --------------------
| Lynn
| ABC
+=======================================================================================================================
| End Example: 11
+=======================================================================================================================

SQL> --------------------------------------------------------------------
SQL> Define PNo = 12;
SQL> -- SSN
SQL> --------------------------------------------------------------------
SQL> Create Table SocSec_Table ( SocSecNo Varchar2(20));
SQL> Insert Into SocSec_Table Values ( '444-77-9999' );
SQL> Insert Into SocSec_Table Values ( '494=77-9999' );
SQL> Insert Into SocSec_Table Values ( '4444-A7-9999');
SQL> Insert Into SocSec_Table Values ( '444-7-79999' );
SQL> Insert Into SocSec_Table Values ( '987-65-4974' );
SQL>
SQL> Select '|' ,
2 SocSecno,
3 Case When Regexp_Like(SocSecNo,'^[0-9]{3}-[0-9]{2}-[0-9]{4}$')
4 Then 'Good'
5 Else 'Bad'
6 End
7 Valid
8 From SocSec_Table;

+=======================================================================================================================
| Begin Example: 12
+=======================================================================================================================
' SOCSECNO VALID
- -------------------- -----
| 444-77-9999 Good
| 494=77-9999 Bad
| 4444-A7-9999 Bad
| 444-7-79999 Bad
| 987-65-4974 Good
+=======================================================================================================================
| End Example: 12
+=======================================================================================================================

SQL> --------------------------------------------------------------------
SQL> Define PNo = 13;
SQL> -- Alternative matches
SQL> --------------------------------------------------------------------
SQL>
SQL> Select '|' ,String,
2 Regexp_Substr(String,'fl(y(ing)?|(ew)|(own)|(ies))' ,1,1)Re1,
3 Regexp_Substr(String,'fl(y(ing)?|(ew)|(own)|(ies))' ,1,2)Re2,
4 Regexp_Substr(String,'fl(y(ing)?|(ew)|(own)|(ies))' ,1,3)Re3,
5 Regexp_Substr(String,'fl(y(ing)?|(ew)|(own)|(ies))' ,1,4)Re4
6 From (
7 Select '|' ,
8 'If you flew like I fly, then you would have flown with all the flying birds.'
9 As String
10 From Dual
11 );

+=======================================================================================================================
| Begin Example: 13
+=======================================================================================================================
' STRING RE1 RE2 RE3 RE4
- ---------------------------------------------------------------------------- ------ ------ ------ ------
| If you flew like I fly, then you would have flown with all the flying birds. flew fly flown flying
+=======================================================================================================================
| End Example: 13
+=======================================================================================================================

To Separate Each Record With a Line

Set RecSep Each
Set RecSepChar '-'

Select *
From Emp
Where DeptNo = 20;

Remove Line Breaks from Data

If you have a column fornatted to hold the longest value, but data is still falling to a second line, it probably has a line break character in it. This is coded as 'CHR(10).' It can be replaced with a space to keep the value on one line as shown in the screen to the right.
Column Comments Format A80

Select Comments
From Dict
Where Table_Name = 'ALL_REFRESH_DEPENDENCIES';

Select Replace(Comments,Chr(10),' ')
As
Comments
From Dict
Where Table_Name = 'ALL_REFRESH_DEPENDENCIES';

Schemas

SYS
contains the data dictionary

SYSTEM
contains additional tables and views that store administrative information


Sample Schemas
The names are in alphabetical order, and specifies the order of creation.

HR - Human Resources
  • basic topics
  • an extension supports Oracle Internet Directory

OE - Order Entry
  • HR must be installed and you have the password to it
  • intermediate topics
  • multitude of datatypes
  • Oracle Spatial be installed
OC - Online Catalog (sub-schema)
  • object-relational examples

PM - Product Media
  • for multimedia datatypes
  • foreign keys to OE
  • database must be enabled for JVM and interMedia

IX - Information Exchange
  • shows advanced queuing
  • based on order entry data in OE

SH - Sales History
  • large amount of data
  • analytic processing
  • logically depends on the OE schema
  • requires the partitioning option


EXAMPLE Tablespace:
First create the tablespace that will hold all of the schema's segments.
Create Tablespace "EXAMPLE"
Logging Datafile '___________/example01.dbf' Size 50m Reuse
Autoextend On Next 50m Maxsize 1000m
Extent Management Local
Segment Space Management Auto;

PL/SQL Loop Creates Pivot

Declare
All_Depts Varchar2 (50) := '';

Cursor c_Loc Is
-----------------------------------
-- don't put ',' in front of 1st
-----------------------------------
Select Case When Rownum <> 1 Then ',' End
||
Loc
As
Loc
From Dept;

Begin
For c_Each In c_Loc
Loop
All_Depts := All_Depts || c_Each.Loc;
End Loop;

Dbms_Output.Put_Line (All_Depts);
End;
/

Bind Variables in SQL Code


@bind
---------------------------------------------------------
-- Bind variables can be declared in your SQL*Plus script
---------------------------------------------------------
VARIABLE s_table_name varchar2(30)

---------------------------------------------------------
-- Preface a bind variable with a colon to reference it
-- in a PL/SQL block.
---------------------------------------------------------
BEGIN
:s_table_name := 'EMPLOYEES';
END;
/

---------------------------------------------------------
--Bind variables persist until you exit SQL*Plus, so
--they can be referenced by more than one PL/SQL block.
---------------------------------------------------------
SET SERVEROUTPUT ON
BEGIN
DBMS_OUTPUT.PUT_LINE(:s_table_name);
END;
/
@bind2
------------------------------------------------------
--Bind variables can even be referenced by SQL queries
------------------------------------------------------

SELECT Table_Name, Tablespace_Name, Status
FROM user_tables
WHERE table_name = :s_table_name;


Note: Use 'Print' to display the value:
Print :s_table_name

Who's Running What?


Ttitle Left "Who's Running What" Skip 2
Set Linesize 200 Pagesize 200

Column Sid Format 999
Column Serial# Format 99999 Heading Serial|#
Column Audsid Format 99999 Heading Aud|Sid
Column Username Format A10 Heading Db|User
Column Osuser Format A20 Heading Os|User
Column Machine Format A20 Heading Machine
Column Terminal Format A12 Heading Terminal
Column Process Format A10 Heading Client|Process|Id
Column Spid Format A10 Heading Client|Server|Id
Column Program Format A20 Heading Client|Program|Name

Select s.Sid,s.Serial#,s.Audsid,
s.Username, s.Osuser,
s.Machine, s.Terminal,
s.Process,
p.Spid ,
s.Program
From v$Process P,v$Session S
Where p.Addr = s.Paddr
And s.Audsid = Userenv('SESSIONID');
Thanks to Rob Balter of MSA, Pittsburgh, PA for the basics of this query.

Saturday, September 13, 2008

Java Basics

Basic Example With User Input
import java.util.Scanner;
public class Sample1
{
public static void main( String args[] )
{
Scanner userInput = new Scanner( System.in );
int number1, half;

System.out.print( "Enter integer: " );
number1 = userInput.nextInt();

half = number1 /2;
System.out.printf( "Half of %d is %d\n", number1, half );
}
}

Read Next User Input
y = userInput.nextInt();
y = userInput.nextFloat();
x = userInput.nextDouble( );
y = userInput.next(); // for one word
y = userInput.nextLine(); // string

char c1 = userInput.findInLine(".").charAt(0); // for one char
int z = userInput.nextInt();
String word2 = userInput.next( ); // one word only
String line = userInput.nextLine( );

Data Types
all variables must be declared before using
* int : integer
* long : large integer
* float : small number with decimals
* double : large number with decimals
* char : a single character.
* String : immutable, once created, values can't change

int n3 = 2 , n4; // integer - can be defined
double d2 = 75.25 , d8;
long d3 = 450000;
String n5 = "abc de"; // string takes double quotes
char d5 = 'A'; // 1 char only with single quote

Math
int sum = number1 + number2  ;    // add numbers
gradeAv = (double)(grade1 + grade2)/2; // double to show decimal places

Assignments:
i += 2; // Same as "i = i + 2"
i -= 2; // Same as "i = i - 2"
i /= 2; // Same as "i = i / 2"
i *= 2; // Same as "i = i * 2"
i %= 2; // Same as "i = I % 2"

System.out.println(c++ ); // print then postincrement
System.out.println(++c ); // preincrement then print

User Input From Keyboard
import java.util.Scanner;
Scanner userInput = new Scanner(System.in);
number1 = userInput.nextInt();

Main Method
public static void main(String[] args)
{
} // end method main

Display Results On Screen -or-
Prompt For User Input
System.out.println("You entered " + d1 + " and " + d2);

System.out.print( "Enter 1st grade: " ); // cursor stays on line
System.out.println("Next enter two numbers.");

If Then Else

if (y == 1)
{
x = 1+2;
}
else if (y == 2)
{
x = 1*2;
}
else
{
x = 1/2;
}

Printf Formatting
%[flags][width][.precision]conversion

%-5c lj one character in a five character space
%+0d signed, padded integer
%.2f 2 decimal places

conversion specifying how to display the argument:
'd': decimal integer 'f': float
'c': 1 character 's': string.

flags: '-' LJ '^' uppercase
'+' sign '0' padded

\n - move cursor to new line

System.out.printf("n1 = %d \n", n1); // d for integer & long
System.out.printf("r1 = %.2f \n", r1); // f for float & double
System.out.printf("n5 = %s \n", n5); // s for string
System.out.printf("c1 = %c \n", c1); // c for one character
System.out.printf("n2 = %+d \n", n2); // whole # '+' for + or minus
System.out.printf("n4 = %20s \n", n4); // 20 character rj string
System.out.printf("n3 = %-20s\n", n3); // 20 character lj string

System.out.printf("All Data : %d %d %.2f %s %c \n",
n1, d1, r1, s2, n2 );

Comment
// this is a comment

Escape A Character
\  (i.e., "\"" would print " )

Continuation
System.out.printf( "Student:%s "   +
"Status:%s \n",
studentName, passStatus );

Creating An Instance Of A Class
   Func a1  = new Func();             // the class is 'Func'.    the instance is 'a1'
Scanner inp = new Scanner(System.in); // the class is 'Scanner'. the instance is 'inp'

fileName+ .java
public class fileName  // the exact name (including case) of the actual file name

.java is the source code
.class is the object code

Clear \n From Buffer after Number and before String or Character
This is necessary if you've requested a number from the user, and then want to get alphabetic data. If you don't do this, the prompt will be on the same line with the numeric answer.
String junk = userInput.nextLine( );

Words, Misc.
class - String is a class, as is Math
public class Student1
Scanner userInput = new Scanner( System.in );
public - program is accessible to any other code
method/function - list of things to do with a name. i.e., main
instance or object - userInput
inheritance - a new class enhances an existing class members.
superclass - the existing class
subclass - the new class
Constructors - create an instance/object of a class.

Two kinds of members in a class:
1. data (sometimes called fields)
2. methods or functions

// The object owns instance variables but not static variables.
final int size = 5; // 'final' indicates a constant. this is a data member
static int total = 0; // Static indicates a class variable -- they don't belong to the instance. static is shared by all objects.
myArray3 m1 = new myarray(); //m1 (an instance) would own a set of the variables
myArray3 m2 = new myarray(); //m2 (an instance) would own a set of the variables

//only 1 extend in a program. 1 parent can have more than one child.
      class myArray1 
class myArray2 extend myArray1
final class myArray3 extend myArray2 // can't have any children

public void computeTotal() // Method Header
{
t = n1+n2; // Method Body
System.out.printf("TOTAL = %d",t); // Method Body
}

Assigment: i += 2;
Assignment: a = b = c = 0; //evaluated from right to left
Declaration: int g1;

Wednesday, September 3, 2008

Drop If Exists

This is one way to issue a drop command and not have an error message posted when there is no table to drop.

The small test script shown below is the query that will call 'DROP.SQL' when a table is to be dropped. It creates a table, and then calls Drop with the variable &1 set equal to the table name to be dropped. It immediately tries it again to prove that no error message will be posted.
clear screen
Create Table TestTbl (num number);
@drop TestTbl

@drop TestTbl


This is the query that will generate the drop statement, and then run it:

Drop.SQL

Set Term Off                                    /* Hide what's going on */
Store Set InitSets Replace /* Save 'Sets' so they can be reset */
Set Pagesize 0 Feedback Off Verify Off Echo Off /* Turn off to create clean spool file */

Spool Drop_if_Exists.sql Replace /* This will be run after it is generated */

Select 'Drop Table '||Table_Name||';' /* See the spool file to view statment created */
From User_Tables
Where Table_Name = Upper('&1'); /* Where table name = the one passed in */

Spool Off

@initsets /* Reset their 'sets' */
@Drop_If_Exists /* Execute the spool file created */

SCN - System Change Number

To get the last change number:
Commit;

Variable Scn_Flash Number;
Execute :Scn_Flash := Dbms_Flashback.Get_System_Change_Number;

Column Scn_Flash Format 999,999,999
Print Scn_Flash

Oracle Text - Word Searches

Define Onoff = Off
rem +-----------------------------------------------------------------+
rem | Script ID: doi.sql
rem |
rem | Purpose: Oracle Text Search on words from the Declaration
rem | of Independence. Added some dog words to test
rem | 'About'. No luck with 'About' or 'stem'.
rem |
rem | Developer: Lynn Tobias
rem | Script Date: 9/2/2008
rem | Oracle Ver: 10g
rem |
rem | Table(s) Used: DOI_Context and DOI_CTXCAT created in this query.
rem |
rem | Revisions: Dvl Date Ver Comment/Change
rem | --- -------- --- --------------------------------+
rem |
rem +-----------------------------------------------------------------+

Clear Screen
Set Echo &Onoff Feedback &Onoff Linesize 100 Term Off

Column Words Format A64 Word_Wrapped
Column Pid Format 99 Heading PId

--+--------------------------------------------------------------------------+
--| Drop the table before recreating it and inserting a few recs
--+--------------------------------------------------------------------------+

Drop Table Doi_Context Cascade Constraints Purge;
Drop Table Doi_Ctxcat Cascade Constraints Purge;

Create Table Doi_Context
( Pid Number(2)
, Words Varchar2(4000)
, Constraint Doi_Pk Primary Key (Pid)
);
Insert Into DOI_Context Values(1,'Governments Governed people LAWS abolishing GOVERNORS poodle');
Insert Into DOI_Context Values(2,'representation labrador justice people basset hound ');
Insert Into DOI_Context Values(3,'laws representative peace corgi representatives people');
Insert Into DOI_Context Values(4,'laws abolishing government german shepherd justice peace');
Commit;

--+--------------------------------------------------------------------------+
--| Create a 2nd similar table to test ctxcat index and Catsearch.
--| "You must create a primary key for table."
--+--------------------------------------------------------------------------+

Create Table Doi_Ctxcat
As Select *
From Doi_Context;

Alter Table Doi_Ctxcat Add Primary Key (Pid);

--+--------------------------------------------------------------------------+
--| This is my attempt to get the stem and 'about' to work. No luck yet.
--| The lexer parameter is copied from the internet.
--+--------------------------------------------------------------------------+

Begin
Ctx_Ddl.Create_Preference( 'MyLex', 'Basic_Lexer' );
Ctx_Ddl.Set_Attribute ( 'MyLex', 'Printjoins' , '_-' );
Ctx_Ddl.Set_Attribute ( 'MyLex', 'Index_Themes', 'yes');
Ctx_Ddl.Set_Attribute ( 'MyLex', 'Index_Text' , 'yes');
End;
/
Create Index Doi_Context_Index
On Doi_Context(Words)
Indextype Is Ctxsys.Context
Parameters ( 'Lexer MyLex' );

Create Index Doi_Ctxcat_Index
On Doi_Ctxcat(Words)
Indextype Is Ctxsys.Ctxcat;

--+--------------------------------------------------------------------------+
--| When the text is changed, the index is out of sync unless you execute
--| the sync_index statement -- or you include the sync parameter in the
--| create index.
--+--------------------------------------------------------------------------+

--Parameters('sync (On Commit)');
--execute CTX_DDL.Sync_index('doi_context_index');

--+--------------------------------------------------------------------------+
--| Show the indexes created
--+--------------------------------------------------------------------------+
Column Owner Format A6
Column Constraint_Name Format A17
Column Deferrable Format A10
Column Generated Format A9
Column Index_Name Format A17

Select *
From User_Constraints
Where Constraint_Name Like '%DOI%'
Or Table_Name Like '%DOI%';

--+--------------------------------------------------------------------------+
--| These gave identical results. Display all lines with 'people'
--+--------------------------------------------------------------------------+
Set Term On
Column Words Heading 'Contains(Words, people)'

Select *
From Doi_Context
Where Contains(Words, 'people') >0;

--Select * From Doi_Ctxcat Where Catsearch(Words, 'people', NULL) >0;

--+--------------------------------------------------------------------------+
--| Print any lines with both 'laws' and 'people' in it.
--+--------------------------------------------------------------------------+
Column Words Heading 'Contains(Words, laws AND people)'

Select Pid, Words
From Doi_Context
Where Contains(Words,'laws AND people')>0;

--Select Pid, Words From Doi_Ctxcat Where Catsearch(Words,'laws people', NULL)>0;

--+--------------------------------------------------------------------------+
--| Any line with one word or the other
--+--------------------------------------------------------------------------+
Column Words Heading 'Contains(Words,laws Or People)'

Select Pid, Words
From Doi_Context
Where Contains(Words,'laws Or People')>0;

--select Pid, words From DOI_Ctxcat where catsearch(words,'laws |people', NULL)>0;

--+--------------------------------------------------------------------------+
--| Any line with one word near the other
--+--------------------------------------------------------------------------+
Column Words Heading 'Contains(Words,laws Near People)'

Select Pid, Words, Score(10)
From Doi_Context
Where Contains(Words,'laws Near People',10)>0;

--+--------------------------------------------------------------------------+
--| Any line with first word but not second
--+--------------------------------------------------------------------------+
Column Words Heading 'Contains(Words,laws - People) Laws but not people'

Select Pid, Words
From Doi_Context
Where Contains(Words,'laws - People')>0;

--Select Pid, Words From Doi_Ctxcat Where Catsearch(Words,'laws - People', Null)>0;

--+--------------------------------------------------------------------------+
--| One of three words
--+--------------------------------------------------------------------------+
Column Words Heading 'Contains(Words,Government Or People Or Abolishing'

Select Pid, Words, Score(10)
From Doi_Context
Where Contains(Words,'Government Or People Or Abolishing',10)>0;

Column Words Heading 'Words Weighted: government*3 Or People*1 Or Abolishing*2'

Select Pid, Words,Score(10)
From Doi_Context
Where Contains(Words,'government*3 Or People*1 Or Abolishing*2',10)>3;

--+--------------------------------------------------------------------------+
--| % is wildcard. $ is stem search (not working)
--+--------------------------------------------------------------------------+
Column Words Heading 'Wildcards: (Words,represent%'

Select Pid, Words, Score(10)
From Doi_Context
Where Contains(Words,'represent%',10)>0;

--Select Pid, Words, Score(10)
--From Doi_Context
--Where Contains(Words,'$Represent',10)>0;

--+--------------------------------------------------------------------------+
--| Fuzzy Match: Justis -> Justice
--+--------------------------------------------------------------------------+
Column Words Heading 'Fuzzy Match: (Words,?Justis'

Select Pid, Words, Score(10)
From Doi_Context
Where Contains(Words,'?Justis',10)>0;

--+--------------------------------------------------------------------------+
--| Perform a Soundex Search
--+--------------------------------------------------------------------------+
Column Words Heading 'Soundex: !Piece'

Select Pid,Words, Score(10)
From Doi_Context
Where Contains(Words,'!Piece',10)>0;

--+--------------------------------------------------------------------------+
--| Topic Search - not working yet
--+--------------------------------------------------------------------------+
--Column Words Heading 'Topic Seach: About(Dog)

--Select Pid, Words, Score(10)
-- From Doi_Context
-- Where Contains(Words,'about(Dog)',10)>0;

Tuesday, September 2, 2008

Data Pump - Parameter File

DIRECTORY             = Directory name from "CREATE DIRECTORY dpump_dir1 AS 'c:/data/datapump'"
CONTENT = ALL, DATA_ONLY, METADATA_ONLY
DUMPFILE = scott1.dmp, scott2.dmp (par_exp%u.dmp if parallel)
PARALLEL = 1 (Max # of threads) (EE only) (chg on-the-fly) (have 1 file on separate disk for each)


FULL = Y|N (default = N)(must have EXP_FULL_DATABASE role)
SCHEMAS = hr,scott,oe (default: login schema).
TABLESPACES = tblsp1, tblsp2
TABLES = emp, dept, salgrade, scott.table:partition
TRANSPORT_TABLESPACES = List of tablespaces from which metadata will be unloaded. (must have EXP_FULL_DATABASE role)
TRANSPORT_FULL_CHECK = N - default. Verify storage segments of all tables


ESTIMATE = BLOCKS - default or STATISTICS
ESTIMATE_ONLY = N | Y


EXCLUDE = Table[:EMP] , (Filter Metadata)
INCLUDE = Table:Dept, (Filter Metadata) (Objects and their dependents)
INCLUDE = TABLE:"IN ('EMPLOYEES', 'DEPARTMENTS')"
INCLUDE = PROCEDURE
INCLUDE = INDEX:"LIKE 'EMP%'"


SAMPLE = .000001 - 99 SAMPLE="HR"."EMPLOYEES":50
QUERY = employees:'"WHERE department_id > 10 AND salary > 10000"'


FLASHBACK_SCN = SCN used to set session snapshot back to.
FLASHBACK_TIME = Time used to get the SCN closest to the specified time.


LOGFILE = export.log
NOLOGFILE = N


ATTACH = Attach to existing job, e.g. ATTACH [= job name].
COMPRESSION = METADATA_ONLY (default) or NONE
ENCRYPTION_PASSWORD = Password key for creating encrypted column data.
FILESIZE = Specify the size of each dumpfile in units of bytes.
JOB_NAME = SYS_EXPORT__NN -- can't match any view or table in schema
NETWORK_LINK = Name of remote database link to the source system.
STATUS = 60 (every 60 secs job status is displayed. default=0
VERSION = COMPATIBLE-default, LATEST, or any valid database version not less than 9.2

Jobname Check for Data Pump

rem +--------------------------------------------------------------------------+
rem | Script ID: ckjob.sql
rem |
rem | Purpose: Check the job name to see if a table exists with that name
rem | before Data Pump job is run
rem |
rem | Developer: Lynn Tobias
rem | Script Date: 9/2/2008
rem | Oracle Ver: 10g
rem |
rem | Table(s) Used: All_Catalog
rem |
rem | Variables: Schema JobName Ctr OnOff
rem |
rem | Revisions: Dvl Date Ver Comment/Change
rem | --- -------- --- -----------------------------------------+
rem |
rem +--------------------------------------------------------------------------+
Define OnOff = Off
Clear Screen
Set Echo &OnOff Term On

Prompt +--------------------------------------------------------------------------+
Prompt | This will check your Data Pump jobname against the schema. |
Prompt | Since Data Pump creates a table with this name, it cannot already exist. |
Prompt +--------------------------------------------------------------------------+
Prompt
--+-----------------------------------------------------------------------------
--| Ask them for schema (if the current it will be equal to _User) and jobname
--+-----------------------------------------------------------------------------
Accept Schema Default &_User Prompt 'Type Schema or press enter for default (&_user.): '
Prompt
Accept JobName Prompt 'Your jobname : '

--+-----------------------------------------------------------------------------
--| Turn off the display and get the count of tables like the job name
--+-----------------------------------------------------------------------------
Set Term &OnOff
Column Ctr New_Value Ctr

Select Count(*) Ctr
From All_Catalog
Where Table_Name = Upper('&JobName')
And Owner = '&Schema';

--+-----------------------------------------------------------------------------
--| Based on the count, display an error or not
--+-----------------------------------------------------------------------------
Set Pagesize 50 Term On Heading &OnOff Feedback &OnOff

Ttitle Left 'Results of jobname check: ' Skip 1 -
'------------------------- ' Skip 2

Select Case when &Ctr > 0
Then 'Error: A jobname can''t be the name of a table or view in the schema'
Else 'JobName is ok to use.'
End
From Dual;
Ttitle off
Undefine Schema JobName Ctr