Technorati 标签: oracle

--以SYS用户创建目录dir_dump,文件就保存在这个目录下
SQL> create directory dir_dump as '/data/cmssdb';
Directory created.
--授权对应的操作帐号读和写的权限,这里是operator
SQL> grant read on directory dir_dump to operator;
Grant succeeded.
SQL> grant write on directory dir_dump to operator;
Grant succeeded.
--以operator用户登陆
SQL> connect operator/operation
Error accessing PRODUCT_USER_PROFILE
Warning:  Product user profile information not loaded!
You may need to run PUPBLD.SQL as SYSTEM
Connected.
--创建表BIBI,并加入测试数据
SQL> create table bibi(row_id int,row_name varchar2(10));
Table created.
SQL> insert into bibi values(1,'luochun');
1 row created.
SQL> insert into bibi values(2,'maihy');
1 row created.
SQL> commit;
Commit complete.
/*--该过程负责备份数据到DIR_DUMP目录,名称为bibi.csv
DECLARE lv_file_handle UTL_FILE.file_type;
BEGIN
lv_file_handle := UTL_FILE.FOPEN('DIR_DUMP','bibi.csv','a');
FOR x IN (SELECT ROW_ID,ROW_NAME FROM BIBI) LOOP
  UTL_FILE.PUT_LINE(lv_file_handle,x.ROW_ID || ',' || NVL(x.ROW_NAME,''));
END LOOP;
UTL_FILE.FCLOSE(lv_file_handle);
EXCEPTION WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SUBSTR(SQLERRM,1,200));
END;
/
*/
--过程完成,转到DIR_DUMP目录查看生成的文件,数据已经产生
[oracle@qaserver oracle]$ cd /data/cmssdb
[oracle@qaserver cmssdb]$ cat bibi.csv
1,luochun
2,maihy
/*
--现在删除BIBI数据,准备将备份的导入
SQL> truncate table bibi;
Table truncated.
/*--这个过程负责读取文件,并导入数据
DECLARE lv_file_handle UTL_FILE.file_type;
lv_row_text VARCHAR2(2000);
lv_row_id PLS_INTEGER;
lv_row_name VARCHAR2(50);
BEGIN
lv_file_handle := UTL_FILE.FOPEN('DIR_DUMP','bibi.csv','r');
LOOP
  BEGIN
   UTL_FILE.GET_LINE(lv_file_handle,lv_row_text);
   lv_row_id := SUBSTR(lv_row_text,1,INSTR(lv_row_text,',',1,1) - 1);
   lv_row_name := SUBSTR(lv_row_text,INSTR(lv_row_text,',',1,1) + 1);
   INSERT INTO BIBI VALUES(lv_row_id,lv_row_name);
  EXCEPTION
   WHEN NO_DATA_FOUND THEN
    EXIT;
  END;
END LOOP;
COMMIT;
UTL_FILE.FCLOSE(lv_file_handle);
EXCEPTION WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SUBSTR(SQLERRM,1,200));
END;
/
*/
--数据已经产生
SQL> SQL> SELECT * FROM BIBI;
    ROW_ID ROW_NAME
---------- --------------------
         1 luochun
         2 maihy
SQL>