oracle数据库的表数据导出为csv文件

 今天有朋友的同学问起我怎么把oracle数据库的表数据导出为csv文件?当然用TOAD查询数据,并选择save as,并选择other delim char为“,”然后粘出数据到.dat即可.可是用pl/sql怎么实现?我也没做过。所以就google了一下。找到办法,如下:

1.先创建如下function,用以保存表数据为csv文件:
create or replace function  dump_csv( p_query     in varchar2,
                                      p_separator in varchar2
                                                    default ',',
                                      p_dir       in varchar2 ,
                                      p_filename  in varchar2 )
return number
AUTHID CURRENT_USER
is
    l_output        utl_file.file_type;
    l_theCursor     integer default dbms_sql.open_cursor;
    l_columnValue   varchar2(2000);
    l_status        integer;
    l_colCnt        number default 0;
    l_separator     varchar2(10) default '';
    l_cnt           number default 0;
begin
    l_output := utl_file.fopen( p_dir, p_filename, 'w' );

    dbms_sql.parse(  l_theCursor,  p_query, dbms_sql.native );

    for i in 1 .. 255 loop
        begin
            dbms_sql.define_column( l_theCursor, i,
                                    l_columnValue, 2000 );
            l_colCnt := i;
        exception
            when others then
                if ( sqlcode = -1007 ) then exit;
                else
                    raise;
                end if;
        end;
    end loop;

    dbms_sql.define_column( l_theCursor, 1, l_columnValue,
                            2000 );

    l_status := dbms_sql.execute(l_theCursor);

    loop
        exit when ( dbms_sql.fetch_rows(l_theCursor) <= 0 );
        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 );
            l_separator := p_separator;
        end loop;
        utl_file.new_line( l_output );
        l_cnt := l_cnt+1;
    end loop;
    dbms_sql.close_cursor(l_theCursor);

    utl_file.fclose( l_output );
    return l_cnt;
end dump_csv;

2.创建如下过程,调用前面的function即可。要注意的是,在传递给function  dump_csv的p_dir参数时,如果要想在c盘temp目录下创建文件,则传的参数应该为'C:/temp',同时应该注意的是必须要事先修改utl_file_dir的值,确保该值为C:/temp,以保证同过程传递的参数一致。

create or replace procedure test_dump_csv
as
    l_rows  number;
begin
    l_rows := dump_csv( 'select * from employee where rownum < 25',',', 'C:/temp', 'test.dat' );
end;

注:修改utl_file_dir需要重启数据库。

 

 

你可能感兴趣的:(数据库开发)