Tìm hiểu cách sử dụng UTL_FILE gói để xuất dữ liệu từ bảng sang tệp CSV trong Oracle PL / SQL.
Trong Oracle, gói UTL_FILE chứa nhiều thủ tục và chức năng để viết một tệp văn bản. Dưới đây là chi tiết cú pháp và các bước cần thiết để viết một tệp:
Cú pháp và các bước để viết tệp bằng UTL_FILE
-- Declare a variable to store file type
n_file UTL_FILE.FILE_TYPE;
-- Open the file in Begin section, it will open the file and return the file handle into the variable n_file
n_file := UTL_FILE.FOPEN('DIR_OBJ', 'YourCSVFileName.csv', 'w', 4000);
-- Write a single or multiple lines
UTL_FILE.PUT_LINE(n_file, 'abc, xyz, xxx');
-- Close the file
UTL_FILE.FCLOSE(n_file); Ví dụ cơ bản
Declare
n_file Utl_File.File_Type;
Begin
-- The directory object MY_DIR must be exist or create a new one
n_file := Utl_File.Fopen('MY_DIR', 'myfile.csv', 'w', '4000');
Utl_File.Put_Line(n_file, 'First line.');
Utl_File.Put_Line(n_file, 'Second line.');
Utl_File.Put_Line(n_file, 'Third line.');
Utl_File.Fclose(n_file);
End;
Như tôi đã đề cập trong ví dụ trên, đối tượng thư mục MY_DIR phải tồn tại. Đối tượng thư mục trong Oracle là một tham chiếu đến thư mục vật lý trên máy chủ. Sau đây là một ví dụ về cách tạo một đối tượng thư mục trong Oracle:
-- Windows example CREATE OR REPLACE DIRECTORY CSVDIR AS 'd:\oracle\csvfiles'; -- Linux example CREATE OR REPLACE DIRECTORY CSVDIR AS '/usr1/oracle/csvfiles';
Để tìm hiểu thêm về đối tượng thư mục trong Oracle, hãy xem liên kết này.
Xuất dữ liệu từ một bảng sang CSV trong ví dụ Oracle
Sau đây là ví dụ về thủ tục được lưu trữ trong Oracle, thủ tục này sẽ xuất dữ liệu từ bảng EMP sang tệp CSV:
Create Or Replace Procedure exp_emp_data Is
n_file utl_file.file_type;
v_string Varchar2(4000);
-- get the data using cursor
Cursor c_emp Is
Select
empno,
ename,
deptno,
sal,
comm
From
emp;
Begin
n_file := utl_file.fopen('CSVDIR', 'empdata.csv', 'w', 4000);
-- if you do not want heading then remove below two lines
v_string := 'Emp Code, Emp Name, Dept, Salary, Commission';
utl_file.put_line(n_file, v_string);
-- open the cursor and concatenate fields using comma
For cur In c_emp Loop
v_string := cur.empno
|| ','
|| cur.ename
|| ','
|| cur.deptno
|| ','
|| cur.sal
|| ','
|| cur.comm;
-- write each row
utl_file.put_line(n_file, v_string);
End Loop;
-- close the file
utl_file.fclose(n_file);
Exception
When Others Then
-- on error, close the file if open
If utl_file.is_open(n_file) Then
utl_file.fclose(n_file);
End If;
End; Bây giờ thủ tục lưu trữ của bạn đã được tạo, hãy thực thi nó để xuất dữ liệu:
Begin
exp_emp_data;
End; Hướng dẫn liên quan:
- Tiện ích:Tạo quy trình PL / SQL để xuất dữ liệu từ bảng