简体   繁体   中英

read delimited file from pl sql procedure

I'm new to pl sql and trying to read a file(column wise),where file(abc.txt) has data delimited by pipe "|" like as below:

 first test|add|123
 second test|mod|654

So my requirement is like

  • How can we read above file in a pl sql procedure.

working sample code will be very helpful.

and below code i used for reading a file:

set serveroutput on;

DECLARE 
    V1 VARCHAR2(200);
    F1 UTL_FILE.FILE_TYPE;
    V1 VARCHAR2(200);
    F1 UTL_FILE.FILE_TYPE; 
BEGIN 
    F1 := UTL_FILE.FOPEN('USER_DIR','abc.txt','R');

    LOOP
        BEGIN
            UTL_FILE.GET_LINE(F1,V1);
            dbms_output.put_line(V1);
        EXCEPTION
            WHEN no_data_found THEN EXIT;
        END;
    END LOOP;

    IF UTL_FILE.IS_OPEN(F1) THEN
        dbms_output.put_line('File is Open');
    end if;
    UTL_FILE.FCLOSE(F1);
 END;
/

Solution 1: sqlloader

  1. create a table for incoming data

  2. define your "loading rules":

     Use LOAD DATA infile '/yourappli/utl_file/abc.txt' REPLACE INTO TABLE LOAN_BALANCE_MASTER_INT fields terminated by '|' optionally enclosed by '"' ( Col_1, Col_2, Col_3 ) 

Solution 2: Turn each of your delimited string into a collection

Here is how you can loop trough your delimited string V1 in your code, with the cto_table function declared from the documentation link :

DECLARE 
  V1 VARCHAR2(200);
  F1 UTL_FILE.FILE_TYPE;
BEGIN 
  F1 := UTL_FILE.FOPEN('USER_DIR','abc.txt','R');
  Loop
  BEGIN
    UTL_FILE.GET_LINE(F1,V1);
      for x in ( 
        select column_value a from  table(cto_table('|', V1) )
      ) loop
        dbms_output.put_line(x.a);
      end loop;
  EXCEPTION WHEN No_Data_Found 
   THEN EXIT; 
  END;
  end loop;
  IF UTL_FILE.IS_OPEN(F1) THEN
    dbms_output.put_line('File is Open');
  end if;
  UTL_FILE.FCLOSE(F1);
END;
/

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