简体   繁体   中英

export multiple table data into csv file in oracle

I have five different tables as a,b,c,d,e with different number of columns. I want to export the data into the csv file from all this five table. In common i have seq_no in all five tables.seq_no wise file should get generated.

And

table a data should be row 1

table b data should be row 2

table c data should be row 3

table d data should be row 4

table d data should be row n    

table e data should be row n+1

In table a,b,c,e only 1 record will be there for 1 seq_no

In table d multiple records will be there for 1 seq_no.

EG

Seq_no = 1 then only that data should get exported to the csv.

seq_no = 2 then only that data should get exported to the csv

..... etc

if count(seq_no) = 10 then 10 files should get exported.

how can i achive this through plsql function/procedure?

create associative array of file handles indexed by seq_no

type ta_file is table of utl_file.file_type index by number(5);
va_file ta_file;

iterate rows and put their csv lines into files (you have to replace '{csv string from x}' by concatenation)

for r in (
  select * from (
    select seq_no, '{csv string from a}' s, 'a' t from a
    union all
    select seq_no, '{csv string from b}' s, 'b' t from b
    union all
    select seq_no, '{csv string from c}' s, 'c' t from c
    union all
    select seq_no, '{csv string from d}' s, 'd' t from d
    union all
    select seq_no, '{csv string from e}' s, 'e' t from e
  ) order by t, seq_no
) loop
  if not va_file.exists(r.seq_no) then
    -- for new seq_no open new seq_no file
    va_file(r.seq_no) := fopen(filepath, filename || r.seq_no || fileext, 'W');
  end if;
  -- write csv to seq_no file
  utl_file.put_line(va_file(r.seq_no), r.s);
end loop;

close all files (iterating through va_file)

for i in va_file.first .. va_file.last loop
  utl_file.fflush(va_file(i));
  utl_file.fclose(va_file(i));
end loop;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM