Thursday, July 23, 2009

Delete Based on Another Table

I recently had to delete records in one table based on the data in another table. This isn't particularly tricky, but the only examples I could find online ended up deleting all the records in the table.

The code at the beginning is just to set up a table I can use as an example.
Conn Scott/Tiger
Set Feedback On Echo On

Select *
From Dept;

Drop Table Dept2 Purge;

Create Table Dept2 As
Select * From Dept;

Insert Into Dept2 Values(50,'HR','PITTSBURGH');
Insert Into Dept2 Values(60,'HOUSEKEEPING','LA');
Insert Into Dept2 Values(70,'MANAGEMENT','ATLANTA');

Select * From Dept2;
















This code deletes from the newly created table where a record exists in the original table that has a matching key.
Delete From Dept2
Where Exists
(Select 1
From Dept
Where Dept.Deptno = Dept2.Deptno);

Select * From Dept2;

Wednesday, July 8, 2009

Timestamp in an External Table

Since this wasn't particularly easy to find, and it took several tries, I decided to post it here. As most things, once you know how to write it, it's not particularly tricky.

Input Data from External Table:
1,Jan 8 1998 12:43:27:012AM
2,Feb 19 1998 2:43:27:111PM
3,Jan 8 2008 3:49:27:693PM


Create Table Ext_Dt
( Item Number
, Needed_By Timestamp
)
Organization External
(
Type Oracle_Loader
Default Directory Ext
Access Parameters
(
Records Delimited By Newline
Badfile 'Date.Bad'
Logfile 'Date.Log'
Fields Terminated By ','
Missing Field Values Are Null
(
Item,
Needed_By Char Date_Format Timestamp Mask 'Mon Dd Yyyy Hh:Mi:Ss:Ff3am'
)
)
Location (Ext:'Dt.Txt')
)
Reject Limit Unlimited;

Select Item
, Needed_By
, To_Char(Needed_By,'Mon' ) Mth
, To_Char(Needed_By,'Hh24') Hr
From Ext_Dt;