Reading a File using UTL_FILE [message #41027] |
Tue, 19 November 2002 09:32 |
Das
Messages: 92 Registered: November 2002
|
Member |
|
|
Hello All,
I am trying to read a file using the UTL_FILE package and then write its contents to a table in my database. can someone give me leads on how to do this?
my code:
in_file = utl_file.fopen("c:Temp.txt", "r", 4750);
Loop
utl_file.get_line(in_file, muBuffer);
?????
I am not sure how to break the line (which is a delimited file) and build an insert query out of it.
Thanks for any help.
Das
|
|
|
Re: Reading a File using UTL_FILE [message #41028 is a reply to message #41027] |
Tue, 19 November 2002 10:47 |
F. Tollenaar
Messages: 64 Registered: November 2002
|
Member |
|
|
If the file is delimited, you could (better) use sql*loader.
You should use instr to locate the position of the delimiters and substr to take pieces out of muBuffer:
SQL> get test_file
1 create or replace procedure test_file
2 as
3 l_file utl_file.file_type;
4 l_buffer varchar2(2000);
5 l_textbit varchar2(2000);
6 l_old_delimiter number;
7 l_new_delimiter number;
8 l_eol boolean;
9 begin
10 l_old_delimiter := 1;
11 l_new_delimiter := 0;
12 l_file := utl_file.fopen('z:MyWork', 'test.txt', 'r');
13 begin
14 --
15 -- Loop through all lines in file
16 --
17 loop
18 --
19 -- Reset positions
20 --
21 l_old_delimiter := 1;
22 l_new_delimiter := 0;
23 --
24 -- Read next line
25 --
26 utl_file.get_line(l_file, l_buffer);
27 --
28 -- For clarity, print out complete line
29 --
30 dbms_output.put_line(l_buffer);
31 l_eol := false;
32 while not l_eol
33 loop
34 --
35 -- Determine position of next delimiter
36 --
37 l_new_delimiter := instr(l_buffer, ',', l_old_delimiter);
38 if l_new_delimiter = 0
39 then
40 --
41 -- Stop loop; no more delimiters found
42 --
43 l_eol := true;
44 --
45 -- Last field must still be displayed
46 --
47 l_textbit := substr(l_buffer, l_old_delimiter);
48 dbms_output.put_line(l_textbit);
49 else
50 --
51 -- Field is text starting at old_delimiter with length (new - old delimiter)
52 --
53 l_textbit := substr(l_buffer, l_old_delimiter, instr(l_buffer, ',', l_new_delimiter) - l_old_delimiter);
54 dbms_output.put_line(l_textbit);
55 l_old_delimiter := l_new_delimiter + 1;
56 end if;
57 end loop;
58 end loop;
59 exception
60 when no_data_found
61 then
62 --
63 -- Close file
64 --
65 utl_file.fclose(l_file);
66 end;
67* end;
SQL> /
Procedure created.
SQL> set serveroutput on size 1000000
SQL> exec test_file
This,is,my,first,line
This
is
my
first
line
And,this,is,my,second,line
And
this
is
my
second
line
PL/SQL procedure successfully completed.
hth
Frank
|
|
|
|