便捷输出sql查询结果为TXT/CSV文件
2017-04-16 17:41
387 查看
1. 创建存储过程sql_to_csv
create or replace procedure sql_to_csv(p_query in varchar2, --sql query statementp_dir in varchar2, --the directory of file
p_filename in varchar2, --the export filename
p_max_linesize in number default 32000 --max linesize,must less than 32787
) 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;
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 || '"');
*/ --注释1
dbms_sql.define_column(l_theCursor, i, l_columnValue, 4000);
l_separator := ',';
end loop;
-- utl_file.new_line(l_output); --注释1和本行都注释表示输出到文件不输出表列名
--execute the query statement
l_status := dbms_sql.execute(l_theCursor);
-- generate file
--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 || l_columnValue); --generate txt file
--utl_file.put( l_output, l_separator || '"' ||trim(both ' ' from replace(l_columnValue,'"','""')) || '"'); -- generate csv file
l_separator := ','; --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 sql_to_csv;
/
2. 创建导出文件的目录
SQL> create directory test as '/home/oracle';Directory created.
3. 调用存储过程,导出txt或csv文件
SQL> exec sql_to_csv('select * from test','TEST','test.txt'); # 参数:sql语句+directory name+导出文件名(sql语句中如果有引号要使用转义,另外directorr name要大写)PL/SQL procedure successfully completed.
相关文章推荐
- 将sqlplus查询结果输出为文件
- SQLSERVER,不使用BCP,把查询结果输出为txt文本文件的存储过程
- PostgresSQL将查询结果写入CSV文件
- 怎样把sqlplus执行的查询结果重定向输出到一个文件里面去?
- 把sql查询结果输出到文件
- SQL查询CSV文件方法
- Sql 查询技巧 优先输出某结果
- SQL C# nvarchar类型转换为int类型 多表查询的问题,查询结果到新表,TXT数据读取到控件和数据库,生成在控件中的数据如何存到TXT文件中
- MATLAB中,矩阵元素输出到TXT/csv文件,干掉讨厌的科学计数法。
- 写一个程序,能够动态生成多条插入语句如:insert into MyStudents values(“人名1”,年龄,‘男’,分数1,分数2)。将生成的插入语句输出到记事本文件 SQLStr.txt中
- 将根据字符查询转换后输出结果,规则为:’A’转换为’男’,’B’转换为’女’,其他字符转换为’未知’,请用一个SQL语句写出。
- 动态生成多条插入语句如:insert into MyStudents values(“人名1”,年龄,‘男’,分数1,分数2)。将生成的插入语句输出到记事本文件 SQLStr.txt中
- [access查询]将access表导出为TXT文件及将TXT文件导入access表的几个SQL语句
- Postgresql 将SQL 查询结果写入文件
- 把一个sql查询结果,输出到浏览器或者excel下载
- SQL查询结果导出XML文件简单的方法
- 将ping结果输出到txt文件
- 如何将MySQL数据库sql查询结果保存到excel文件中
- PL/SQL将txt(csv)文件导入数据到oracle
- spool sqlplus输出结果到文件