我是oracle的初学者。
我一直在尝试读取文本文件并在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);
答案 0 :(得分:1)
这是一个很好的简单示例,用于从文本文件中读取数据的代码,它比您最初发布的内容简单得多 - http://nimishgarg.blogspot.co.il/2013/04/load-csv-file-in-oracle-using-plsql.html
以下是所附链接的相关代码 - 运行所有这些命令,以便从目录e:\ mycsv \读取文件EMP_DEPT.CSV到用户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;
/
祝你好运。