使用oracle存储过程实现查询结果导出至csv文件中。调用过程时,需要在oracle服务器上定义目录(已经存在的目录)。
create or replace PROCEDURE PX_SYS_IMP_CSV(V_sql IN VARCHAR2,V_DIR IN VARCHAR2,V_FILENAME IN VARCHAR2)
IS V_FILE UTL_FILE.FILE_TYPE; V_CURSOR INTEGER DEFAULT DBMS_sql.OPEN_CURSOR; V_COL_VALUE VARCHAR2(4000); V_COL_CNT NUMBER := 0; V_SEPARATOR CHAR(1); V_TAB_DESC DBMS_sql.DESC_TAB; V_STATUS INTEGER; V_MAX_LINESIZE NUMBER := 32000; BEGIN --OPEN FILE V_FILE := UTL_FILE.FOPEN(V_DIR,V_FILENAME,'W',V_MAX_LINESIZE); EXECUTE IMMEDIATE 'ALTER SESSION SET NLS_DATE_FORMAT=''YYYY-MM-DDHH24:MI:SS'''; --OPEN CURSOR DBMS_sql.PARSE( V_CURSOR,V_sql,DBMS_sql.NATIVE ); DBMS_sql.DESCRIBE_COLUMNS( V_CURSOR,V_COL_CNT,V_TAB_DESC ); --DUMP TABLE COLUMN NAME FOR I IN 1 .. V_COL_CNT LOOP UTL_FILE.PUT( V_FILE,V_SEPARATOR || '"' || V_TAB_DESC(I).COL_NAME ||'"' ); DBMS_sql.DEFINE_COLUMN( V_CURSOR,I,V_COL_VALUE,4000 ); V_SEPARATOR := ','; END LOOP; UTL_FILE.NEW_LINE( V_FILE ); --EXECUTE THE QUERY STATEMENT V_STATUS := DBMS_sql.EXECUTE(V_CURSOR); --DUMP TABLE COLUMN VALUE WHILE ( DBMS_sql.FETCH_ROWS(V_CURSOR) > 0 ) LOOP V_SEPARATOR := ''; FOR I IN 1 .. V_COL_CNT LOOP DBMS_sql.COLUMN_VALUE( V_CURSOR,V_COL_VALUE ); UTL_FILE.PUT( V_FILE,V_SEPARATOR || '"' || TRIM(BOTH ' ' FROM REPLACE(V_COL_VALUE,'"','""')) ||'"'); V_SEPARATOR := ','; END LOOP; UTL_FILE.NEW_LINE( V_FILE ); END LOOP; --CLOSE CURSOR DBMS_sql.CLOSE_CURSOR(V_CURSOR); --CLOSE FILE UTL_FILE.FCLOSE( V_FILE ); END PX_SYS_IMP_CSV ; 原文链接:https://www.f2er.com/oracle/213709.html