जानें कि UTL_FILE का उपयोग कैसे करें Oracle PL/SQL में तालिका से CSV फ़ाइल में डेटा निर्यात करने के लिए पैकेज।
Oracle में, पैकेज UTL_FILE टेक्स्ट फ़ाइल लिखने के लिए कई प्रक्रियाएं और कार्य शामिल हैं। फ़ाइल लिखने के लिए सिंटैक्स विवरण और आवश्यक चरण नीचे दिए गए हैं:
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); मूल उदाहरण
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;
जैसा कि मैंने उपरोक्त उदाहरण में उल्लेख किया है, निर्देशिका वस्तु MY_DIR मौजूद होना चाहिए। Oracle में निर्देशिका वस्तु सर्वर पर भौतिक निर्देशिका का एक संदर्भ है। Oracle में डायरेक्टरी ऑब्जेक्ट बनाने का एक उदाहरण निम्नलिखित है:
-- Windows example CREATE OR REPLACE DIRECTORY CSVDIR AS 'd:\oracle\csvfiles'; -- Linux example CREATE OR REPLACE DIRECTORY CSVDIR AS '/usr1/oracle/csvfiles';
Oracle में डायरेक्टरी ऑब्जेक्ट के बारे में अधिक जानने के लिए, इस लिंक को देखें।
Oracle उदाहरण में तालिका से CSV में डेटा निर्यात करें
निम्नलिखित Oracle में संग्रहीत कार्यविधि का एक उदाहरण है, जो डेटा को EMP तालिका से 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; अब आपकी संग्रहित प्रक्रिया बन गई है, डेटा निर्यात करने के लिए इसे निष्पादित करें:
Begin
exp_emp_data;
End; संबंधित ट्यूटोरियल:
- उपयोगिता:तालिका से डेटा निर्यात करने के लिए PL/SQL प्रक्रिया उत्पन्न करें