Oracle 使用UTL_FILE包批量导出CSV文件

导出步骤:

  1. 创建目录
create or replace directory dir as 'C:\Users\user\Desktop\dir'
  1. 给用户授权目录操作权限
grant read,write on dir to user;
  1. 导出存储过程
CREATE OR REPLACE PROCEDURE SQL_TO_CSV(P_QUERY IN VARCHAR2, -- PLSQL文
                                      PWHERE  IN VARCHAR2,
                                      P_DIR      IN VARCHAR2, -- 导出的文件放置目录
                                      P_FILENAME IN VARCHAR2 -- CSV名
                                      )

IS
 L_OUTPUT       UTL_FILE.FILE_TYPE;
 L_THECURSOR    INTEGER DEFAULT DBMS_SQL.OPEN_CURSOR;
 L_COLUMNVALUE  VARCHAR2(4000);
 L_STATUS       INTEGER;
 L_COLCNT       NUMBER := 0;
 L_SEPARATOR    VARCHAR2(1);
 L_DESCTBL      DBMS_SQL.DESC_TAB;
 P_MAX_LINESIZE NUMBER := 32000;
 l_sql          clob;
BEGIN

 --OPEN FILE
 L_OUTPUT := UTL_FILE.FOPEN(P_DIR, P_FILENAME, 'W', P_MAX_LINESIZE);
 --DEFINE DATE FORMAT
 EXECUTE IMMEDIATE 'ALTER SESSION SET NLS_DATE_FORMAT=''YYYY-MM-DD HH24:MI:SS''';

 l_sql := P_QUERY;
 if PWHERE is not null then
   l_sql := l_sql || ' where qxdm = ''' || PWHERE || '''';
 end if;
 --OPEN CURSOR
 DBMS_SQL.PARSE(L_THECURSOR, l_sql, DBMS_SQL.NATIVE);
 DBMS_SQL.DESCRIBE_COLUMNS(L_THECURSOR, L_COLCNT, L_DESCTBL);

 --DUMP TABLE COLUMN NAME
 FOR I IN 1 .. L_COLCNT LOOP
   UTL_FILE.PUT(L_OUTPUT,
                L_SEPARATOR || '"' || L_DESCTBL(I).COL_NAME || '"');
   DBMS_SQL.DEFINE_COLUMN(L_THECURSOR, I, L_COLUMNVALUE, 4000);
   L_SEPARATOR := '|';
 END LOOP;

 UTL_FILE.NEW_LINE(L_OUTPUT);
 --EXECUTE THE QUERY STATEMENT
 L_STATUS := DBMS_SQL.EXECUTE(L_THECURSOR);

 --DUMP TABLE COLUMN VALUE
 WHILE (DBMS_SQL.FETCH_ROWS(L_THECURSOR) > 0) LOOP
 
   L_SEPARATOR := '';
   FOR I IN 1 .. L_COLCNT LOOP
     DBMS_SQL.COLUMN_VALUE(L_THECURSOR, I, L_COLUMNVALUE);
     UTL_FILE.PUT(L_OUTPUT,
                  L_SEPARATOR || '"' ||
                  TRIM(BOTH ' ' FROM REPLACE(L_COLUMNVALUE, '"', '""')) || '"');
     L_SEPARATOR := '|';
   END LOOP;
 
   UTL_FILE.NEW_LINE(L_OUTPUT);
 END LOOP;

 --CLOSE CURSOR
 DBMS_SQL.CLOSE_CURSOR(L_THECURSOR);

 --CLOSE FILE
 UTL_FILE.FCLOSE(L_OUTPUT);
EXCEPTION
 WHEN OTHERS THEN
   RAISE;
END;

  1. 导出脚本

  /*
   select 'call sql_to_csv(''select * from ' || table_name ||
        ' t '',''DIR'',''' || table_name || '.CSV' ||
        ''');'
   from user_tables
  where num_rows > 0;

5.调用

sql_to_csv('select * from table_name t ','DIR','table_name.CSV');

坑:导出中目录名称DIR需要大写

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值