Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

plsql - Oracle UTL_FILE read CSV file lines

i'm using UTL_FILE package to read a csv file , then insert values in table, but my issue is how to read values separated by Commas.. , this is my code :

     declare
         file1 UTL_FILE.FILE_TYPE;
         str varchar2(200 CHAR);
        begin
         file1 := UTL_FILE.FOPEN('DRCT1','test_file.csv','R');

         loop
          UTL_FILE.GET_LINE(file1,str);
-- here i want to read each value before the Commas then insert them in my table
-- insert statement..
          dbms_output.put_line(str);
         end loop;

        exception
        when no_data_found then
        UTL_FILE.FCLOSE(file1);

        end; 
        /

this is my csv file :

100,Steven,King
101,Neena,Kochha
102,Lex,De Haan
103,Alexander
104,Bruce,Ernst

please do you have any suggestion to my issue ?

Regards .

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's an example which shows how to do that. My code slightly differs from yours because of different directory and file names.

Sample table, which will contain data stored in the file:

SQL> create table test2 (id number, fname varchar2(20), lname varchar2(20));

Table created.

Code; interesting part is line 14 and the way to split the whole row into separate values:

SQL> declare
  2    l_file         utl_file.file_type;
  3    l_text         varchar2(32767);
  4    l_cnt          number;
  5  begin
  6    -- Open file.
  7    l_file := utl_file.fopen('EXT_DIR', 'test2.txt', 'R', 32767);
  8
  9    loop
 10      utl_file.get_line(l_file, l_text, 32767);
 11
 12      -- L_TEXT contains the whole row; split it (by commas) into 3 values
 13      -- and insert them into the TEST2 table
 14      insert into test2 (id, fname, lname)
 15        values (regexp_substr(l_text, '[^,]+', 1, 1),
 16                regexp_substr(l_text, '[^,]+', 1, 2),
 17                regexp_substr(l_text, '[^,]+', 1, 3)
 18               );
 19    end loop;
 20
 21    utl_file.fclose(l_file);
 22  exception
 23    when no_data_found then
 24      null;
 25  end;
 26  /

PL/SQL procedure successfully completed.

The result:

SQL> select * from test2;

        ID FNAME                LNAME
---------- -------------------- --------------------
       100 Steven               King
       101 Neena                Kochha
       102 Lex                  De Haan
       103 Alexander
       104 Bruce                Ernst

SQL>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...