Utl_file + query

Hi guys.
I am really newbie in procedures.
I am trying to implement a procedure, using utl_dir :
create or replace procedure UTL_FILE_EXAMPLE is
FILE_HANDLE utl_file.file_type;
COL1 varchar2;
RETRIEVED_BUFFER varchar2(100);
DIR_NAME varchar2(40) := 'UTF_DIR';
FILE_NAME varchar2(40) := 'myfile.txt';
begin
FILE_HANDLE := utl_file.fopen(DIR_NAME,FILE_NAME,'W');
utl_file.put_line(FILE_HANDLE, 'auditing and testing');
cursor CUR_EMISOR is
SELECT username,
extended_timestamp,
owner,
obj_name,
action_name,
sql_text
FROM dba_audit_trail
ORDER BY timestamp;
utl_file.putf (
FILE_HANDLE, CUR_EMISOR
utl_file.fclose(FILE_HANDLE);
file_handle := utl_file.fopen(DIR_NAME,FILE_NAME,'R');
utl_file.get_line (FILE_HANDLE, RETRIEVED_BUFFER);
dbms_output.put_line(RETRIEVED_BUFFER);
utl_file.fclose(FILE_HANDLE);
end;
I am trying to get the results of the query and put it on a .txt file.
Could anybody gimme a hint ?
Thanks!

Hello guys.
I've Tried to follow user11181920´s hint
create or replace procedure UTL_FILE_EXAMPLE is
FILE_HANDLE utl_file.file_type;
COL1 varchar2(10);
RETRIEVED_BUFFER varchar2(100);
DIR_NAME varchar2(40) := 'UTF_DIR';
FILE_NAME varchar2(40) := 'myfile.txt';
begin
FILE_HANDLE := utl_file.fopen(DIR_NAME,FILE_NAME,'W');
FOR C in (
SELECT username,extended_timestamp,owner,obj_name,action_name,sql_text FROM dba_audit_trail
ORDER BY timestamp)
LOOP
utl_file.put_line(FILE_HANDLE,C.username||','||C.extended_timestamp||','||C.owner);
END LOOP;
utl_file.fclose(FILE_HANDLE);
end;
I had some errors:
At line 11: PL/SQL: ORA-00942: table or view does not exist
At Line 11: PL/SQL: sql statement ignored
At line 15: PLS-00364: loop index variable 'C' use in invalid
At line 15: PL/SQL: sql statement ignored
Ps.: Normally i can do this select, i have access on the table, the table has this columns mentioned on the query.
Thanks.

Similar Messages

  • Oracle 11g : UTL_FILE query

    Hi,
    I am having 2 server. One server has oracle database while on another one is application server where all the data files and application specific shell scripts are kept. We are connecting to database via the application server.
    I am using Oracle 11g:
    Oracle Database 11g Enterprise Edition Release 11.1.0.6.0 - 64bit Production
    PL/SQL Release 11.1.0.6.0 - Production
    CORE 11.1.0.6.0 Production
    TNS for HPUX: Version 11.1.0.6.0 - Production
    NLSRTL Version 11.1.0.6.0 - Production
    I know that using UTL_FILE in PL/SQL procedure we can create file on the server (where oracle is installed).
    My requirement is generated some report which will involve writing to more than 2 files simultaneously. I know I can easily do this in PL/SQL procedure.
    But my issue is that due to space issue I cannot generate the files on database server and need to generate the same on the application one (client side)
    Queries:
    1] Is it also possible to create file on client machince instead of server in my case the application server via PL/SQL because I read that in Oracle 11g
    UTL_FILE provides file access both on the client side and on the server side.
    2] If yes any idea, how is this possible?
    3] If not, is there any way by which I can write to 2 or more file simultaneously on the client using oralce. I know SQL*Plus can spool file on client. But it is only one file at a time.
    Rgds,
    Amol

    Looking at the 11g documentation you are probably referring to:
    http://download.oracle.com/docs/cd/B28359_01/appdev.111/b28419/u_file.htm#BABDEJDH
    where it says...
    >
    UTL_FILE provides file access both on the client side and on the server side. When run on the server, UTL_FILE provides access to all operating system files that are accessible from the server. On the client side, as in the case for Forms applications, UTL_FILE provides access to operating system files that are accessible from the client.
    >
    This is referring to client installed forms applications where it provides a local UTL_FILE functionality that accesses the local file system. It doesn't mean that UTL_FILE within PL/SQL that is running on the database server can access the client machine's file system as this would also be a breach of network security.

  • Utl_file query help.

    hi friends.,
    i have oracle client client installed in my machine..
    i have used utl file package to write in the text file..but m facing below error.
    DECLARE
    fid UTL_FILE.FILE_TYPE;
    f VARCHAR(200);
    v VARCHAR2(32767);
    BEGIN
    f := 'D:\';-------------------------------------------------------------(My local D drive)
    fid := UTL_FILE.FOPEN (f, 'temp.txt', 'W');
    UTL_FILE.PUT_LINE (fid, v);
    UTL_FILE.FCLOSE (fid);
    DBMS_OUTPUT.PUT_LINE ('Successful write to ' || f);
    END;
    ORA-29283: invalid file operation
    ORA-06512: at "SYS.UTL_FILE", line 449
    ORA-29283: invalid file operation
    ORA-06512: at line 6

    Rajnish Chauhan wrote:
    hi friends.,
    i have oracle client client installed in my machine..
    i have used utl file package to write in the text file..but m facing below error.
    DECLARE
    fid UTL_FILE.FILE_TYPE;
    f VARCHAR(200);
    v VARCHAR2(32767);
    BEGIN
    f := 'D:\';-------------------------------------------------------------(My local D drive)
    fid := UTL_FILE.FOPEN (f, 'temp.txt', 'W');
    UTL_FILE.PUT_LINE (fid, v);
    UTL_FILE.FCLOSE (fid);
    DBMS_OUTPUT.PUT_LINE ('Successful write to ' || f);
    END;
    ORA-29283: invalid file operation
    ORA-06512: at "SYS.UTL_FILE", line 449
    ORA-29283: invalid file operation
    ORA-06512: at line 6
    UTL_FILE can access only Server Directory. You need to create a directory object and use it. You can read in detail from the document.
    What is your DB Version?

  • Query Regarding UTL_FILE.fopen() -

    Guys hope you all doin well-
    I am using Oracle 9i release 2 -
    I am having problem while i am trying to open a file using the UTL_FILE builtin package -
    I created the directory as well where the file is located, that i want to access
    While i am executing the utl_file.fopen function returns record
    location in varchar2 ,
    filename in varchar2 ,
    open_mode in varchar2 ,
    max_linesize in binary_integer default
    returns the following error ORA-29283: invalid file operation
    The description of the error i found is:
    ORA-29283: invalid file operation
    Cause: An attempt was made to read from a file or directory that does not exist, or file or directory access was denied by the operating system.
    Action: Verify file and directory access privileges on the file system, and if reading, verify that the file exists
    The file exists and the user has the privileges to access the file too - but still having problems
    please help -
    if any buddy has the idea please share -
    Thanks
    Y.V.

    Hello Y.V.
    Have you set the parameter utl_file_dir? Please check. In most of the cases the problem is because of this parameter
    You can set it to directory that you want to access. Or else you can set it to * (which means) that UTL_FILE would be able to read from any directory on which Oracle Binary Owner has got access. Please be careful when setting this to *
    To check the parameter use query:
    select name,value from v$parameter
    where name ='utl_file_dir';
    Regards
    Sudhanshu
    OCP DBA

  • Query on UTL_FILE

    Hi All,
    I have a procedure which generates a file using UTL_FILE package. If the procedure fails while generating the file, will ORACLE cloase the file after the procedure fails?
    Thanks in advance,
    Annie

    user10660677 wrote:
    Continuing on this discussion, is there a way to check the file is open when the procedure is called once again after it has failed.
    To make it more clear, is it possible to check whether the file was left open from the last time the procedure was called. If yes, then close it and try a fresh open.Only if you still have the file handle, which typically you won't as you will have declared it locally within the procedure.
    If however, it was a package variable and you were still connected within the same database session then the package variable would still hold the file handle.
    However, I wouldn't recommend doing it that way because it's leaving it open to problems. Far better to capture the exception, close the file if it's open and then raise the exception up.

  • Producing text file from PL/SQL procedure (UTL_FILE)?

    Hi,
    I need to produce a text file from a PL/SQL procedure. My output should be a little over 38K records and my query has 70 fields. I'd like to separate the fields by pipe delimiters in the text file. I can either concatenate all 70 fields into one variable for each record or send all 70 fields over with a pipe, whichever is easier. It looks like I can't spool within PL/SQL but UTL_FILE might be an option from what I'm reading. Does anyone have any good, simple example(s) to produce a text file using this package in calling multiple fields from a LOOP? Our os is UNIX and db is Oracle 9i.
    Also, I've read that UTL_FILE has a record output of 1,023 bytes. Is this for each record line or the whole file size? I belive the max # of characters for each line wouldn't exceed 500 characters. The 38K rows I have for the data set would be well over 1MB. If this is the case, is there a work around to produce a larger text file?
    Any suggestions and/or examples would be greatly appreciated.
    Thanks,
    Eric

    Assuming the goal is to create a text file on the database server, you can use UTL_FILE here. Each line can be 1023 characters, but you can have as many lines as you'd like.
    Tom Kyte has an example here
    http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:235814350980
    Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

  • How do I use UTL_FILE to insert a large number of fields to a file?

    Hi
    I am trying to use UTL_FILE for the first time in a Stored Procedure. I need to run a complex query to select 50 fields from various tables. I need these to be inserted into one line in the output file for all rows. Is this possible? My procedure so far is like the following
    CREATE OR REPLACE PROCEDURE PROC_TEST IS
    output_file UTL_FILE.FILE_TYPE;
    BEGIN
    FOR query in (SELECT FIELD1, FIELD2, ..........FIELD50)
    FROM TABLE A, TABLE B
    WHERE A.ID = B.ID
    ETC
    LOOP
    UTL_FILE.PUT_LINE(output_file, <put all 50 fields for all records into file> );
    END LOOP;               
    UTL_FILE.FCLOSE (output_file);
    EXCEPTION
    WHEN NO_DATA_FOUND THEN
    NULL;
    WHEN OTHERS THEN
         UTL_FILE.FCLOSE_ALL;
    RAISE;
    END PROC_TEST;
    Do I need to define 'query' (after the FOR) anywhere, also please advise with how I put all of the fields into the file.
    Thanks
    GB

    Thanks Steve,
    I have the UTL_FILE working fine now.
    I have other queries to run and conditions to apply in the same procedure, and I need to schedule via Enterprise Manager, therefore using UTL_FILE in a procedure seemed the best option. I looked up Data-pump but this seems to be an 11g feature, and we are still on 10g therefore I will not be able to use it.
    Thanks for your help.
    GB

  • How to read a specific value or a portion of text using utl_file.

    hi,
    I have a small requirement which goes as follows. I have a text file which is a resultof the sql query and it contains 16 columns as PIPE delimited text . I am using the UTL_FILE package concept to read the data. In general when we use the UTL_FILE.GET_LINE we read the entire line of text. But i need to read the 10th column of the query or the PIPE delimited text .
    Please advice.
    My query goes something like this:
    declare
    f utl_file.file_type;
    s long;
    c number := 0;
    begin
    f := utl_file.fopen('ABC_EXTRACTS','sample1.txt','R');
    loop
    utl_file.get_line(f,s);
    insert into s values (s);
    c := c + 1;
    end loop;
    exception
    when NO_DATA_FOUND then
    utl_file.fclose(f);
    dbms_output.put_line('No. of rows inserted : ' || c);
    end;

    Why don't you use varchar2 instead of long data type. I doubt you can read a portion from a file using utl_file but after doing the fetch you can do substring over the varchar2 variable and retrieve just the 10th column.
    sample sql:
    If your DB is 10g or higher, you can use the below regular expression to retrieve value based on your need.
    PRAZY@11gR1> select regexp_substr('111|222|333|444|555|666|777|888|999|000|aaa|bbb|','[^|]+',1,10) from dual;
    REG
    000
    Elapsed: 00:00:00.00Btwn, if the text file has fixed number of columns at all time, why don't you use a external table instead?
    Regards,
    Prazy
    Edited by: Prazy on Mar 22, 2010 4:11 PM

  • Can someone please help me with a sub query question?

    I need to list a 3rd party contract and then a list of students who belong to that contract.
    On the students segment of the listing I need to show students with student id, name, total credit hours,
    total amount spent on tuition, total amount spent on books and total amount spent on misc.
    This code has a query for the contract information and I get that just fine.
    Then it has a query that gives me total credit hours and that works fine
    then it has a query that gives me total amount spent on tuition and that works fine
    but
    when I add the next query to get total amount spent on books I get only the information for the contract, I don't get student stuff anymore.
    I would really appreciate any guidance that you could give.
    Thanks in advance, Bob Hohulski
    DECLARE
    l_conn utl_TCP.connection;
    v_filehandle utl_file.file_type;
    v_output varchar2(1000);
    v_contract_id varchar2(9);
    v_contract_addr1 varchar2(30);
    v_contract_addr2 varchar2(30);
    v_contract_city varchar2(20);
    v_contract_stat varchar2(03);
    v_contract_zip varchar2(10);
    v_contract_name varchar2(60);
    v_student_id varchar2(09);
    v_student_first_name varchar2(15);
    v_student_mid_name varchar2(15);
    v_student_last_name varchar2(60);
    v_last_out varchar2(20);
    v_student_detail_code varchar2(04);
    v_student_amount number(12,2);
    v_student_ref_number varchar2(09);
    v_credit_hrs number(7,2);
    v_tuition_amount number(12,2);
    v_books_amount number(12,2);
    v_misc_amount number(12,2);
    v_total_for_student number(12,2);
    v_current_student varchar2(09);
    v_sftregs_pidm varchar2(09);
    v_tbraccd_pidm varchar2(09);
    CURSOR c_sel_contract IS
    SELECT DISTINCT spriden_id, spriden_last_name,
    spraddr_street_line1, spraddr_street_line2,
    spraddr_city, spraddr_stat_code, spraddr_zip
    FROM spriden, spraddr
    -- WHERE spriden_id = '&Enter_Id'
    where spriden_id = 'T10474666'
    AND spriden_pidm = spraddr_pidm
    AND SPRIDEN_CHANGE_IND IS NULL;
    CURSOR c_sel_student IS
    SELECT DISTINCT spriden_id, spriden_first_name, spriden_mi, spriden_last_name,
    sftregs_credit_hr,
    tbraccd_amount,
    sftregs_pidm,
    tbraccd_pidm
    FROM spriden, tbraccd, tbbcstu, sftregs
    WHERE 559220 = tbbcstu_contract_pidm
    AND spriden_pidm = tbraccd_pidm
    AND spriden_pidm = tbbcstu_stu_pidm
    AND spriden_pidm = sftregs_pidm
    AND (sftregs_pidm, sftregs_credit_hr) IN
    (SELECT DISTINCT sftregs_pidm, SUM(sftregs_credit_hr)
    FROM sftregs, tbbcstu, spriden
    WHERE sftregs_term_code = '201010'
    AND sftregs_pidm = tbbcstu_stu_pidm
    AND sftregs_pidm = spriden_pidm
    GROUP BY sftregs_pidm)
    AND (tbraccd_pidm, tbraccd_amount) IN
    (SELECT DISTINCT tbraccd_pidm, SUM(tbraccd_amount)
    -- tuition
    FROM tbraccd, tbbcstu, spriden
    WHERE tbraccd_term_code = '201010'
    AND (tbraccd_detail_code = 'TU01' OR
    tbraccd_detail_code = 'TU02' OR
    tbraccd_detail_code = 'TU03' OR
    tbraccd_detail_code = 'TU04')
    AND tbraccd_pidm = tbbcstu_stu_pidm
    AND tbraccd_pidm = spriden_pidm
    GROUP BY tbraccd_pidm)
    --this code works up to this point
    --when I add the next query I get nothing
    AND (tbraccd_pidm, tbraccd_amount) IN
    (SELECT tbraccd_pidm, SUM(tbraccd_amount)
    books
    FROM tbraccd, tbbcstu
    WHERE tbraccd_term_code = '201010'
    AND (tbraccd_detail_code = 'BKSU' OR
    tbraccd_detail_code = 'BKCH')
    AND tbraccd_pidm = tbbcstu_stu_pidm
    GROUP BY tbraccd_pidm, tbraccd_amount)
    --AND (tbraccd_pidm, tbraccd_amount) IN
    -- (SELECT tbraccd_pidm, SUM(tbraccd_amount)
    -- misc
    -- FROM tbraccd, tbbcstu
    -- WHERE tbraccd_term_code = '201010'
    -- AND tbraccd_pidm = tbbcstu_stu_pidm
    -- AND (tbraccd_detail_code = 'AUNA' OR
    -- tbraccd_detail_code = 'OTPB')
    -- GROUP BY tbraccd_pidm, tbraccd_amount)
    --ORDER BY tbraccd_pidm, spriden_first_name, spriden_mi, spriden_last_name,
    -- tbbcstu_sponsor_ref_number, sftregs_credit_hr;
    ORDER BY tbraccd_pidm;
    BEGIN
    v_filehandle := utl_file.fopen(location => 'UTLFILE_MISAP9',
    filename => 'ban_matrix.dat',
    open_mode => 'w',
    max_linesize => 32767);
    OPEN c_sel_contract;
    LOOP
    DBMS_OUTPUT.PUT_LINE('looping');
    FETCH c_sel_contract INTO v_contract_id, v_contract_name,
    v_contract_addr1, v_contract_addr2,
    v_contract_city, v_contract_stat,
    v_contract_zip;
    EXIT WHEN c_sel_contract%NOTFOUND;
    v_output :=
    nvl(rpad(v_contract_id,9),rpad(' ',9)) ||
    ' ' ||
    nvl(rpad(v_contract_name,60),rpad(' ',60));
    utl_file.put_line(v_filehandle,v_output);
    v_output :=
    nvl(rpad(v_contract_addr1, 30),rpad(' ',30)) ||
    ' ' ||
    nvl(rpad(v_contract_addr2, 30),rpad(' ',30));
    utl_file.put_line(v_filehandle,v_output);
    v_output :=
    nvl(rpad(v_contract_city, 20), rpad(' ',20)) ||
    ' ' ||
    nvl(rpad(v_contract_stat, 3), rpad(' ',3)) ||
    ' ' ||
    nvl(rpad(v_contract_zip, 10), rpad(' ',10));
    utl_file.put_line(v_filehandle,v_output);
    utl_file.new_line(v_filehandle);
    OPEN c_sel_student;
    LOOP
    FETCH c_sel_student into v_student_id, v_student_first_name, v_student_mid_name,
    v_student_last_name,
    v_credit_hrs,
    v_tuition_amount,
    v_sftregs_pidm,
    v_tbraccd_pidm;
    -- v_books_amount, v_misc_amount;
    EXIT WHEN c_sel_student%NOTFOUND;
    v_last_out := substr(v_student_last_name, 1, 20);
    v_output :=
    nvl(rpad(v_student_id, 09),rpad(' ',09)) ||
    ' ' ||
    nvl(rpad(v_student_first_name, 15),rpad(' ',15)) ||
    nvl(rpad(v_student_mid_name, 15),rpad(' ',15)) ||
    nvl(rpad(v_last_out, 20),rpad(' ',20)) ||
    ' ' ||
    nvl(rpad(v_student_ref_number, 09),rpad(' ',09)) ||
    ' ' ||
    v_credit_hrs ||
    ' ' ||
    v_tuition_amount ||
    -- v_books_amount ||
    -- ' ' ||
    -- v_misc_amount;
    utl_file.put_line(v_filehandle,v_output);
    END LOOP;
    END LOOP;
    --EXCEPTION
    --WHEN OTHERS THEN
    -- DECLARE
    -- err_msg VARCHAR2(100);
    -- BEGIN
    -- err_msg := 'ERR- '||SUBSTR(SQLERRM, 1,100);
    -- - utl_file.put_line(v_filehandle,err_msg);
    --END;
    utl_file.fclose(v_filehandle);
    CLOSE c_sel_contract;
    CLOSE c_sel_student;
    --END AR_MATRIX_PROC;
    END;

    run this original query
    SELECT DISTINCT spriden_id,
            spriden_first_name,
            spriden_mi,
            spriden_last_name,
            sftregs_credit_hr,
            tbraccd_amount,
            sftregs_pidm,
            tbraccd_pidm
       FROM spriden, tbraccd, tbbcstu, sftregs
    WHERE 559220 = tbbcstu_contract_pidm
       AND spriden_pidm = tbraccd_pidm
       AND spriden_pidm = tbbcstu_stu_pidm
       AND spriden_pidm = sftregs_pidm
       AND (sftregs_pidm, sftregs_credit_hr) IN (SELECT DISTINCT sftregs_pidm, SUM(sftregs_credit_hr)
                                                   FROM sftregs, tbbcstu, spriden
                                                  WHERE sftregs_term_code = '201010'
                                                    AND sftregs_pidm = tbbcstu_stu_pidm
                                                    AND sftregs_pidm = spriden_pidm
                                                 GROUP BY sftregs_pidm)
       AND (tbraccd_pidm, tbraccd_amount) IN (SELECT DISTINCT tbraccd_pidm, SUM(tbraccd_amount)
                                              -- tuition
                                                FROM tbraccd, tbbcstu, spriden
                                               WHERE tbraccd_term_code = '201010'
                                                 AND (tbraccd_detail_code = 'TU01' OR
                                                      tbraccd_detail_code = 'TU02' OR
                                                      tbraccd_detail_code = 'TU03' OR
                                                      tbraccd_detail_code = 'TU04')
                                                 AND tbraccd_pidm = tbbcstu_stu_pidm
                                                 AND tbraccd_pidm = spriden_pidm
                                               GROUP BY tbraccd_pidm)
       AND (tbraccd_pidm, tbraccd_amount) IN (SELECT tbraccd_pidm, SUM(tbraccd_amount) books
                                                FROM tbraccd, tbbcstu
                                               WHERE tbraccd_term_code = '201010'
                                                 AND (tbraccd_detail_code = 'BKSU' OR
                                                      tbraccd_detail_code = 'BKCH')
                                                 AND tbraccd_pidm = tbbcstu_stu_pidm
                                              GROUP BY tbraccd_pidm, tbraccd_amount)
    ORDER BY tbraccd_pidm;then run this sub-query:
    SELECT tbraccd_pidm, SUM(tbraccd_amount) books
       FROM tbraccd, tbbcstu
      WHERE tbraccd_term_code = '201010'
        AND (tbraccd_detail_code = 'BKSU' OR
             tbraccd_detail_code = 'BKCH')
       AND tbraccd_pidm = tbbcstu_stu_pidm
    GROUP BY tbraccd_pidm, tbraccd_amount)see if you have a matching tbraccd_pidm and tbraccd_amount between the two results.

  • Master-details query to XML file?

    Hi:
    I'm new in XML and Oracle. I want to create XML file from two tables (master-details).
    I made a small serach and tried some examples:
    Say we have these tables:
    CREATE TABLE "TEST_XML"
    (     "ID" NUMBER,
         "NAME" VARCHAR2(15),
         "AMOUNT" NUMBER,
         CONSTRAINT "TEST_XML_PK" PRIMARY KEY ("ID") ENABLE
    CREATE TABLE "TEST_XML2"
    (     "ID2" NUMBER,
         "NAME2" VARCHAR2(20),
         "AMOUNT2" NUMBER
    ALTER TABLE "TEST_XML2" ADD CONSTRAINT "TEST_XML2_FK" FOREIGN KEY ("ID2")
         REFERENCES "TEST_XML" ("ID") ENABLE
    INSERT INTO TEST_XML VALUES (1,'A',50);
    INSERT INTO TEST_XML VALUES (2,'B',30);
    INSERT INTO TEST_XML VALUES (3,'C',70);
    INSERT INTO TEST_XML2 VALUES (1,'AA',10);
    INSERT INTO TEST_XML2 VALUES (1,'AB',20);
    INSERT INTO TEST_XML2 VALUES (1,'AC',20);
    INSERT INTO TEST_XML2 VALUES (2,'BA',10);
    INSERT INTO TEST_XML2 VALUES (2,'BB',20);
    INSERT INTO TEST_XML2 VALUES (3,'CA',20);
    INSERT INTO TEST_XML2 VALUES (3,'CB',40);
    INSERT INTO TEST_XML2 VALUES (3,'CC',10);
    I want a query to create XML file contains data from TEST_XML table and for each row the related data from TEST_XML2 table.
    I did some tries (working in iSQL*PLUS):
    SET SERVEROUTPUT ON
    DECLARE
    v_ctx DBMS_XMLGEN.ctxType;
    v_file Utl_File.File_Type;
    v_xml CLOB;
    v_more BOOLEAN := TRUE;
    BEGIN
    -- Create XML document from query.
    v_ctx := DBMS_XMLGEN.newContext('select id,name,amount,cursor (select id2,name2,amount2 from test_xml2 t2 where t2.id2=t1.id) val from test_xml t1');
    DBMS_XMLGEN.setMaxRows(v_ctx, 10);
    DBMS_XMLGEN.setRowsetTag(v_ctx, 'CLAIM');
    -- Output XML document to file.
    v_file := Utl_File.FOpen('TEST_DIR', 'test1.xml', 'w');
    WHILE v_more
    LOOP
    v_xml := DBMS_XMLGEN.GetXML(v_ctx,0);
    EXIT WHEN dbms_xmlgen.getNumRowsProcessed(v_ctx) =0;
    Utl_File.Put(v_file,v_xml);
    END LOOP;
    Utl_File.FClose(v_file);
    EXCEPTION
    WHEN OTHERS THEN
    DBMS_OUTPUT.PUT_LINE(SUBSTR(SQLERRM,1,255));
    Utl_File.FClose(v_file);
    END;
    But hte output wasn't as I wanted:
    <CLAIM>
    <ROW>
    <ID>1</ID>
    <NAME>A</NAME>
    <AMOUNT>50</AMOUNT>
    <VAL>
    <VAL_ROW>
    <ID2>1</ID2>
    <NAME2>AA</NAME2>
    <AMOUNT2>10</AMOUNT2>
    </VAL_ROW>
    <VAL_ROW>
    <ID2>1</ID2>
    <NAME2>AB</NAME2>
    <AMOUNT2>20</AMOUNT2>
    </VAL_ROW>
    <VAL_ROW>
    <ID2>1</ID2>
    <NAME2>AC</NAME2>
    <AMOUNT2>20</AMOUNT2>
    </VAL_ROW>
    </VAL>
    </ROW>
    <ROW>
    <ID>3</ID>
    <NAME>C</NAME>
    <AMOUNT>70</AMOUNT>
    <VAL>
    <VAL_ROW>
    <ID2>3</ID2>
    <NAME2>CA</NAME2>
    <AMOUNT2>20</AMOUNT2>
    </VAL_ROW>
    <VAL_ROW>
    <ID2>3</ID2>
    <NAME2>CB</NAME2>
    <AMOUNT2>40</AMOUNT2>
    </VAL_ROW>
    <VAL_ROW>
    <ID2>3</ID2>
    <NAME2>CC</NAME2>
    <AMOUNT2>10</AMOUNT2>
    </VAL_ROW>
    </VAL>
    </ROW>
    <ROW>
    <ID>2</ID>
    <NAME>B</NAME>
    <AMOUNT>30</AMOUNT>
    <VAL>
    <VAL_ROW>
    <ID2>2</ID2>
    <NAME2>BA</NAME2>
    <AMOUNT2>10</AMOUNT2>
    </VAL_ROW>
    <VAL_ROW>
    <ID2>2</ID2>
    <NAME2>BB</NAME2>
    <AMOUNT2>20</AMOUNT2>
    </VAL_ROW>
    </VAL>
    </ROW>
    </CLAIM>
    Notice that for each details (from TEST_XML2) there is <VAL> tag which I don't need beside i want a query which is applicable on all environments.
    May anyone help me please......
    Regards,
    Saad

    The following looks like it produces your desired output. I used the WITH to simulate your two tables so I didn't have to CREATE them. This runs on 10.2.0.1. I'm not sure what bugs you are referring to as SQL/XML is stable in 10g that I have seen. I'm sure some bugs exist somewhere in it, just not with this usage. Just start with the SELECT statement to run on your system.
    WITH test_xml AS
    (SELECT 1 ID, 'A' name, 50 amount FROM DUAL UNION ALL
    SELECT 2, 'B', 30  FROM DUAL UNION ALL
    SELECT 3, 'C', 70  FROM DUAL),
    test_xml2 AS
    (SELECT 1 ID2, 'AA' name2, 10 amount2 FROM DUAL UNION ALL
    SELECT 1, 'AB', 20  FROM DUAL UNION ALL
    SELECT 1, 'AC', 20  FROM DUAL UNION ALL
    SELECT 2, 'BA', 10  FROM DUAL UNION ALL
    SELECT 2, 'BB', 20  FROM DUAL UNION ALL
    SELECT 2, 'BC', 20  FROM DUAL UNION ALL
    SELECT 3, 'CA', 20  FROM DUAL UNION ALL
    SELECT 3, 'CB', 40  FROM DUAL UNION ALL
    SELECT 3, 'CC', 10  FROM DUAL)
    SELECT XMLElement("CLAIM",
             XMLAgg(
               XMLElement("ROW",
                 XMLForest(id "ID",
                           name "NAME",
                           amount "AMOUNT"),
                 (SELECT XMLAgg(XMLElement("VAL_ROW",
                                 XMLForest(id2 "ID2",
                                           name2 "NAME2",
                                           amount2 "AMOUNT2")))
                          FROM test_xml2 t2
                         WHERE t2.id2=t1.id)
      FROM test_xml t1This solution works in any environment where you can issue a SQL statement from, be it SQL*Plus, PL/SQL, Java, etc.

  • Query o/p directly written intofile present disk in 11g

    in 11g i came to know that xml data from table is directly saved in dsik using below code
    Saving XML data directly to disk
    The below example explains the how to create xml file and save that file in disk
    (1) Create logical directory
    CREATE OR REPLACE directory utldata as 'C:\temp';
    (2)
    declare
    doc DBMS_XMLDOM.DOMDocument;
    xdata XMLTYPE;
    CURSOR xmlcur IS
    SELECT xmlelement("Employee",XMLAttributes('http://www.w3.org/2001/XMLSchema' AS
    "xmlns:xsi",
    'http://www.oracle.com/Employee.xsd' AS
    "xsi:nonamespaceSchemaLocation")
    ,xmlelement("EmployeeNumber",e.empno)
    ,xmlelement("EmployeeName",e.ename)
    ,xmlelement("Department",xmlelement("DepartmentName",d.dname)
    ,xmlelement("Location",d.loc)
    FROM emp e
    , dept d
    WHERE e.DEPTNO=d.DEPTNO;
    begin
    OPEN xmlcur;
    FETCH xmlcur INTO xdata;
    CLOSE xmlcur;
    doc := DBMS_XMLDOM.NewDOMDocument(xdata);
    DBMS_XMLDOM.WRITETOFILE(doc, 'UTLDATA/marco.xml');
    end;
    The file with name as marco.xml is created and saved in this folder C:\temp
    The content of file is shown below
    - <Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema" xsi:nonamespaceSchemaLocation="http://www.oracle.com/Employee.xsd">
    <EmployeeNumber>7369</EmployeeNumber>
    <EmployeeName>SMITH</EmployeeName>
    - <Department>
    <DepartmentName>RESEARCH</DepartmentName>
    <Location>DALLAS</Location>
    </Department>
    </Employee>
    similarly is there any method for o/p of the query reslut directly written into file which is in disk in 11g

    There are various ways, but generally you would use UTL_FILE to write out data to a file:
    CREATE OR REPLACE PROCEDURE run_query(p_sql IN VARCHAR2
                                         ,p_dir IN VARCHAR2
                                         ,p_header_file IN VARCHAR2
                                         ,p_data_file IN VARCHAR2 := NULL) IS
      v_finaltxt  VARCHAR2(4000);
      v_v_val     VARCHAR2(4000);
      v_n_val     NUMBER;
      v_d_val     DATE;
      v_ret       NUMBER;
      c           NUMBER;
      d           NUMBER;
      col_cnt     INTEGER;
      f           BOOLEAN;
      rec_tab     DBMS_SQL.DESC_TAB;
      col_num     NUMBER;
      v_fh        UTL_FILE.FILE_TYPE;
      v_samefile  BOOLEAN := (NVL(p_data_file,p_header_file) = p_header_file);
    BEGIN
      c := DBMS_SQL.OPEN_CURSOR;
      DBMS_SQL.PARSE(c, p_sql, DBMS_SQL.NATIVE);
      d := DBMS_SQL.EXECUTE(c);
      DBMS_SQL.DESCRIBE_COLUMNS(c, col_cnt, rec_tab);
      FOR j in 1..col_cnt
      LOOP
        CASE rec_tab(j).col_type
          WHEN 1 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000);
          WHEN 2 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_n_val);
          WHEN 12 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_d_val);
        ELSE
          DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000);
        END CASE;
      END LOOP;
      -- This part outputs the HEADER
      v_fh := UTL_FILE.FOPEN(upper(p_dir),p_header_file,'w',32767);
      FOR j in 1..col_cnt
      LOOP
        v_finaltxt := ltrim(v_finaltxt||','||lower(rec_tab(j).col_name),',');
      END LOOP;
      --  DBMS_OUTPUT.PUT_LINE(v_finaltxt);
      UTL_FILE.PUT_LINE(v_fh, v_finaltxt);
      IF NOT v_samefile THEN
        UTL_FILE.FCLOSE(v_fh);
      END IF;
      -- This part outputs the DATA
      IF NOT v_samefile THEN
        v_fh := UTL_FILE.FOPEN(upper(p_dir),p_data_file,'w',32767);
      END IF;
      LOOP
        v_ret := DBMS_SQL.FETCH_ROWS(c);
        EXIT WHEN v_ret = 0;
        v_finaltxt := NULL;
        FOR j in 1..col_cnt
        LOOP
          CASE rec_tab(j).col_type
            WHEN 1 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_v_val);
                        v_finaltxt := ltrim(v_finaltxt||',"'||v_v_val||'"',',');
            WHEN 2 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_n_val);
                        v_finaltxt := ltrim(v_finaltxt||','||v_n_val,',');
            WHEN 12 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_d_val);
                        v_finaltxt := ltrim(v_finaltxt||','||to_char(v_d_val,'DD/MM/YYYY HH24:MI:SS'),',');
          ELSE
            v_finaltxt := ltrim(v_finaltxt||',"'||v_v_val||'"',',');
          END CASE;
        END LOOP;
      --  DBMS_OUTPUT.PUT_LINE(v_finaltxt);
        UTL_FILE.PUT_LINE(v_fh, v_finaltxt);
      END LOOP;
      UTL_FILE.FCLOSE(v_fh);
      DBMS_SQL.CLOSE_CURSOR(c);
    END;This allows for the header row and the data to be written to seperate files if required.
    e.g.
    SQL> exec run_query('select * from emp','TEST_DIR','output.txt');
    PL/SQL procedure successfully completed.Output.txt file contains:
    empno,ename,job,mgr,hiredate,sal,comm,deptno
    7369,"SMITH","CLERK",7902,17/12/1980 00:00:00,800,,20
    7499,"ALLEN","SALESMAN",7698,20/02/1981 00:00:00,1600,300,30
    7521,"WARD","SALESMAN",7698,22/02/1981 00:00:00,1250,500,30
    7566,"JONES","MANAGER",7839,02/04/1981 00:00:00,2975,,20
    7654,"MARTIN","SALESMAN",7698,28/09/1981 00:00:00,1250,1400,30
    7698,"BLAKE","MANAGER",7839,01/05/1981 00:00:00,2850,,30
    7782,"CLARK","MANAGER",7839,09/06/1981 00:00:00,2450,,10
    7788,"SCOTT","ANALYST",7566,19/04/1987 00:00:00,3000,,20
    7839,"KING","PRESIDENT",,17/11/1981 00:00:00,5000,,10
    7844,"TURNER","SALESMAN",7698,08/09/1981 00:00:00,1500,0,30
    7876,"ADAMS","CLERK",7788,23/05/1987 00:00:00,1100,,20
    7900,"JAMES","CLERK",7698,03/12/1981 00:00:00,950,,30
    7902,"FORD","ANALYST",7566,03/12/1981 00:00:00,3000,,20
    7934,"MILLER","CLERK",7782,23/01/1982 00:00:00,1300,,10

  • UTL_FILE reqeust taking too much time for completion

    Hi,
    We are running utl_file reqeust.
    the select statement fetching 6000 records, for this it taking 22 mins for completion.
    the code is
    CREATE OR REPLACE PACKAGE BODY "XXC"."XXC_MOD_IN_068_AP_TO_FIS_PKG"
    AS
    * Module Type : PL/SQL
    * Module Name : XXC_MOD_IN_068_AP_FIS_PKG
    * Description : This package is used for AP to Fiscal Interface.
    * Run Env. : SQL*Plus
    * Procedure Name Description
    * XXC_MOD_068_AP_PR XXC_MOD_068_AP_PR Procedure is used to insert transactions
    * into CSV OutPut File from Oracle Account Payables.
    * Calling Module: None
    * Modules Called: XXC_COMMON_INT_PK.INSERT_AUDIT
    * Module Number : MOD_IN_068
    * Known Bugs and Restrictions: none
    * History
    * =======
    * Version Name Date Description of Change
    * 0.1 Sanjeev Khurana 25-JULY-2011 Initial Creation.
    * 0.2 Rohit 09-DEC-2011 Updated header details for the file
    * 0.3 Amit Kulwal 28-AUG-2012 Updated the cursor query for incident 671520
    * 0.4 Swaraj Goud 20-Nov-2012 Updated as per the CR 671520
    | PACKAGE BODY
    -- Actual Code Start Here
    -- Procedure : XXC_MOD_068_AP_PR
    -- Description : XXC_MOD_068_AP_PR Procedure is used to insert transactions
    -- into CSV OUTPUT File from Oracle Account Payables.
    -- Parameters:
    -- Parm Name I/O Description
    -- p_errbuf OUT Error message.
    -- p_retcode OUT Error code. Returns 0 if no errors otherwise returns 1.
    -- p_start_date IN Start Date
    -- p_end_date IN End Date
    PROCEDURE xxc_mod_068_ap_pr (
    p_errbuf OUT VARCHAR2,
    p_retcode OUT NUMBER,
    p_start_date IN VARCHAR2,
    p_end_date IN VARCHAR2
    IS
    -- Define variables and assign default values
    l_sucess_count NUMBER := 0;
    l_error_count NUMBER := 0;
    -- Standard declaration
    l_source VARCHAR2 (10);
    l_target VARCHAR2 (10);
    lc_module_description VARCHAR2 (50)
    := 'MOD_IN_068 - AP to Fiscal';
    l_status CONSTANT VARCHAR2 (50) := 'NEW';
    p_status NUMBER;
    l_batch_id NUMBER;
    l_batch_id_next NUMBER
    := apps_common_out_batch_id_s1.NEXTVAL;
    l_proc_name VARCHAR2 (100) := 'XXC_MOD_IN_068';
    l_request_id NUMBER
    := fnd_global.conc_request_id;
    l_audit_master_id NUMBER := NULL;
    l_mod_code VARCHAR2 (100);
    l_log_type NUMBER := 1; --INFORMATION
    l_det_status_success NUMBER := 0; --SUCCESS
    l_det_status_inprocess NUMBER := 3; --INPROCESS
    l_det_status_rejected NUMBER := 4; --REJECTED
    l_det_status_err NUMBER := 3; --Error
    l_det_status_complete NUMBER := 9; --COMPLETE
    -- Standard who Columns
    l_created_by NUMBER := fnd_global.user_id;
    l_creation_date DATE := SYSDATE;
    l_last_update_date DATE := SYSDATE;
    l_last_update_login NUMBER := fnd_global.user_id;
    v_file UTL_FILE.file_type;
    l_location VARCHAR2 (150);
    l_archive_location VARCHAR2 (150);
    l_date VARCHAR2 (50);
    l_filename VARCHAR2 (50);
    l_open_mode VARCHAR2 (1) := 'W';
    --- l_max_linesize NUMBER := 32767;
    l_max_linesize VARCHAR2 (150); -- Updated 09-Nov-2012
    --Cursor is used to fetch valid records for the interface
    CURSOR get_ap_data_inv
    IS
    SELECT asp.segment1 supplier_ref,
    -- asp.vendor_name supplier_name,
    replace(asp.vendor_name, ',', ' ') supplier_name,
    --aia.invoice_num invoice_number,
    replace(aia.invoice_num, ',','') invoice_number,
    aia.invoice_date,
    aia.invoice_amount amount,
    aia.doc_sequence_value unique_id,
    aia.creation_date date_invoice_entered,
    apsa.due_date date_invoice_paid,
    aia.SOURCE user_id,
    aia.payment_status_flag,
    aia.invoice_type_lookup_code doc_type,
    --aia.description,
    replace(aia.description, ',' , ' ') description,
    apsa.gross_amount
    FROM ap_invoices_all aia,
    ap_suppliers asp,
    apps.ap_payment_schedules_all apsa
    -- apps.iby_payments_all iba,
    -- apps.iby_docs_payable_all dp
    WHERE aia.invoice_id = apsa.invoice_id
    AND aia.vendor_id = asp.vendor_id
    AND aia.org_id = apsa.org_id
    -- AND apsa.payment_status_flag != 'Y' -- commented for CR
    -- AND dp.payment_id = iba.payment_id(+)
    -- AND aia.invoice_id = dp.calling_app_doc_unique_ref2(+)
    -- AND apsa.due_date <= (SYSDATE + 1)
    AND TRUNC (aia.creation_date)
    BETWEEN NVL (fnd_date.canonical_to_date (p_start_date),
    TRUNC (aia.creation_date))
    AND NVL (fnd_date.canonical_to_date (p_end_date),
    TRUNC (aia.creation_date));
         TYPE xxc_tbl IS TABLE OF get_ap_data_inv%ROWTYPE;
    xxc_tbl1 xxc_tbl;
    BEGIN
    l_batch_id := apps_common_out_batch_id_s1.CURRVAL;
    xxc_common_int_pk.insert_audit (p_batch_id => l_batch_id,
    p_request_id => l_request_id,
    p_source_system => l_source,
    p_proc_name => l_proc_name,
    p_log_type => l_log_type,
    p_det_status => l_det_status_inprocess,
    p_msg_code => NULL,
    p_entity => NULL,
    p_msg_desc => 'Process Starts',
    p_mast_request_id => l_request_id,
    p_record_id => NULL,
    p_source => l_source,
    p_target => l_target,
    p_email => NULL,
    p_mod_code => l_mod_code,
    p_audit_master_id => l_audit_master_id
    -- Get Module Code
    BEGIN
    SELECT TRIM (fval.flex_value),
    TRIM (SUBSTR (fval.description,
    1,
    INSTR (fval.description, ' -')
    INTO l_source,
    l_mod_code
    FROM fnd_flex_values_vl fval, fnd_flex_value_sets vset
    WHERE vset.flex_value_set_id = fval.flex_value_set_id
    AND vset.flex_value_set_name IN ('XXC_COMM_INT_CONFIG')
    AND fval.enabled_flag = 'Y'
    AND fval.description = lc_module_description;
    EXCEPTION
    WHEN OTHERS
    THEN
    xxc_common_int_pk.insert_audit (p_batch_id => l_batch_id,
    p_request_id => l_request_id,
    p_source_system => l_source,
    p_proc_name => l_proc_name,
    p_log_type => l_log_type,
    p_det_status => l_det_status_err,
    p_msg_code => NULL,
    p_entity => NULL,
    p_msg_desc => 'Error Mode Code',
    p_mast_request_id => l_request_id,
    p_record_id => NULL,
    p_source => l_source,
    p_target => l_target,
    p_email => NULL,
    p_mod_code => l_mod_code,
    p_audit_master_id => l_audit_master_id
    raise_application_error (-20045, SQLERRM);
    END;
    --File Location Path for OutPut File
    BEGIN
    SELECT fnd_profile.VALUE ('XXC_MOD_IN_068_AP_OUTBOUND'),
    fnd_profile.VALUE ('XXC_MOD_IN_068_AP_ARCHIVE')
    INTO l_location,
    l_archive_location
    FROM DUAL;
    EXCEPTION
    WHEN OTHERS
    THEN
    xxc_common_int_pk.insert_audit
    (p_batch_id => l_batch_id,
    p_request_id => l_request_id,
    p_source_system => l_source,
    p_proc_name => l_proc_name,
    p_log_type => l_log_type,
    p_det_status => l_det_status_rejected,
    p_msg_code => NULL,
    p_entity => NULL,
    p_msg_desc => 'Profile Value not found',
    p_mast_request_id => l_request_id,
    p_record_id => NULL,
    p_source => l_source,
    p_target => l_target,
    p_email => NULL,
    p_mod_code => l_mod_code,
    p_audit_master_id => l_audit_master_id
    END;
    BEGIN
    SELECT TO_CHAR (SYSDATE, 'YYYYMMDDhh24miss')
    INTO l_date
    FROM DUAL;
    EXCEPTION
    WHEN OTHERS
    THEN
    xxc_common_int_pk.insert_audit (p_batch_id => l_batch_id,
    p_request_id => l_request_id,
    p_source_system => l_source,
    p_proc_name => l_proc_name,
    p_log_type => l_log_type,
    p_det_status => l_det_status_rejected,
    p_msg_code => NULL,
    p_entity => NULL,
    p_msg_desc => 'status not found',
    p_mast_request_id => l_request_id,
    p_record_id => NULL,
    p_source => l_source,
    p_target => l_target,
    p_email => NULL,
    p_mod_code => l_mod_code,
    p_audit_master_id => l_audit_master_id
    END;
    l_filename := 'AP_Fiscal_' || l_date || '.csv';
    v_file :=
    UTL_FILE.fopen (LOCATION => l_location,
    filename => l_filename,
    open_mode => l_open_mode,
    max_linesize => l_max_linesize
    -- Changed as per Sarah's email on 9th Decemeber
    /* UTL_FILE.put_line (v_file,
    'SUPPLIER_REF'
    || ','
    || 'SUPPLIER_NAME'
    || ','
    || 'INVOICE_NUMBER'
    || ','
    || 'INVOICE_DATE'
    || ','
    || 'AMOUNT'
    || ','
    || 'UNIQUE_ID'
    || ','
    || 'DATE_INVOICE_ENTERED'
    || ','
    || 'DATE_INVOICE_PAID'
    || ','
    || 'USER_ID'
    || ','
    || 'PAYMENT_STATUS_FLAG'
    || ','
    || 'DOC_TYPE'
    || ','
    || 'DESCRIPTION'
    || ','
    || 'PAYMENT_AMOUNT'
    UTL_FILE.put_line (v_file,
    'SUPPLIERREF'
    || ','
    || 'SUPPLIERNAME'
    || ','
    || 'INVOICENUMBER'
    || ','
    || 'DATE'
    || ','
    || 'AMOUNT'
    || ','
    || 'UNIQUEID'
    || ','
    || 'DATEINVOICEENTERED'
    || ','
    || 'DATEINVOICEPAID'
    || ','
    || 'USERID'
    || ','
    || 'PAYMENTSTATUS'
    || ','
    || 'DOCTYPE'
    || ','
    || 'DESCRIPTION'
    || ','
    || 'PAYMENTAMOUNT');
    UTL_FILE.put_line (v_file,
    'XX'
    || ','
    || 'XX'
    || ','
    || 'XX'
    || ','
    || 'XX'
    || ','
    || 'XX'
    || ','
    || 'XX'
    || ','
    || 'XX'
    || ','
    || 'XX'
    || ','
    || 'XX'
    || ','
    || 'XX'
    || ','
    || 'XX'
    || ','
    || 'XX'
    || ','
    || 'XX');
                             open get_ap_data_inv;
                             loop
                             fetch get_ap_data_inv bulk collect into xxc_tbl1 limit 6000;
    fnd_file.put_line(fnd_file.log, 'Cursor Count is : '||xxc_tbl1.count);
                             for i in xxc_tbl1.first .. xxc_tbl1.count
    --FOR cur_rec IN get_ap_data_inv
    LOOP
    BEGIN
    --Common package used for proper sequence for Record_id and Bath_id
    l_sucess_count := l_sucess_count + 1;
    --Insert into CSV file
    fnd_file.put_line (fnd_file.LOG, 'Before Utl file');
    UTL_FILE.put_line (v_file,
    xxc_tbl1(i).supplier_ref
    || ','
    || xxc_tbl1(i).supplier_name
    || ','
    || xxc_tbl1(i).invoice_number
    || ','
    || xxc_tbl1(i).invoice_date
    || ','
    || xxc_tbl1(i).amount
    || ','
    || xxc_tbl1(i).unique_id
    || ','
    || xxc_tbl1(i).date_invoice_entered
    || ','
    || xxc_tbl1(i).date_invoice_paid
    || ','
    || xxc_tbl1(i).user_id
    || ','
    || xxc_tbl1(i).payment_status_flag
    || ','
    || xxc_tbl1(i).doc_type
    || ','
    || xxc_tbl1(i).description
    || ','
    || xxc_tbl1(i).gross_amount);
    fnd_file.put_line (fnd_file.LOG,
    'Supplier Reference : ' || xxc_tbl1(i).supplier_ref);
    xxc_common_int_pk.insert_audit
    (p_batch_id => l_batch_id,
    p_request_id => l_request_id,
    p_source_system => l_source,
    p_proc_name => l_proc_name,
    p_log_type => l_log_type,
    p_det_status => l_det_status_complete,
    p_msg_code => NULL,
    p_entity => NULL,
    p_msg_desc => 'Inserting records from AP to Fiscal Successfully',
    p_mast_request_id => l_request_id,
    p_record_id => NULL,
    p_source => l_source,
    p_target => l_target,
    p_email => NULL,
    p_mod_code => l_mod_code,
    p_audit_master_id => l_audit_master_id
    EXCEPTION
    WHEN OTHERS
    THEN
    l_error_count := l_error_count + 1;
    fnd_file.put_line (fnd_file.LOG,
    'Error While Inserting from AP to Fiscal '
    || SQLERRM);
    -- Create audit log for AP Inv records insert Exception
    --Insert into the Audit table XXC_COMM_AUDIT_DETAIL_LOG and XXC_COMM_AUDIT_MASTER_LOG
    xxc_common_int_pk.insert_audit
    (p_batch_id => l_batch_id,
    p_request_id => l_request_id,
    p_source_system => l_source,
    p_proc_name => l_proc_name,
    p_log_type => l_log_type,
    p_det_status => l_det_status_rejected,
    p_msg_code => NULL,
    p_entity => NULL,
    p_msg_desc => 'Error While Inserting from AP to Fiscal',
    p_mast_request_id => l_request_id,
    p_record_id => NULL,
    p_source => l_source,
    p_target => l_target,
    p_email => NULL,
    p_mod_code => l_mod_code,
    p_audit_master_id => l_audit_master_id
    END;
    END LOOP;
    exit when get_ap_data_inv%NOTFOUND;
    end loop;
         close get_ap_data_inv;
    UTL_FILE.fclose (v_file);
    UTL_FILE.fcopy (l_location,
    l_filename,
    l_archive_location,
    l_filename
    -- Create audit log for Successfully processed records
    -- Procedure call to insert in Audit tables
    xxc_common_int_pk.insert_audit
    (p_batch_id => l_batch_id,
    p_request_id => l_request_id,
    p_source_system => l_source,
    p_proc_name => l_proc_name,
    p_log_type => l_log_type,
    p_det_status => l_det_status_complete,
    p_msg_code => NULL,
    p_entity => NULL,
    p_msg_desc => 'Compeleted Sucessfully AP to Fiscal',
    p_mast_request_id => l_request_id,
    p_record_id => NULL,
    p_source => l_source,
    p_target => l_target,
    p_email => NULL,
    p_mod_code => l_mod_code,
    p_audit_master_id => l_audit_master_id
    --Insert into the Audit table XXC_COMM_AUDIT_DETAIL_LOG and XXC_COMM_AUDIT_MASTER_LOG for populating email drop table
    BEGIN
    SELECT transaction_status
    INTO p_status
    FROM xxc_comm_audit_master_log
    WHERE audit_master_id = l_audit_master_id;
    EXCEPTION
    WHEN OTHERS
    THEN
    xxc_common_int_pk.insert_audit (p_batch_id => l_batch_id,
    p_request_id => l_request_id,
    p_source_system => l_source,
    p_proc_name => l_proc_name,
    p_log_type => l_log_type,
    p_det_status => l_det_status_err,
    p_msg_code => NULL,
    p_entity => NULL,
    p_msg_desc => 'Status Error',
    p_mast_request_id => l_request_id,
    p_record_id => NULL,
    p_source => l_source,
    p_target => l_target,
    p_email => NULL,
    p_mod_code => l_mod_code,
    p_audit_master_id => l_audit_master_id
    END;
    IF p_status <> 0
    THEN
    xxc_comm_audit_log_pk.populate_email_drop_table (l_audit_master_id,
    l_batch_id);
    END IF;
    EXCEPTION
    WHEN UTL_FILE.invalid_path
    THEN
    UTL_FILE.fclose (v_file);
    raise_application_error (-20000, 'File location is invalid.');
    WHEN UTL_FILE.invalid_mode
    THEN
    UTL_FILE.fclose (v_file);
    raise_application_error (-20001,
    'The open_mode parameter in FOPEN is invalid.');
    WHEN UTL_FILE.invalid_filehandle
    THEN
    UTL_FILE.fclose (v_file);
    raise_application_error (-20002, 'File handle is invalid.');
    WHEN UTL_FILE.invalid_operation
    THEN
    UTL_FILE.fclose (v_file);
    raise_application_error
    (-20003,
    'File could not be opened or operated on as requested.');
    WHEN UTL_FILE.write_error
    THEN
    UTL_FILE.fclose (v_file);
    raise_application_error
    (-20005,
    'Operating system error occurred during the write operation.');
    WHEN UTL_FILE.file_open
    THEN
    UTL_FILE.fclose (v_file);
    raise_application_error
    (-20008,
    'The requested operation failed because the file is open.');
    WHEN UTL_FILE.invalid_maxlinesize
    THEN
    UTL_FILE.fclose (v_file);
    raise_application_error
    (-20009,
    'The MAX_LINESIZE value for FOPEN() is invalid; it should '
    || 'be within the range 1 to 32767.');
    COMMIT;
    ROLLBACK TO data_extract;
    WHEN OTHERS
    THEN
    raise_application_error (-20045, SQLERRM);
    UTL_FILE.fclose (v_file);
    END xxc_mod_068_ap_pr;
    END xxc_mod_in_068_ap_to_fis_pkg;
    Show Errors
    Iam implemented BULK collect concept in programe,can anyone please suggest how can I imporve performance....
    Thanks,
    Rakesh

      CREATE OR REPLACE PACKAGE BODY "XXC"."XXC_MOD_IN_068_AP_TO_FIS_PKG"
    AS
      PROCEDURE xxc_mod_068_ap_pr (
        p_errbuf                         OUT      VARCHAR2,
        p_retcode                        OUT      NUMBER,
        p_start_date                     IN       VARCHAR2,
        p_end_date                       IN       VARCHAR2
      IS
        -- Define variables and assign default values
        l_sucess_count                          NUMBER := 0;
        l_error_count                           NUMBER := 0;
        -- Standard declaration
        l_source                                VARCHAR2 (10);
        l_target                                VARCHAR2 (10);
        lc_module_description                   VARCHAR2 (50)
                                                     := 'MOD_IN_068 - AP to Fiscal';
        l_status                       CONSTANT VARCHAR2 (50) := 'NEW';
        p_status                                NUMBER;
        l_batch_id                              NUMBER;
        l_batch_id_next                         NUMBER
                                             := apps_common_out_batch_id_s1.NEXTVAL;
        l_proc_name                             VARCHAR2 (100) := 'XXC_MOD_IN_068';
        l_request_id                            NUMBER
                                                      := fnd_global.conc_request_id;
        l_audit_master_id                       NUMBER := NULL;
        l_mod_code                              VARCHAR2 (100);
        l_log_type                              NUMBER := 1;   --INFORMATION
        l_det_status_success                    NUMBER := 0;   --SUCCESS
        l_det_status_inprocess                  NUMBER := 3;   --INPROCESS
        l_det_status_rejected                   NUMBER := 4;   --REJECTED
        l_det_status_err                        NUMBER := 3;   --Error
        l_det_status_complete                   NUMBER := 9;   --COMPLETE
        -- Standard who Columns
        l_created_by                            NUMBER := fnd_global.user_id;
        l_creation_date                         DATE := SYSDATE;
        l_last_update_date                      DATE := SYSDATE;
        l_last_update_login                     NUMBER := fnd_global.user_id;
        v_file                                  UTL_FILE.file_type;
        l_location                              VARCHAR2 (150);
        l_archive_location                      VARCHAR2 (150);
        l_date                                  VARCHAR2 (50);
        l_filename                              VARCHAR2 (50);
        l_open_mode                             VARCHAR2 (1) := 'W';
    --- l_max_linesize                          NUMBER := 32767;
        l_max_linesize                          VARCHAR2 (150); -- Updated 09-Nov-2012
        --Cursor is used to fetch valid records for the interface
        CURSOR get_ap_data_inv
        IS
          SELECT       asp.segment1 supplier_ref,
                 -- asp.vendor_name supplier_name,
                 replace(asp.vendor_name, ',', ' ') supplier_name,
                 --aia.invoice_num invoice_number,
                 replace(aia.invoice_num, ',','') invoice_number,
                 aia.invoice_date,
                 aia.invoice_amount amount,
                 aia.doc_sequence_value unique_id,
                 aia.creation_date date_invoice_entered,
                 apsa.due_date date_invoice_paid,
                 aia.SOURCE user_id,
                 aia.payment_status_flag,
                 aia.invoice_type_lookup_code doc_type,
                 --aia.description,
                 replace(aia.description, ',' , ' ') description,
                 apsa.gross_amount
          FROM   ap_invoices_all aia,
                 ap_suppliers asp,
                 apps.ap_payment_schedules_all apsa
                -- apps.iby_payments_all iba,
            --     apps.iby_docs_payable_all dp
          WHERE  aia.invoice_id = apsa.invoice_id
          AND    aia.vendor_id  = asp.vendor_id
          AND    aia.org_id     = apsa.org_id
      --  AND    apsa.payment_status_flag != 'Y'   -- commented for CR
      --  AND    dp.payment_id = iba.payment_id(+)
      --  AND    aia.invoice_id = dp.calling_app_doc_unique_ref2(+)
      --  AND    apsa.due_date <= (SYSDATE + 1)
          AND    TRUNC (aia.creation_date)
                   BETWEEN NVL (fnd_date.canonical_to_date (p_start_date),
                                TRUNC (aia.creation_date))
                       AND NVL (fnd_date.canonical_to_date (p_end_date),
                                TRUNC (aia.creation_date));
                                     TYPE xxc_tbl IS TABLE OF get_ap_data_inv%ROWTYPE;
                                  xxc_tbl1 xxc_tbl;
      BEGIN
        l_batch_id                      := apps_common_out_batch_id_s1.CURRVAL;
        xxc_common_int_pk.insert_audit (p_batch_id                        => l_batch_id,
                                        p_request_id                      => l_request_id,
                                        p_source_system                   => l_source,
                                        p_proc_name                       => l_proc_name,
                                        p_log_type                        => l_log_type,
                                        p_det_status                      => l_det_status_inprocess,
                                        p_msg_code                        => NULL,
                                        p_entity                          => NULL,
                                        p_msg_desc                        => 'Process Starts',
                                        p_mast_request_id                 => l_request_id,
                                        p_record_id                       => NULL,
                                        p_source                          => l_source,
                                        p_target                          => l_target,
                                        p_email                           => NULL,
                                        p_mod_code                        => l_mod_code,
                                        p_audit_master_id                 => l_audit_master_id
    -- Get Module Code
        BEGIN
          SELECT TRIM (fval.flex_value),
                 TRIM (SUBSTR (fval.description,
                               1,
                               INSTR (fval.description, ' -')
          INTO   l_source,
                 l_mod_code
          FROM   fnd_flex_values_vl fval, fnd_flex_value_sets vset
          WHERE  vset.flex_value_set_id = fval.flex_value_set_id
          AND    vset.flex_value_set_name IN ('XXC_COMM_INT_CONFIG')
          AND    fval.enabled_flag = 'Y'
          AND    fval.description = lc_module_description;
        EXCEPTION
          WHEN OTHERS
          THEN
            xxc_common_int_pk.insert_audit (p_batch_id                        => l_batch_id,
                                            p_request_id                      => l_request_id,
                                            p_source_system                   => l_source,
                                            p_proc_name                       => l_proc_name,
                                            p_log_type                        => l_log_type,
                                            p_det_status                      => l_det_status_err,
                                            p_msg_code                        => NULL,
                                            p_entity                          => NULL,
                                            p_msg_desc                        => 'Error Mode Code',
                                            p_mast_request_id                 => l_request_id,
                                            p_record_id                       => NULL,
                                            p_source                          => l_source,
                                            p_target                          => l_target,
                                            p_email                           => NULL,
                                            p_mod_code                        => l_mod_code,
                                            p_audit_master_id                 => l_audit_master_id
            raise_application_error (-20045, SQLERRM);
        END;
    --File Location Path for OutPut File
        BEGIN
          SELECT fnd_profile.VALUE ('XXC_MOD_IN_068_AP_OUTBOUND'),
                 fnd_profile.VALUE ('XXC_MOD_IN_068_AP_ARCHIVE')
          INTO   l_location,
                 l_archive_location
          FROM   DUAL;
        EXCEPTION
          WHEN OTHERS
          THEN
            xxc_common_int_pk.insert_audit
                                          (p_batch_id                        => l_batch_id,
                                           p_request_id                      => l_request_id,
                                           p_source_system                   => l_source,
                                           p_proc_name                       => l_proc_name,
                                           p_log_type                        => l_log_type,
                                           p_det_status                      => l_det_status_rejected,
                                           p_msg_code                        => NULL,
                                           p_entity                          => NULL,
                                           p_msg_desc                        => 'Profile Value not found',
                                           p_mast_request_id                 => l_request_id,
                                           p_record_id                       => NULL,
                                           p_source                          => l_source,
                                           p_target                          => l_target,
                                           p_email                           => NULL,
                                           p_mod_code                        => l_mod_code,
                                           p_audit_master_id                 => l_audit_master_id
        END;
        BEGIN
          SELECT TO_CHAR (SYSDATE, 'YYYYMMDDhh24miss')
          INTO   l_date
          FROM   DUAL;
        EXCEPTION
          WHEN OTHERS
          THEN
            xxc_common_int_pk.insert_audit (p_batch_id                        => l_batch_id,
                                            p_request_id                      => l_request_id,
                                            p_source_system                   => l_source,
                                            p_proc_name                       => l_proc_name,
                                            p_log_type                        => l_log_type,
                                            p_det_status                      => l_det_status_rejected,
                                            p_msg_code                        => NULL,
                                            p_entity                          => NULL,
                                            p_msg_desc                        => 'status not found',
                                            p_mast_request_id                 => l_request_id,
                                            p_record_id                       => NULL,
                                            p_source                          => l_source,
                                            p_target                          => l_target,
                                            p_email                           => NULL,
                                            p_mod_code                        => l_mod_code,
                                            p_audit_master_id                 => l_audit_master_id
        END;
        l_filename                      := 'AP_Fiscal_' || l_date || '.csv';
        v_file                          :=
          UTL_FILE.fopen (LOCATION                          => l_location,
                          filename                          => l_filename,
                          open_mode                         => l_open_mode,
                          max_linesize                      => l_max_linesize
                           -- Changed as per Sarah's email on 9th Decemeber
        /* UTL_FILE.put_line (v_file,
                               'SUPPLIER_REF'
                            || ','
                            || 'SUPPLIER_NAME'
                            || ','
                            || 'INVOICE_NUMBER'
                            || ','
                            || 'INVOICE_DATE'
                            || ','
                            || 'AMOUNT'
                            || ','
                            || 'UNIQUE_ID'
                            || ','
                            || 'DATE_INVOICE_ENTERED'
                            || ','
                            || 'DATE_INVOICE_PAID'
                            || ','
                            || 'USER_ID'
                            || ','
                            || 'PAYMENT_STATUS_FLAG'
                            || ','
                            || 'DOC_TYPE'
                            || ','
                            || 'DESCRIPTION'
                            || ','
                            || 'PAYMENT_AMOUNT'
        UTL_FILE.put_line (v_file,
                              'SUPPLIERREF'
                           || ','
                           || 'SUPPLIERNAME'
                           || ','
                           || 'INVOICENUMBER'
                           || ','
                           || 'DATE'
                           || ','
                           || 'AMOUNT'
                           || ','
                           || 'UNIQUEID'
                           || ','
                           || 'DATEINVOICEENTERED'
                           || ','
                           || 'DATEINVOICEPAID'
                           || ','
                           || 'USERID'
                           || ','
                           || 'PAYMENTSTATUS'
                           || ','
                           || 'DOCTYPE'
                           || ','
                           || 'DESCRIPTION'
                           || ','
                           || 'PAYMENTAMOUNT');
        UTL_FILE.put_line (v_file,
                              'XX'
                           || ','
                           || 'XX'
                           || ','
                           || 'XX'
                           || ','
                           || 'XX'
                           || ','
                           || 'XX'
                           || ','
                           || 'XX'
                           || ','
                           || 'XX'
                           || ','
                           || 'XX'
                           || ','
                           || 'XX'
                           || ','
                           || 'XX'
                           || ','
                           || 'XX'
                           || ','
                           || 'XX'
                           || ','
                           || 'XX');
                                open get_ap_data_inv;
                                loop
                                fetch get_ap_data_inv bulk collect into xxc_tbl1 limit 6000;
                 fnd_file.put_line(fnd_file.log, 'Cursor Count is : '||xxc_tbl1.count);
                                for i in xxc_tbl1.first .. xxc_tbl1.count
        --FOR cur_rec IN get_ap_data_inv
        LOOP
          BEGIN
            --Common package used for proper sequence for Record_id and Bath_id
            l_sucess_count                  := l_sucess_count + 1;
            --Insert into CSV file
            fnd_file.put_line (fnd_file.LOG, 'Before Utl file');
            UTL_FILE.put_line (v_file,
                                  xxc_tbl1(i).supplier_ref
                               || ','
                               || xxc_tbl1(i).supplier_name
                               || ','
                               || xxc_tbl1(i).invoice_number
                               || ','
                               || xxc_tbl1(i).invoice_date
                               || ','
                               || xxc_tbl1(i).amount
                               || ','
                               || xxc_tbl1(i).unique_id
                               || ','
                               ||  xxc_tbl1(i).date_invoice_entered
                               || ','
                               ||  xxc_tbl1(i).date_invoice_paid
                               || ','
                               ||  xxc_tbl1(i).user_id
                               || ','
                               ||  xxc_tbl1(i).payment_status_flag
                               || ','
                               ||  xxc_tbl1(i).doc_type
                               || ','
                               ||  xxc_tbl1(i).description
                               || ','
                               ||  xxc_tbl1(i).gross_amount);
            fnd_file.put_line (fnd_file.LOG,
                               'Supplier Reference : ' ||  xxc_tbl1(i).supplier_ref);
            xxc_common_int_pk.insert_audit
                  (p_batch_id                        => l_batch_id,
                   p_request_id                      => l_request_id,
                   p_source_system                   => l_source,
                   p_proc_name                       => l_proc_name,
                   p_log_type                        => l_log_type,
                   p_det_status                      => l_det_status_complete,
                   p_msg_code                        => NULL,
                   p_entity                          => NULL,
                   p_msg_desc                        => 'Inserting records from AP to Fiscal Successfully',
                   p_mast_request_id                 => l_request_id,
                   p_record_id                       => NULL,
                   p_source                          => l_source,
                   p_target                          => l_target,
                   p_email                           => NULL,
                   p_mod_code                        => l_mod_code,
                   p_audit_master_id                 => l_audit_master_id
          EXCEPTION
            WHEN OTHERS
            THEN
              l_error_count                   := l_error_count + 1;
              fnd_file.put_line (fnd_file.LOG,
                                    'Error While Inserting from AP to Fiscal '
                                 || SQLERRM);
                 -- Create audit log for AP Inv records insert Exception
              --Insert into the Audit table XXC_COMM_AUDIT_DETAIL_LOG and XXC_COMM_AUDIT_MASTER_LOG
              xxc_common_int_pk.insert_audit
                           (p_batch_id                        => l_batch_id,
                            p_request_id                      => l_request_id,
                            p_source_system                   => l_source,
                            p_proc_name                       => l_proc_name,
                            p_log_type                        => l_log_type,
                            p_det_status                      => l_det_status_rejected,
                            p_msg_code                        => NULL,
                            p_entity                          => NULL,
                            p_msg_desc                        => 'Error While Inserting from AP to Fiscal',
                            p_mast_request_id                 => l_request_id,
                            p_record_id                       => NULL,
                            p_source                          => l_source,
                            p_target                          => l_target,
                            p_email                           => NULL,
                            p_mod_code                        => l_mod_code,
                            p_audit_master_id                 => l_audit_master_id
          END;
        END LOOP;
         exit when get_ap_data_inv%NOTFOUND;
        end loop;
         close get_ap_data_inv;
        UTL_FILE.fclose (v_file);
        UTL_FILE.fcopy (l_location,
                        l_filename,
                        l_archive_location,
                        l_filename
          -- Create audit log for Successfully processed records
        -- Procedure call to insert in Audit tables
        xxc_common_int_pk.insert_audit
                               (p_batch_id                        => l_batch_id,
                                p_request_id                      => l_request_id,
                                p_source_system                   => l_source,
                                p_proc_name                       => l_proc_name,
                                p_log_type                        => l_log_type,
                                p_det_status                      => l_det_status_complete,
                                p_msg_code                        => NULL,
                                p_entity                          => NULL,
                                p_msg_desc                        => 'Compeleted Sucessfully AP to Fiscal',
                                p_mast_request_id                 => l_request_id,
                                p_record_id                       => NULL,
                                p_source                          => l_source,
                                p_target                          => l_target,
                                p_email                           => NULL,
                                p_mod_code                        => l_mod_code,
                                p_audit_master_id                 => l_audit_master_id
        --Insert into the Audit table XXC_COMM_AUDIT_DETAIL_LOG and XXC_COMM_AUDIT_MASTER_LOG for populating email drop table
        BEGIN
          SELECT transaction_status
          INTO   p_status
          FROM   xxc_comm_audit_master_log
          WHERE  audit_master_id = l_audit_master_id;
        EXCEPTION
          WHEN OTHERS
          THEN
            xxc_common_int_pk.insert_audit (p_batch_id                        => l_batch_id,
                                            p_request_id                      => l_request_id,
                                            p_source_system                   => l_source,
                                            p_proc_name                       => l_proc_name,
                                            p_log_type                        => l_log_type,
                                            p_det_status                      => l_det_status_err,
                                            p_msg_code                        => NULL,
                                            p_entity                          => NULL,
                                            p_msg_desc                        => 'Status Error',
                                            p_mast_request_id                 => l_request_id,
                                            p_record_id                       => NULL,
                                            p_source                          => l_source,
                                            p_target                          => l_target,
                                            p_email                           => NULL,
                                            p_mod_code                        => l_mod_code,
                                            p_audit_master_id                 => l_audit_master_id
        END;
        IF p_status <> 0
        THEN
          xxc_comm_audit_log_pk.populate_email_drop_table (l_audit_master_id,
                                                           l_batch_id);
        END IF;
      EXCEPTION
        WHEN UTL_FILE.invalid_path
        THEN
          UTL_FILE.fclose (v_file);
          raise_application_error (-20000, 'File location is invalid.');
        WHEN UTL_FILE.invalid_mode
        THEN
          UTL_FILE.fclose (v_file);
          raise_application_error (-20001,
                                   'The open_mode parameter in FOPEN is invalid.');
        WHEN UTL_FILE.invalid_filehandle
        THEN
          UTL_FILE.fclose (v_file);
          raise_application_error (-20002, 'File handle is invalid.');
        WHEN UTL_FILE.invalid_operation
        THEN
          UTL_FILE.fclose (v_file);
          raise_application_error
                           (-20003,
                            'File could not be opened or operated on as requested.');
        WHEN UTL_FILE.write_error
        THEN
          UTL_FILE.fclose (v_file);
          raise_application_error
                     (-20005,
                      'Operating system error occurred during the write operation.');
        WHEN UTL_FILE.file_open
        THEN
          UTL_FILE.fclose (v_file);
          raise_application_error
                        (-20008,
                         'The requested operation failed because the file is open.');
        WHEN UTL_FILE.invalid_maxlinesize
        THEN
          UTL_FILE.fclose (v_file);
          raise_application_error
                    (-20009,
                        'The MAX_LINESIZE value for FOPEN() is invalid; it should '
                     || 'be within the range 1 to 32767.');
          COMMIT;
          ROLLBACK TO data_extract;
        WHEN OTHERS
        THEN
          raise_application_error (-20045, SQLERRM);
          UTL_FILE.fclose (v_file);
      END xxc_mod_068_ap_pr;
    END xxc_mod_in_068_ap_to_fis_pkg;Please verify...

  • Need to generate the excel file with diffrent sheets using utl_file package

    Hi,
    Sorry for previous message in which I had missed the usage of " UTL_FILE " package
    I need to generate the excel file with diffrent sheets . Currently I am generating the data in three diffrent excel files using
    " UTL_File " package and my requirement is to generate this in a single excel file with diffrent sheets.
    Please help on this
    Thanks & Regards,
    Krishna Vyavahare

    Hello 10866107,
    at Re: How to save a query result and export it to, say excell? you can find links to different solutions. At least the packages behind second and fourth link support more than one worksheet.
    Regards
    Marcus

  • Export query results to a CSV file

    Hi,
    My requirement is I need to export the results of a query to a CSV file. Can anyone please suggest a way to include the column names also in the CSV file?
    Thanks in advance.
    Annie

    Following code is from asktom. I have modified to include column heading. This will get your desired CSV file for a given query.
    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;
         l_colDesc          dbms_sql.DESC_TAB;
    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);
         dbms_sql.describe_columns(l_theCursor,l_colCnt, l_colDesc);
         l_separator := '';
         for lColCnt in 1..l_colCnt
         loop          
                utl_file.put( l_output, l_separator ||  '"' || Upper(l_colDesc(lColCnt).col_name) || '"');
                   l_separator := p_separator;
         end loop;
         utl_file.new_line( l_output );
        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;The original link is below.
    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:95212348059
    Thanks,
    Karthick.

  • UTL_FILE Usage

    I am working in the following Oracle environment:
    Oracle Database 11g Enterprise Edition Release 11.2.0.2.0
    Unix: Solaris Sunsparc 10
    Oracle Financials: 12.1.3
    I defined a stored procedure seen below.  I am trying to create a CSV file and write it to a directory on my C: drive (ultimately in a UNIX directory)  I can't issue a CREATE DIRECTORY from within the stored procedure (or can I) so how do I specify the path to the directory c;\? What avialable paths do I have from Windows 2007?
    create or replace
    Procedure ZZAP_REMEDY_EXPORT_PROC
    (P_Folder_Name In Varchar2
    ,P_File_name In Varchar2 
    AS
    --    F := UTL_FILE.FOPEN('MYCSV','REMEDY_AP_EXPORT.CSV','w',32767);
    ---Declare
       Exp_A Exception;
       Errbuf Varchar2(120);
       V_Errloc VARCHAR2(120);Count number;
       Retcode Varchar2(120);
       Counter Number;
       F UTL_FILE.FILE_TYPE;
    Begin
        Counter := 0;
        F := Utl_File.Fopen('MYCSV','REMEDY_AP_EXPORT.CSV','w',32767);
    --    F := UTL_FILE.FOPEN('MYCSV','REMEDY_AP_EXPORT.CSV','w',32767);
        Loop
            Utl_File.Put(F,'123456');
            Utl_File.Put(F,',A' );
            Utl_File.Put(F,',1050 MAIN' );
            Utl_File.Put(F,',BRONX' );
            UTL_FILE.PUT(F,',NY' );
            Utl_File.New_Line(F);
            Exit When Counter = 10;
            counter := counter + 1;
        END LOOP;
        Utl_File.Fclose(F);
    Exception
    WHEN OTHERS THEN
       errbuf := 'Error:- ' || SQLCODE ||' '|| SUBSTR(SQLERRM, 1, 950) ;
       Fnd_File.Put_Line(Fnd_File.Log, 'Exception -> Err Code: ' || To_Char(Sqlcode) || '(' || Rtrim(Sqlerrm) || ') occured in procedure Inactivate item at location '|| V_Errloc);
       Retcode := 2;
    End Zzap_Remedy_Export_Proc;

    UTL_FILE can only create files on the database server.
    In SQL Developer, you can run a query, fetch the results, and then tell SQL Developer to write them to a CSV file on your local drive.  It's not obvious to me why you would want to do that, though, since obviously your code may be quite different from the code SQL Developer uses to write the file.  And it would seem easier to review the results of your query in SQL Developer rather than writing it to a separate file just to use some other tool to open the file.  Perhaps you want SQL Developer to write an XLS[X] file of results that you can then use Excel to view?
    Justin

Maybe you are looking for

  • How to get a serial number without a registration or redemption/product code?

    I downloaded Adobe CS6 last fall from IUWare (Indiana University's online software store). At that time I had Windows 8, which I loved. I recently updated to Windows 8.1 and am wanting to go back to Windows 8. To do this, I need to reinstall all of t

  • How to create Source System in BI 7.0

    Hi Experts, How to create Source System in BI 7.0, please urgent Thanks

  • Convert from component cable to Stereo A/V + S-video for AppleTV

    Hello, We are looking for a converter cable, box, hub that will convert from component cable (red/blue/green) to Stereo A/V + S-video. We are hooking up a AppleTV box to an older Sony WEGA TV. Anyone heard of such a product or work around? We have no

  • Financial Analytics Implementation

    Hi guys I am looking for generic implementation plans for Financial Analytics to validate the assumption the product can be installed in around 3 months. Any assistance would be greatly appreciated.

  • Long list of presets.

    The long list of Presets in Grid Mode are useless to me. I only ever use two that I have made. One for basic import, and one for B&W. I would like to be able to delete all the long list of built in ones. Or have a toggle switch as in Develop to hide