oracel中的表匯出csv檔案

2021-08-09 19:28:30 字數 2815 閱讀 2417

1.定義儲存過程

create or replace procedure sql_to_csv

( p_query in varchar2, -- plsql文

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);

end loop;

--close cursor

dbms_sql.close_cursor(l_thecursor);

--close file

utl_file.fclose(l_output);

exception

when others then

raise;

end;

2.指定匯出的儲存路徑

create or replace directory out_path as '目標路徑';
例如sql>create or replace directory out_path as 'd:\';
3.指定當前使用者下的表名

通過查詢語句查出需要執行的儲存過程的語句

select 'exec sql_to_csv(''select * from ' ||t.table_name ||''',''out_path''' || ',''ods_mds.' || t.table_name ||'.csv'');' from user_tables t where t.table_name='表名'
例如:

select 'exec sql_to_csv(''select * from ' ||t.table_name ||''',''out_path''' || ',''' || t.table_name ||'.csv'');' from user_tables t where t.table_name='position_20170912';
exec sql_to_csv('select * from position_20170912','out_path','position_20170912.csv');

4.執行對應的過程語句

sql> exec sql_to_csv('select * from position_20170912','out_path','position_20170912.csv');

pl/sql procedure successfully completed

SQLite表匯出csv檔案

最近常常用到這個將資料庫中的表匯出用excel檢視,記錄一下操作過程。2 然後win r開啟命令列 win10 進入要轉換的資料庫所在資料夾,執行sqlite命令。c users zktx cd c users zktx desktop temp c users zktx desktop temp ...

Hive表匯出成csv檔案

將表頭輸出 select from data table where some query conditions sed s t g hivefile.csv set hive.cli.print.header true將表頭輸出 sed s t g 將 t替換成 將shell裡列印的內容輸出到檔案...

Mysql 匯出表資料到 csv

select from users into outfile f develop mysql57 uploads users.csv character set utf8 fields terminated by optionally enclosed by escaped by lines ter...