oracle 后台把sql导出成csv文件

CREATE OR REPLACE PROCEDURE EXP_SQL_TO_CSV(P_QUERY    IN VARCHAR2, -- PLSQL文
                                           P_DIR      IN VARCHAR2, -- 导出的文件放置目录
                                           P_FILENAME IN VARCHAR2 -- CSV名
                                           ) IS
                                           
                                           
/*


--一、创建路径
CREATE OR REPLACE DIRECTORY OUT_PATH AS '/home/oracle';

--二、查看路径是否存在
SELECT  * FROM DBA_DIRECTORIES A WHERE A.OWNER = 'SYS' AND A.DIRECTORY_NAME = 'OUT_PATH';


--三、调用方法
CALL EXP_SQL_TO_CSV('
 SELECT A.PARTY_ID,  -- 客户号
       A.PARTY_CHN_NAME,-- 客户名称
       B.GENDER, -- 性别
       A.COUNTRY_CD, -- 国籍
       A.CARD_TYPE, -- 证件类型
       A.CARD_NO, -- 证件号
       B.CARD_END_DT, -- 证件到期日期
       B.OCCUPATION,  -- 职业
       B.PROFESSION, -- 职业编码
       A.TEL_NO, --  固定电话
       A.CELL_NO, --   移动电话
       A.ADDR1, -- 地址1
       A.ADDR2, -- 地址2
       A.ORGANKEY

  FROM T47_PARTY A, T47_INDIVIDUAL B
 WHERE A.PARTY_ID = B.PARTY_ID
       AND A.PARTY_CLASS_CD = ''I''
       AND (B.OCCUPATION IS NULL OR LENGTH(A.ADDR1)<9 OR LENGTH(A.ADDR2)<9)
       AND ROWNUM<1000
 ', -- 查询语句
       'OUT_PATH',  -- 系统变量
       'PARTY_CUST.csv' -- 文件名称
       );


*/
                                           
  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;
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''';
  --OPEN CURSOR
  DBMS_SQL.PARSE(L_THECURSOR, P_QUERY, 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 EXP_SQL_TO_CSV;

  

posted @ 2022-03-28 10:58  洺剑残虹  阅读(348)  评论(0编辑  收藏  举报