Search code examples
oracle-databasecsvplsqlexport

how to export data from around 300 tables in ORACLE DB to csv or txt files


Is there any possibility to export data from around 300 tables within single schema with millions of records to CSV or TXT using any PL/SQL procedure?

What do you propose, which is fastest way to do it? For the moment I do not need to import these exported files to any other schema...

I tried with Toad manually exporting table by table...


Solution

  • I managed to dynamically go through all tables and get column names and write to a file. I am struggling into part how to fetch data rows from tables dynamically when execute immediate query? how should I save data rows and than fetch it and write to files? Here is the code:

    DECLARE p_table        VARCHAR2 (100);
    l_file UTL_FILE.FILE_TYPE;
    l_string       VARCHAR2 (10000);
    query_string   VARCHAR2 (4000);
    BEGIN
    FOR tab IN (SELECT *
                 FROM dba_tables
                WHERE owner = 'XYZ' AND table_name LIKE 'XYZ%')
    LOOP
      p_table := tab.table_name;
    
      l_file :=
         UTL_FILE.FOPEN ('my_path',
                         tab.table_name || '.txt',
                         'w',
                         10000);
      l_string := NULL;
    
    
      FOR col_he IN (SELECT *
                       FROM dba_tab_columns
                      WHERE owner = 'DWHCO' AND table_name = p_table)
      LOOP
         CASE
            WHEN l_string IS NULL
            THEN
               l_string := col_he.column_name;
            ELSE
               l_string := l_string || ',' || col_he.column_name;
         END CASE;
      END LOOP;
    
      UTL_FILE.PUT_LINE (l_file, l_string);            --Printng table columns
    
      query_string := 'select ' || l_string || ' from DWHCO.' || p_table      
      --Execute immediate query_string into ??????????;
            --??????
      UTL_FILE.FCLOSE (l_file);  END LOOP;END;