Oracle批量导出表数据到CSV文件

您所在的位置:网站首页 oracle如何导出大量数据到文本文件中 Oracle批量导出表数据到CSV文件

Oracle批量导出表数据到CSV文件

2024-02-14 12:16| 来源: 网络整理| 查看: 265

需求:把oracle数据库中符合条件的n多表,导出成csv文本文件,并以表名.csv为文件名存放。

实现:通过存储过程中utl_file函数来实现。导出的csv文件放入提前创建好的directory中。使用方法:使用以下命令数据预执行的sql脚本

select 'exec sql_to_csv(''select * from ' ||t.table_name ||

''',''out_put_csv''' || ',''' || t.table_name ||'.csv'');'

from user_tables t

实例:exec sql_to_csv('select * from ip_role','backup/oracle/csv','ip_role.csv');

重点:当使用一下的存储过程执行的时候,报存在相关目录的时候 请在oracle 的启动文件的末尾中添加你要下载到的目录中

例如: utl_file_dir='/backup/oracle/cvs' 到 /oracle/projuct/11.2.0/dbhome_1/init.ora 文件中

脚本说明:sql_to_csv 存储过程名;out_put_csv数据库目录名称;ods_mds预定义的schema名称;

存储过程代码如下:

create or replace procedure chenqy.sql_to_csv( p_query in varchar2, -- plsql查询sql语句 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;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);--写入cvs行 end loop; --close cursor dbms_sql.close_cursor(l_thecursor); --close file utl_file.fclose(l_output);exception when others then raise;end;



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3