I want to export one table to each csv file and name the csv file with timestamp. For example, if I have a table t1
, after export, a csv file name t1.YYYYMMDDHHMISS.csv is generated. Here is my code:
create or replace procedure
T_to_CSV(Tname varchar2,Directory varchar2)
BEGIN
set colsep , -- separate columns with a comma
set pagesize 0 -- No header rows
set trimspool on -- remove trailing blanks
set headsep off -- this may or may not be useful...depends on your
spool timestamp.csv --don't know how to write in directory
select *
from Tname
end
Here are my questions:
(1) I don't know how to output the csv file into the requried directory, how to fix the spool code please?
Should I use spool D:\\path\\filename.csv
please?
(2) In the spool line, how to change the name of the csv file using the timestamp now() please?
There are a few steps:
GRANT read,write on DIRECTORY my_dir to the_user;
I have used this and it works really nicely.
Usage
data_dump ( 'Select emp_name from emp',
CURRENT_TIMESTAMP||'filename.csv',
my_dir);
(vastly simplified sample!)
After creating the directory verify your work by running this:
Spool file will be created in the same directory as the .sql file
SET COLSEP , SET HEADSEP OFF -- character used when defining a two-line column heading SET TRIMSPOOL ON -- trim trailing spaces from each line SET LINESIZE 32000 -- number of characters to be printed on one line SET WRAP OFF -- truncates lines longer than LINESIZE SET NUMWIDTH 5 -- default width while displaying numbers COLUMN tm new_value iso8601 noprint SELECT to_char(sysdate, 'YYYY-MM-DD') tm FROM dual; spool output_file_&iso8601..csv -- Append new data to spool file: "spool output_file_&iso8601..csv append" SELECT * FROM table_name spool OFF
Thanks kevin for sharing the procedure and it was very useful for me. I have customized the code:
I am also sharing the customized code which might help others. Customized code can be downloaded here .
FOR i IN t_describe.FIRST .. t_describe.LAST LOOP IF i <> t_describe.LAST THEN put('UTL_FILE.PUT(v_fh,'''||t_describe(i).col_name||'''||'''||v_delimiter||''');'); ELSE put(' UTL_FILE.PUT(v_fh,'''||t_describe(i).col_name||''');'); END IF; END LOOP; put(' UTL_FILE.NEW_LINE(v_fh);');
Customized Code for delimiter
IF i <> t_describe.LAST THEN
put(' UTL_FILE.PUT(v_fh,"'||t_describe(i).col_name||'"(i) ||'''||v_delimiter||''');');
ELSE
put(' UTL_FILE.PUT(v_fh,"'||t_describe(i).col_name||'"(i));');
END IF;
And the correct way to call the procedure is to bind the variable with values
data_dump(query_in => 'Select 1 from dual',file_in => 'file.csv',directory_in => 'MY_DIR', delimiter_in => '|' );
Thanks
Naveen
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.