0

我是甲骨文的初学者。

我一直在尝试读取文本文件并将其数据插入 utl_file 但无法这样做,因为我不了解以下内容:

Comma1 := INSTR(f_line, ',' ,1 , 1);
Comma2 := INSTR(f_line, ',' ,1 , 2);
Comma3 := INSTR(f_line, ',' ,1 , 3);
Comma4 := INSTR(f_line, ',' ,1 , 4);
Comma5 := INSTR(f_line, ',' ,1 , 5);
f_empno := to_number(SUBSTR(f_line, 1, Comma1-1));
f_ename := SUBSTR(f_line, Comma1+1, Comma2-Comma1-1);
f_job := SUBSTR(f_line, comma2+1, Comma3-Comma2-1);
f_mgr := to_number(SUBSTR(f_line, comma3+1, Comma4-Comma3-1));
f_hiredate := to_date(SUBSTR(f_line, comma4+1, Comma5-Comma4-1),'dd-mon-yyyy');
f_sal := to_number(SUBSTR(f_line, comma5+1),'99999');
dbms_output.put_line(f_empno ||' '|| f_ename || ' ' || f_job || ' ' || f_mgr || ' ' || f_hiredate || ' ' || f_sal);
insert into emp12 VALUES (f_empno,f_ename,f_job,f_mgr,f_hiredate,f_sal);
4

1 回答 1

1

这是从文本文件读取数据的代码的一个很好的简单示例,它比您最初发布的内容简单得多 - http://nimishgarg.blogspot.co.il/2013/04/load-csv-file-在-oracle-using-plsql.html

以下是所附链接中的相关代码 - 运行所有这些命令,以便将文件 EMP_DEPT.CSV 从目录 e:\mycsv\ 读取到用户 scott 的表 emp_dept 中(更改每个参数以适合您的设计)

// 1. 首先,创建一个目录对象,以便 oracle 可以访问文件的位置

create or replace directory MYCSV as 'e:\mycsv\';

// 2. 授予用户从该目录读取文件的权限

grant read, write on directory MYCSV to scott;

// 3. 创建一个与文件中的行结构相同的表

CREATE TABLE EMP_DEPT
  (
  EMPNO NUMBER(4),
  ENAME VARCHAR2(10),
  SAL NUMBER(7,2),
  DNAME VARCHAR2(14)
  );

// 4. Run this procedure after making the following changes - 
// a. Change the variables to match the columns in your destination table
// b. Change the UTL.FILE.FOPEN command to match the directory and file name in your case.
// c. Change every REGEXP_SUBSTR(V_LINE, '[^,]+', 1, 1); to match the variable you want to assign.
// 5. Go for it.
 DECLARE
    F UTL_FILE.FILE_TYPE;
    V_LINE VARCHAR2 (1000);
    V_EMPNO NUMBER(4);
    V_ENAME VARCHAR2(10);
    V_SAL NUMBER(7,2);
    V_DNAME VARCHAR2(14);
  BEGIN
    F := UTL_FILE.FOPEN ('MYCSV', 'EMP_DEPT.CSV', 'R');
    IF UTL_FILE.IS_OPEN(F) THEN
      LOOP
        BEGIN
          UTL_FILE.GET_LINE(F, V_LINE, 1000);
          IF V_LINE IS NULL THEN
            EXIT;
          END IF;
          V_EMPNO := REGEXP_SUBSTR(V_LINE, '[^,]+', 1, 1);
          V_ENAME := REGEXP_SUBSTR(V_LINE, '[^,]+', 1, 2);
          V_SAL := REGEXP_SUBSTR(V_LINE, '[^,]+', 1, 3);
          V_DNAME := REGEXP_SUBSTR(V_LINE, '[^,]+', 1, 4);
          INSERT INTO EMP_DEPT VALUES(V_EMPNO, V_ENAME, V_SAL, V_DNAME);
          COMMIT;
        EXCEPTION
        WHEN NO_DATA_FOUND THEN
          EXIT;
        END;
      END LOOP;
    END IF;
    UTL_FILE.FCLOSE(F);
  END;
  /

祝你好运。

于 2015-10-12T20:08:40.597 回答