如何通过过程以CSV格式导出输出

时间:2015-02-02 11:39:56

标签: oracle plsql

如何通过程序以CSV格式导出输出。我的输出存储在v_output变量

请在下面查询

   Declare
    view_name     VARCHAR2(200);
    v_str          VARCHAR2 (1000);
    v_output     VARCHAR2(4000);
    CURSOR tbl IS
         SELECT view_name 
         FROM all_views
         WHERE OWNER = SYS_CONTEXT( 'USERENV', 'CURRENT_SCHEMA')
         ORDER BY 1 ;
    BEGIN
    OPEN tbl ;
         LOOP
         FETCH tbl INTO view_name;
         EXIT WHEN tbl%NOTFOUND;
              v_str := 'Select '''|| view_name ||','' || count (*) from ' || view_name ;
              EXECUTE IMMEDIATE v_str INTO v_output;

              DBMS_OUTPUT.PUT_LINE(v_output);
         END LOOP;
    CLOSE tbl;
    END;

**

当前输出:

V_DSP_BUSINESS_DATE,7
V_DSP_DEPARTMENT,0
V_DSP_EMPLOYEE_DEACTIVATED,515
V_DSP_EMPLOYEE_GED,0
V_DSP_EMP_DEPARTMENT,0

我想以CSV格式导出此输出。

1 个答案:

答案 0 :(得分:1)

您可以使用UTL_FILE包写入平面文件,此文件将在DataBase Server上生成。

使用UTL_FILE的先决条件:

一个。创建指向数据库上物理位置的目录对象。 湾确保您使用的用户/架构具有对此位置的读/写访问权限 C。确保在数据库上安装了UTL_FILE(以SYS身份运行utl_file)并将UTL_FILE上的execute授予您正在使用的帐户。

UTL_FILE的伪代码:

DECLARE
  view_name VARCHAR2 (200);
  v_str     VARCHAR2 (1000);
  v_output  VARCHAR2 (4000);
  CURSOR tbl IS
    SELECT   view_name
    FROM     all_views
    WHERE    owner = Sys_context ('USERENV', 'CURRENT_SCHEMA')
    ORDER BY 1;

l_filehandle utl_file.file_type%TYPE; --Create a Variable with  Filetype record
BEGIN
  l_filehandle := utl_file.fopen(<directory_object>, <filename>, 'W'); --Call to open the file for Write Operation
  OPEN tbl;
  LOOP
    FETCH tbl
    INTO  view_name;

    EXIT
  WHEN tbl%NOTFOUND;
    v_str := 'Select '
    || view_name
    || ',  count (*) from '
    ||view_name;
    EXECUTE IMMEDIATE v_str INTO v_output;
    utl_file.Put_line(l_filehandle,v_output); --Actual Writing of line infile
  END LOOP;
  CLOSE tbl;
  utl_file.Fclose(l_filehandle);
END;

希望这有帮助