How to read any file using external tables.

Hi folks,
I have written an application that reads a series of csv files using external tables which works fine as long as I specify each file name in the directory i.e.......
CREATE TABLE gb_test
(file_name varchar2(10),
rec_date date
rec_name VARCHAR2(20),
rec_age number,
ORGANIZATION EXTERNAL
TYPE ORACLE_LOADER
DEFAULT DIRECTORY GB_TEST
ACCESS PARAMETERS
RECORDS DELIMITED BY NEWLINE
FIELDS TERMINATED BY ','
LOCATION ('data1.csv','data2.csv','data3.csv','data4.csv')
PARALLEL 5
REJECT LIMIT 20000;
However I have discovered that I may not know the name of the files to be processed prior to the program being run so just want to read any file regardless of it's name (although it will always be a .csv file).
Is there a way to ensure that you don't need to specify the files to be read in the LOCATION part of the syntax.
Thanks in advance.
Graham.

Right, I have now completed this, however it's currently only working as SYS as opposed to any user, however here is a detail of the scenario and the steps required in case any of you guys need in the future ......
The problem was I needed to search for csv files on my hard-drive. These files would be stored in a series of directories (a through to z), so I needed a way to read all 26 directories and process all files in these directories.
The problem was, prior to running the program, the user would remove all the files in the directories and insert new ones, but it was never known how many he would decide to do each time.
Solution: I created a table called stock_data_directories as follows ...
create table stock_data_directories(sdd_rec_no number,
sdd_table_name varchar2(50),
sdd_directory_name varchar2(50),
sdd_directory_path varchar2(100));
Then inserted 26 records like ...
insert into stock_data_directories(sdd_rec_no,sdd_table_name,sdd_directory_name,sdd_directory_path)
values(1,'rawdata_a','KPOLLOCKA','C:\KPOLLOCK\A')
insert into stock_data_directories(sdd_rec_no,sdd_table_name,sdd_directory_name,sdd_directory_path)
values(2,'rawdata_b','KPOLLOCKB','C:\KPOLLOCK\B');
etc...etc...
Then created 26 DIRECTORIES E.G.
CREATE OR REPLACE DIRECTORY KPOLLOCKA AS 'C:\KPOLLOCK\A';
CREATE OR REPLACE DIRECTORY KPOLLOCKB AS 'C:\KPOLLOCK\B';
Then created 26 external tables like the following ...
CREATE TABLE rawdata_a
(stock varchar2(1000),
stock_date varchar2(10),
stock_open VARCHAR2(20),
stock_high varchar2(20),
stock_low varchar2(20),
stock_close VARCHAR2(30),
stock_qty varchar2(20) )
ORGANIZATION EXTERNAL
TYPE ORACLE_LOADER
DEFAULT DIRECTORY KPOLLOCKA
ACCESS PARAMETERS
RECORDS DELIMITED BY NEWLINE
FIELDS TERMINATED BY ','
LOCATION ('AA.csv')
PARALLEL 5
REJECT LIMIT 20000
This basically says in directory rawdata_a it currently has 1 file called AA.csv.
Then wrote a procedure as follows ...
procedure p_process_files(pv_return_message OUT varchar2)is
cursor c_get_stock_data_directories is
select distinct sdd_directory_path,
sdd_table_name
from stock_data_directories
order by sdd_table_name;
vv_return_message varchar2(1000);
begin
-- here get the files for each directory
for r_get_stock_directories in c_get_stock_data_directories loop
p_build_external_table(r_get_stock_directories.sdd_directory_path,
     r_get_stock_directories.sdd_table_name,
     vv_return_message);
end loop;
end;
then wrote a procedure called p_build_external_table as follows ...
procedure p_build_external_table(pv_directory_path IN stock_data_directories.sdd_directory_path%type, -- e.g. 'C:\kpollock\A\
pv_table_name IN stock_data_directories.sdd_table_name%type, -- e.g. rawdata_a
pv_return_message OUT varchar2) is
vv_pattern VARCHAR2(1024);
ns VARCHAR2(1024);
vv_file_name varchar2(4000);
vv_start_string varchar2(1) := '''';
vv_end_string varchar2(3) := ''',';
vn_counter number := 0;
vv_err varchar2(2000);
BEGIN
vv_pattern := pv_directory_path||'*';
SYS.DBMS_BACKUP_RESTORE.searchFiles(vv_pattern, ns);
FOR each_file IN (SELECT FNAME_KRBMSFT AS name FROM X$KRBMSFT) LOOP
if each_file.name like '%.CSV' then
vv_file_name := vv_file_name||vv_start_string||substr(each_file.name,instr(each_file.name,'\',1,3)+1)||vv_end_string;
     vn_counter := vn_counter + 1;
end if;
END LOOP;
vv_file_name := substr(vv_file_name,1,length(vv_file_name)-1); -- remove final , from string
execute immediate 'alter table '||pv_table_name||' location('||vv_file_name||')';
pv_return_message := 'Successfully changed '||pv_table_name||' at '||pv_directory_path||' to now have '||to_char(vn_counter)||' directories';
exception
when others then
vv_err := sqlerrm;
pv_return_message := ' Error found updating directories. Error = '||vv_err;
END;
This reads every file in the directory and appends it to a list, so if it finds A.csv and ABC.csv, then using the dynamic sql, it alters the location to now read 'a.csv','abc.csv',
It ignores all other file extentions.

Similar Messages

  • How to write data to text file using external tables

    can anybody tell how to write data to text file using external tables concept?

    Hi,
    Using external table u can load the data in your local table in database,
    then using your local db table and UTL_FILE pacakge u can wrrite data to text file
    external table
    ~~~~~~~~~~~
    http://download-east.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_7002.htm#i2153251
    UTL_FILE
    ~~~~~~~~~
    http://download-east.oracle.com/docs/cd/B19306_01/appdev.102/b14258/u_file.htm#sthref14093
    Message was edited by:
    Nicloei W
    Message was edited by:
    Nicloei W

  • How to find rejected rows using External Table

    Hi all,
    I had written a stored procedure to read comma(,) separated flat file using External Tables in oracle 9i with Reject Limit "Unlimited" Option. Sometimes all rows are successfully loaded into external table and sometimes some rows are failed, I can find out those rows from logfile created by oracle. I want to inserted those rows key values into some other table. Can any body suggest/links how to write this.
    Thanking you in advance

    "Is there a way to have the system truncate the log files besides some O/S utility that will scour the directory every night, week, etc.?"
    You can use UTL_FILE.FREMOVE to delete the file, if you have sufficient privileges. You can schedule it using DBMS_JOB if you like or run it before you recreate the file, as demonstrated below. The pl/sql block to check whether the file exists is used for demonstration purposes only and is not necessary. This is just one method. There are various ways to delete or truncate a file. This just seems like the simplest.
    scott@ORA92> CREATE OR REPLACE DIRECTORY mydir AS 'c:\oracle'
      2  /
    Directory created.
    scott@ORA92> DECLARE
      2    v_bfile BFILE := BFILENAME ('MY_DIR', 'test_tab.log');
      3  BEGIN
      4    IF DBMS_LOB.FILEEXISTS (v_bfile) = 1
      5    THEN DBMS_OUTPUT.PUT_LINE ('test_tab.log exists');
      6    ELSE DBMS_OUTPUT.PUT_line ('test_tab.log does not exist');
      7    END IF;
      8  END;
      9  /
    test_tab.log exists
    PL/SQL procedure successfully completed.
    scott@ORA92> EXECUTE UTL_FILE.FREMOVE ('MY_DIR', 'test_tab.log')
    PL/SQL procedure successfully completed.
    scott@ORA92> DECLARE
      2    v_bfile BFILE := BFILENAME ('MY_DIR', 'test_tab.log');
      3  BEGIN
      4    IF DBMS_LOB.FILEEXISTS (v_bfile) = 1
      5    THEN DBMS_OUTPUT.PUT_LINE ('test_tab.log exists');
      6    ELSE DBMS_OUTPUT.PUT_line ('test_tab.log does not exist');
      7    END IF;
      8  END;
      9  /
    test_tab.log does not exist
    PL/SQL procedure successfully completed.
    scott@ORA92> CREATE TABLE test_tab
      2    (col1 NUMBER,
      3       col2 VARCHAR2(4))
      4  ORGANIZATION external
      5    (TYPE ORACLE_LOADER
      6       DEFAULT DIRECTORY mydir
      7       ACCESS PARAMETERS
      8         (RECORDS DELIMITED BY NEWLINE
      9          BADFILE 'MYDIR':'test_bad.bad'
    10          LOGFILE 'MYDIR':'test_tab.log'
    11          FIELDS TERMINATED BY ","
    12            (col1,
    13             col2))
    14       LOCATION ('test.dat'))
    15  REJECT LIMIT UNLIMITED
    16  /
    Table created.
    scott@ORA92> SELECT * FROM test_tab
      2  /
          COL1 COL2
             1 a
             2 b
    scott@ORA92> "Or is there a way to prevent the log from being written to every time it's accessed?"
    You can use NOLOGFILE as an access parameter to prevent it from being written to, as shown below.
    scott@ORA92> CREATE OR REPLACE DIRECTORY mydir AS 'c:\oracle'
      2  /
    Directory created.
    scott@ORA92> CREATE TABLE test_tab
      2    (col1 NUMBER,
      3       col2 VARCHAR2(4))
      4  ORGANIZATION external
      5    (TYPE ORACLE_LOADER
      6       DEFAULT DIRECTORY mydir
      7       ACCESS PARAMETERS
      8         (RECORDS DELIMITED BY NEWLINE
      9          BADFILE 'MYDIR':'test_bad.bad'
    10          NOLOGFILE
    11          FIELDS TERMINATED BY ","
    12            (col1,
    13             col2))
    14       LOCATION ('test.dat'))
    15  REJECT LIMIT UNLIMITED
    16  /
    Table created.
    scott@ORA92> SELECT * FROM test_tab
      2  /
          COL1 COL2
             1 a
             2 b
    scott@ORA92> "Is there a way to have the log written only when an error occurs?"
    Not that I know of, but that does not mean that somebody else doesn't know how or isn't able to figure out a way. If you do find a way, please post it for the benefit of the rest of us.

  • How to read HTML files using UTL_FILE

    Hello Friends,
    How to read HTML files using UTL_FILE package ? According
    to Oracle documentation UTL_FILE can read or write OS Text Files.
    Thanx in advance..
    Adi

    HI Hareesh,
    i have gone through that blog.
    i tried it...but i am getting mapping error  no receiver determination fond because there are so  many excel files.
    my data is available on sharedString.xml but also it is in not same order.
    i have no clue how to handle this part form the blog.
    "This way our mapping will receive all data from the sheet in an XML format. The only thing that's left is to create an XSD file from the XML file we received in order to be able to use it in the mapping and as our Service Interface and we can proceed with mapping. As you can see from the sheet.xml files all the data is placed with column name and row number so it's not that difficult to map it to an table type format using the Message Mapping only (no java, abap mapping required)."

  • How to read pdf file using file adapter

    Hi..
        How to read pdf file using file adapter?
    regards
    Arun

    Hi
    This may help you
    /people/sap.user72/blog/2005/07/27/xi-generate-pdf-file-out-of-file-adapter
    /people/alessandro.guarneri/blog/2007/02/21/sap-xi-acting-as-a-huge-file-mover
    ---Ram

  • Need to merge a csv file using external tables into a main table

    Hi,
    I have a csv file which contains the date(with time stamp), column1(number),column2(number), column3 (number). I am using external tables concept to load the data froom csv to this external table and then merging into the main table. Problem here is : the csv file is a system generated file and nothing can be edited under it. our aim is to automate this process of loading data from csv to the table. In this csv the date time stamp is not in the proper format.I mean the date is not visible and only minutes and seconds are visible.By changing the format in csv manually this can be overcome.but we donot need any manual intervention.
    how can i overcome this problem ?? please help mee...
    Excels data looks like:
    (PDH-TSV 4.0) (India Standard Time)(-330)     \\DISAPPSER01\Processor(_Total)\% Privileged Time     \\DISAPPSER01\Processor(_Total)\% Processor Time     \\DISAPPSER01\Web Service(_Total)\Current Connections
    56:59.0               47
    57:09.0     0.72379582     4.204561281     46
    57:19.0     0.916548537     4.006179927     44
    57:29.0     0.663034771     3.674662541     43
    57:39.0     0.750789844     4.093933999     42
    57:49.0     0.721538487     2.650858026     40
    57:59.0     0.594781604     3.333393703     40

    please format your sample data giving header to the column so that we can make sense out of the values, also since the minutes and seconds are only given, what is the date to be considered for records to be moved to the master table, sysdate or will the date be passed as a parameter?

  • How to read pdf files using java.io package classes

    Dear All,
    I have a certain requirement that i should read and write PDF files at runtime. With normal java file IO reading is not working. Can any one suggest me how to proceed probably with sample code block
    Thanks in advance.

    hi I also have the pbm. to read pdf file using JAVA
    can any body help meWhy is it so difficult to read the thread you posted in? They say: java.io is pointless, use iText. So why don't you?
    or also I want to read a binary encoded data into
    ascii,
    can anybody give me a hint how to do it.Depends on what you mean with "binary encoding". ASCII's binary encoding, too, basically.

  • How to import tab delimited using external table?

    Hi all,
    I'm using external table to import data from a tab delimited file. However, I keep getting an error message. I used both TERMINATED BY OX'09' and X'09' but still could not get it work.
    Does anyone know how to solve this problem?
    Thank you very much.

    Hi
    Try this:
    import datafile="/myfiles/mydata" out=mydata dbms=tab replace delimiter='&' getnames=yes
    run;
    Thanks

  • How to read 835 files using ssis

    Hello Everyone,
    It is possible read 835 files using ssis.
    Please share your suggestions on this.
    Regards,
    Vaishu

    Hi Vaishu,
    None of the canned (standard) SSIS tasks let you do so.
    But if you can buy http://www.cozyroc.com/ssis/edi-source (I am not anyhow affiliated with CozyRoc) it states it can read ERA (AKA 835) files. CozyRoc lets you run it for free in Dev.
    If there will be a decision not to buy then you can simply crate a transformation out of several manipulations or by creating a custom SSIS component or some other programming methods need to be used.
    PS: Again, I just know CozyRoc quality of components is awesome, but I do not make any profit from referring to it.
    Arthur My Blog

  • How to read a file using servlet

    hi ,
    i've to read a file using servlet ,
    should read the file using servlet and display it in JSP,Could anybody get me how can i do it .
    Shiva

    To do that you need to get the response output stream and write yur file contents to that.
    response.setContentType(mimeType); //Set the mime type for the response
    ServletOutputStream sos = resp.getOutputStream();
    sos.write(bytes from your file input stream);
    sos.close();

  • How to read specific lines from a text file using external table or any other method?

    Hi,
    I have a text file with delimited data, I have to pick only odd number rows and load into a table...
    Ex:
    row1:  1,2,2,3,3,34,4,4,4,5,5,5,,,5  ( have to load only this row)
    row2:   8,9,878,78,657,575,7,5,,,7,7
    Hope this is enough..
    I am using Oracle 11.2.0 version...
    Thanks

    There are various ways to do this.  I would be inclined to use SQL*Loader.  That way you can load it from the client or the server and you can use a SQL*Loader sequence to preserve the row order in the text file.  I would load the whole row as a varray into a staging table, then use the TABLE and MOD functions to load the individual numbers from only the odd rows.  Please see the demonstration below.
    SCOTT@orcl12c> HOST TYPE text_file.csv
    1,2,2,3,3,34,4,4,4,5,5,5,,,5
    8,9,878,78,657,575,7,5,,,7,7
    101,201
    102,202
    SCOTT@orcl12c> HOST TYPE test.ctl
    LOAD DATA
    INFILE text_file.csv
    INTO TABLE staging
    FIELDS TERMINATED BY ','
    TRAILING NULLCOLS
    (whole_row VARRAY TERMINATED BY '/n' (x INTEGER EXTERNAL),
    rn SEQUENCE)
    SCOTT@orcl12c> CREATE TABLE staging
      2    (rn         NUMBER,
      3     whole_row  SYS.OdciNumberList)
      4  /
    Table created.
    SCOTT@orcl12c> HOST SQLLDR scott/tiger CONTROL=test.ctl LOG=test.log
    SQL*Loader: Release 12.1.0.1.0 - Production on Tue Aug 27 13:48:37 2013
    Copyright (c) 1982, 2013, Oracle and/or its affiliates.  All rights reserved.
    Path used:      Conventional
    Commit point reached - logical record count 4
    Table STAGING:
      4 Rows successfully loaded.
    Check the log file:
      test.log
    for more information about the load.
    SCOTT@orcl12c> CREATE TABLE a_table
      2    (rn       NUMBER,
      3     data  NUMBER)
      4  /
    Table created.
    SCOTT@orcl12c> INSERT INTO a_table (rn, data)
      2  SELECT s.rn,
      3         t.COLUMN_VALUE data
      4  FROM   staging s,
      5         TABLE (s.whole_row) t
      6  WHERE  MOD (rn, 2) != 0
      7  /
    17 rows created.
    SCOTT@orcl12c> SELECT * FROM a_table
      2  /
            RN       DATA
             1          1
             1          2
             1          2
             1          3
             1          3
             1         34
             1          4
             1          4
             1          4
             1          5
             1          5
             1          5
             1
             1
             1          5
             3        101
             3        201
    17 rows selected.

  • Is there a way to know how many rows were rejected using external tables?

    Hi,
    I'm developing a package that needs to load different kinds of text files into the DB.
    I was wondering whether there's a way of knowing in SQL or PL/SQL how many rows were rejected if my external table is defined with "reject limit unlimited".
    I'm using the external tables in "insert into ... (select ... from external_table where...)"
    sql%rowcount returns the number of inserted rows
    I was hoping for something similar/easy to get the number of rejected rows as well.
    I know I can try to analyze the bad file for the number of records if there's no other way...
    Thanks in advance.

    Pyrocks wrote:
    I was afraid of this answer...
    this is a certain "no there's no other way" or should i wait for other responses (no disrespect - just want to make sure :) )Well the difference would be that this external table will have no complex logic. You would simple read in all the lines from the bad file. The chances that this is broken are therefore very slim compared with your original external table.
    And tehre are many other ways possible. For example you can first copy the file into a real internal (temp) table without using any processing logic but with using an external table. Then do the processing / logic checking of the data and move the data from this temp table into your final data structure. Since you move the data two times the whole process will be slower then the original version.

  • How to read any file image file or doc. or any kind and put it in abap

    Hi All,
    I want to write RFC to read any kind of file ,image or doc or any type and put it in ABAP .
    Also read that file from ABAP .
    Can anyone suggest me how to do this functionality?
    Thanks.

    The internal table can be of of string.
    Types : begin of typ_line,
                 line type string,
                end   of typ_line,
                typ_doc type table of typ_line.
    data : t_file type typ_doc.
      CALL FUNCTION 'GUI_UPLOAD'
        EXPORTING
          filename                = l_file
          filetype                = 'bin'
        TABLES
          data_tab                = t_file
        EXCEPTIONS
          file_open_error         = 1
          file_read_error         = 2
          no_batch                = 3
          gui_refuse_filetransfer = 4
          invalid_type            = 5
          no_authority            = 6
          unknown_error           = 7
          bad_data_format         = 8
          header_not_allowed      = 9
          separator_not_allowed   = 10
          header_too_long         = 11
          unknown_dp_error        = 12
          access_denied           = 13
          dp_out_of_memory        = 14
          disk_full               = 15
          dp_timeout              = 16
          OTHERS                  = 17.
    You will have the contents into this internal table T_FILE. You can loop on this table and store it as a application server file using WRITE DATASET.

  • How to read SGML files using Java

    I've got a text categorisation test collection called Reuters-21578 for my Information Retrieval project. It is distributed in 22 files. Each of the first 21 files (reut2-000.sgm through reut2-020.sgm) contains 1000 documents, while the last (reut2-021.sgm) contains 578 documents. The files are in SGML format. Each of the 22 files begins with a document type declaration line:
    <!DOCTYPE lewis SYSTEM "lewis.dtd"> The DTD file lewis.dtd is included in the distribution. Following the document type declaration line are individual Reuters articles marked up with SGML tags.
    My questions is how to write a java program to read those 21578 documents or transform them into 21578 seperated text files.

    I guess I missed something. What is Renes link?. The
    parser stuff isn't really what I'm looking for. I'm
    a new at and just learning java and I just want to
    know the easiest way to read a SGML file. Should I
    use a buffered Reader with a Pushback Input Stream?Hang on.....you want to just read the file without intelligently extracting the SGML data contained within and so have no need of a parser?
    Well, in that case, its just text.....so just use BufferedReader or whatever to read the text data. If I understand you correctly, all you really wanted to ask was "how do I read a text file?"

  • Prblem white handle files using External tables

    Hi,
    I Created an external table to handle files.
    Its working fine.
    But it is rejecting the records, where the fnal column in a record contains no (null) value.
    The data is as follows.
    empno|name|positon
    184|abc|supervisor
    185|xyz|
    186|efg|clerk
    I have given '\n' as row delimiter. and '|' as field delimiter.
    For the above data I am getting only the 1st and 3rd records only.
    External tables are not accepting the 2nd re4cord.
    In the log file it is specifying the error as "KUP-04023: field start is after end of record".
    Could anyone please give me some idea to solve this problem.
    Thank you,
    Regards,
    Gowtham Sen.

    Hi Michaels,
    I have one more doubt.
    After I added the clause "MISSING FIELD VALUES ARE NULL", its working fine.
    Case 1:
    The data is as follows.
    empno|name|positon
    184|abc|supervisor
    185|xyz|
    186|efg|clerk
    Now I am getting the data while query the external table as follows
    empno name position
    184 abc supervisor
    185 xyz <null>
    186 efg clerk
    Case 2:
    But there is a case that the data my come in the following way.
    empno|name|positon
    184|abc|supervisor
    185|xyz|
    186|efg|clerk
    18
    187
    For this data I am getting the data if I query external table as follows.
    empno name position
    184 abc supervisor
    185 xyz <null>
    186 efg clerk
    18 <null> <null>
    187 <null> <null>
    Here I would like to result the last records because, the records violated the formating. But its not doing as I expected.
    Do I need to add any other clauses.
    Thanks in advance,
    Thank you,
    Regards,
    Gowtham Sen

Maybe you are looking for