UTL_FILE + query

Hi guys.
I'm really newbie in procedures.

I'm 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);


Nom_repertoire varchar2 (40): = "UTF_DIR";
File_name varchar2 (40): = "myfile.txt";
Start

FILE_HANDLE: = utl_file.fopen(DIR_NAME,FILE_NAME,'W');

UTL_FILE.put_line (FILE_HANDLE, ' audit and test');

cursor CUR_EMISOR is
SELECT user name,
extended_timestamp,
owner,
obj_name,
action_name,
sql_text
OF 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'm trying to get the query results and put it on a .txt file.

Could someone gimme a hint?

Thank you!

BrunoSales wrote:
Hello
Like I said in the last post:

I have access on the table, and normally I can do this query. I have dba privileges.

Thank you

acquired through ROLE privileges are NOT applicable within the named PL/SQL procedures.

It takes a direct SUBSIDY on the object.

Tags: Database

Similar Questions

  • Verify the existence of the file on the disk does not not (utl_file.fgetattr)

    Hello

    With the help of 11.2.0.3 and have the following code in an attempt to verify the existence of the file.

    Directory and file are certainly and user/schema was the allowance all the specfifed directory for them.

    Another thing to do?

    Wjen, run it says file does not exist - I tried uppare and tiny.

    declare

    v_file_exists BOOLEAN;

    v_file_length NUMBER;

    v_block_size NUMBER;

    Start

    -Create a process to load data to archive

    -A process necessary to run on a regular basis to query the datain.txt_finance_gl table. If an error is triggered which shows that the file is not found then it stops and expected to run next time.

    -If the data is returned, then the data can be queried and loaded into the table in the archive with the relevant number of sequence and datestamp.

    -The txt_load_control will be used to control and verify the transfer.

    -The next sequence in the txt_finance_gl_seq number is obtained as well as current datetime object and create a new entry in the control panel (edc_type will be "GL") and give a working state.

    -At the end of the load, the flat file will be renamed (pre-fixing on the old name, sequence number) and moved to the processed Finance folder.

    -The control panel can then be updated to show the run as it is complete.

    -First check to see if the file already exists on the disk in the box provided.

    UTL_FILE.fgetattr ('big_tab_data', 'testfile', v_file_exists, v_file_length, v_block_size);

    IF v_file_exists THEN

    dbms_output.put_line ("'File Exists");

    ON THE OTHER

    dbms_output.put_line ('file does not exist');

    END IF;

    end;

    user5716448 wrote:

    Location was just prove that the oracle schema user can see the directory and database files.

    create or replace directory BIP_TAB_DATA

    as ' / oracle/finance/export ";

    give all the BIP_TAB_DATA of archiving directory;

    declare

    v_file_exists BOOLEAN;

    v_file_length NUMBER;

    v_block_size NUMBER;

    Start

    UTL_FILE.fgetattr ("BIG_TAB_DATA", "samplefile", v_file_exists, v_file_length, v_block_size);

    IF v_file_exists THEN

    dbms_output.put_line ("'File Exists");

    ON THE OTHER

    dbms_output.put_line ('file does not exist');

    END IF;

    end;

    [BEEP] / finance/export-oracle $ sqlplus archive / pwd @por.sql

    SQL * more: Production release 11.2.0.3.0 the sea Mar 4 16:06:12 2015

    Copyright (c) 1982, 2011, Oracle.  All rights reserved.

    Connected to:

    Oracle Database 11 g Enterprise Edition Release 11.2.0.3.0 - 64 bit Production

    With partitioning, OLAP, Data Mining and Real Application Testing options

    18.

    PL/SQL procedure successfully completed.

    SQL > set serveroutput on

    SQL > /.

    File does not exist

    PL/SQL procedure successfully completed.

    SQL >

    [BEEP] / oracle/export/finance $ ls-l

    total 1192

    -rw-rw-rw-1 orabip s/n 152953 16 Feb 14:42 weekly sales (SAP) .txt

    -rw - r - r - 1 orabip s/n 49 Mar 04 13:44 afiedt.buf

    -rw-rw-rw-1 orabip s/n 172280 17 February 14:38 new weekly sales (SAP) .txt

    -rw - r - r - 1 orabip s/n 374 Mar 04 16:05 por

    -rw - r - r - 1 orabip s/n 374 Mar 04 16:07 por.sql

    -rw - r - r - 1 orabip s/n 0 Mar 04 16:04 samplefile

    -rw-rw-rw-1 orabip s/n 172280 17 February 14:38 sap_weekly_gl_data.txt

    -rw - r - r - 1 s/n 55 16 Feb 09:52 testfile.bad orabip

    -rw - r - r - 1 orabip s/n 13535 16 Feb 22:00 testfile.log

    -rw-rw-rw-1 orabip s/n 42-16 Feb 09:53 testfile.txt

    -rw-rw-rw-1 orabip s/n 62908 12 February 16:45 test.txt weekly sales

    [BEEP] / oracle/export/finance $

    These two are not even!

  • How can I extract the data from a csv file and insert it into an Oracle table? (UTL_FILE)

    Hi, please help me whit this query

    Im trying to extrate the data in a file csv and im using the ULT_FILE package
    I have this query that read the file and the first field, but if the field has a different length does not work as it should

    For example if I had this .csv file:

    1, book, laptop

    2, pen, Eraser

    3, notebook, paper

    And in the table, I had to insert like this

    ID descrption1 description2

    laptop 1 book

    Eraser pen 2

    paper laptop 3

    For now, I have this query, which displays only with DBMS:

    Declare

    -Variables

    Cadena VARCHAR2 (32767).

    Vfile UTL_FILE. TYPE_DE_FICHIER;

    Dato varchar2 (200);                                             -Date

    dato1 varchar2 (200);

    dato2 varchar2 (200);

    Identifier varchar2 (5): = ', ';                             -Identifier (en)

    v_ManejadorFichero UTL_FILE. TYPE_DE_FICHIER;     -For exceptions

    -Table variables

    I_STATUS GL_INTERFACE. % OF STATUS TYPE.

    I_LEDGER_ID GL_INTERFACE. TYPE % LEDGER_ID;

    I_USER_JE_SOURCE_NAME GL_INTERFACE. TYPE % USER_JE_SOURCE_NAME;

    I_ACCOUNTING_DATE GL_INTERFACE. TYPE % ACCOUNTING_DATE;

    I_PERIOD_NAME GL_INTERFACE. TYPE % PERIOD_NAME;

    I_CURRENCY_CODE GL_INTERFACE. CURRENCY_CODE % TYPE;

    I_DATE_CREATED GL_INTERFACE. DATE_CREATED % TYPE;

    I_CREATED_BY GL_INTERFACE. CREATED_BY % TYPE;

    I_ACTUAL_FLAG GL_INTERFACE. TYPE % ACTUAL_FLAG;

    I_CODE_COMBINATION_ID GL_INTERFACE. TYPE % CODE_COMBINATION_ID;

    I_ENTERED_DR GL_INTERFACE. TYPE % ENTERED_DR;

    I_ENTERED_CR GL_INTERFACE. TYPE % ENTERED_CR;

    I_ACCOUNTED_DR GL_INTERFACE. TYPE % ACCOUNTED_DR;

    I_ACCOUNTED_CR GL_INTERFACE. TYPE % ACCOUNTED_CR;

    I_TRANSACTION_DATE GL_INTERFACE. TRANSACTION_DATE % TYPE;

    I_REFERENCE1 GL_INTERFACE. REFERENCE1% TYPE;

    I_REFERENCE2 GL_INTERFACE. REFERENCE2% TYPE;

    I_REFERENCE3 GL_INTERFACE. REFERENCE3% TYPE;

    I_REFERENCE4 GL_INTERFACE. REFERENCE4% TYPE;

    I_REFERENCE5 GL_INTERFACE. REFERENCE5% TYPE;

    I_REFERENCE10 GL_INTERFACE. REFERENCE10% TYPE;

    I_GROUP_ID GL_INTERFACE. GROUP_ID % TYPE;

    BEGIN

    Vfile: = UTL_FILE. FOPEN ('CAPEX_ENVIO', 'comas.csv', 'R');

    loop

    UTL_FILE. GET_LINE(Vfile,Cadena,32767);

    dato1: = substr (cadena, instr(cadena, identificador,1,1)-1, instr(cadena, identificador,1,1)-1);

    dato2: = substr (cadena, instr (cadena, identifier, 1, 1) + 1, instr(cadena, identificador,3,1)-3);

    dbms_output.put_line (dato1);

    dbms_output.put_line (dato2);

    -The evidence

    -dbms_output.put_line (cadena);

    -dbms_output.put_line (substr (dato, 3, instr(dato, identificador,1,1)-1));

    -dbms_output.put_line (substr (dato, instr (dato, identifier, 1, 2) + 1, instr(dato, identificador,1,1)-1));

    -dbms_output.put_line (substr (cadena, 1, length (cadena)-1));

    end loop;

    UTL_FILE. FCLOSE (Vfile);

    -----------------------------------------------------------------------------------EXCEPTIONS------------------------------------------------------------------------------------------------------------------------------------------------------------

    EXCEPTION

    When no_data_found then

    dbms_output.put_line ('Todo Correcto');

    When utl_file.invalid_path then

    UTL_FILE. FCLOSE (V_ManejadorFichero);

    RAISE_APPLICATION_ERROR (-20060,'RUTA DEL ARCHIVO NULLIFIED: (');)

    WHEN UTL_FILE. INVALID_OPERATION THEN

    UTL_FILE. FCLOSE (V_ManejadorFichero);

    RAISE_APPLICATION_ERROR ('-20061,'EL ARCHIVO NO PUDO SER ABIERTO ");

    WHEN UTL_FILE. INVALID_FILEHANDLE THEN

    UTL_FILE. FCLOSE (V_ManejadorFichero);

    RAISE_APPLICATION_ERROR (-20062, 'INVALIDO MANAGER');

    WHEN UTL_FILE. WRITE_ERROR THEN

    UTL_FILE. FCLOSE (V_ManejadorFichero);

    RAISE_APPLICATION_ERROR (-20063, 'ESCRITURA ERROR');

    WHEN UTL_FILE. INVALID_MODE THEN

    UTL_FILE. FCLOSE (V_ManejadorFichero);

    RAISE_APPLICATION_ERROR (-20064, 'MODO INVALIDO');

    WHEN UTL_FILE. INTERNAL_ERROR THEN

    UTL_FILE. FCLOSE (V_ManejadorFichero);

    RAISE_APPLICATION_ERROR (-20065, 'ERROR INTERNO');

    WHEN UTL_FILE. READ_ERROR THEN

    UTL_FILE. FCLOSE (V_ManejadorFichero);

    RAISE_APPLICATION_ERROR (-20066, 'LECTURA ERORR');

    WHEN UTL_FILE. FILE_OPEN THEN

    UTL_FILE. FCLOSE (V_ManejadorFichero);

    RAISE_APPLICATION_ERROR ('-20067,'EL ARCHIVO ARE ESTA ABIERTO ");

    WHEN UTL_FILE. THEN ACCESS_DENIED

    UTL_FILE. FCLOSE (V_ManejadorFichero);

    RAISE_APPLICATION_ERROR (-20068, 'REFUSED ACCESS');

    WHEN UTL_FILE. DELETE_FAILED THEN

    UTL_FILE. FCLOSE (V_ManejadorFichero);

    RAISE_APPLICATION_ERROR (-20069, 'OPERACIÓN BORRADO FALLO');

    WHEN UTL_FILE. RENAME_FAILED THEN

    UTL_FILE. FCLOSE (V_ManejadorFichero);

    RAISE_APPLICATION_ERROR (-20070, 'OPERATION SOBREESCRITURA FALLO');

    END;

    Hello

    Try something like this:

    POS1: = INSTR (cadena, idntificador, 1, 1);
    POS2: = INSTR (cadena, idntificador, 1, 2);

    ID: = SUBSTR (cadena, 1, pos1 - 1);
    description1: = SUBSTR (cadena, pos1 + 1, (pos2 - pos1)-1);
    Description2: = SUBSTR (cadena, pos2 + 1);

    where pos1 and pos2 are numbers.

    Rather than use UTL_FILE, consider creating an external table.  You won't have to write any PL/SQL, and this means that you won't be tempted to write a bad article of EXCEPTION.

  • Written by UTL_FILE Package

    I write a PL/SQL code to extract data from query select via cursor & write output to a CSV file.

    PL/SQL code is as below.

    serverout Set size 1000000

    Set serveroutput on

    ALTER session set nls_date_format = 'YYYY-MM-DD ";

    CREATE or REPLACE DIRECTORY MY_FILE_DIR AS ' / usr/tmp2;

    DECLARE

    file_name varchar2 (100): = "Emp_Data";

    file utl_file.file_type.

    TYPE no IS RECORD)

    v_empno varchar2 (10),

    v_last_name varchar2 (40)

    );

    cursor PnJD_cur is

    Select employee_number, last_name

    of apps.zshr_employee_v one

    where a.user_person_type = '01'

    and a.EFFECTIVE_END_DATE ='4712-12-31';

    BEGIN

    IF this is PnJD_cur % ISOPEN THEN

    PnJD_cur OPEN;

    ENDIF;

    Look FOR PnJD_cur IN SheikYerbouti;

    While PnJD_cur %

    LOOP

    file: = utl_file.fopen (MY_FILE_DIR, file_name |'.) CSV', 'w');

    UTL_FILE.put (file, emp_rec.v_empno |) ',' ||

    emp_rec.v_last_name

    );

    UTL_FILE.fclose (file);

    -dbms_output.put_line (file: '.) CSV');

    Look FOR PnJD_cur IN SheikYerbouti;

    END LOOP;

    END;

    I believe that this code "beautifully" written in the csv file, but it didn't. Rather, there was an output like below. In the end, I had to do CTRL + C to stop execution.

    In this regard, any HELP is APPRECIATED. Thank you in advance.

    SQL > @EMP_Personal_Job_Data_Extract1123

    Modified session.

    Created directory.

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49 50

    51

    52

    53

    54

    55 ^ C

    SQL >

    Hey,.

    Instead of TYPE & OPEN, FETCH, CLOSE cursor, try this simple LOOP FOR cursor that is mentioned below, unless you have a specific requirement to use these commands.

    serverout Set size 1000000

    Set serveroutput on

    ALTER session set nls_date_format = 'YYYY-MM-DD ";

    CREATE or REPLACE DIRECTORY MY_FILE_DIR AS ' / usr/tmp2;

    DECLARE

    file_name varchar2 (100): = "Emp_Data";

    file utl_file.file_type.

    cursor PnJD_cur is

    Select employee_number, last_name
    of apps.zshr_employee_v one

    where a.user_person_type = '01'

    and a.EFFECTIVE_END_DATE ='4712-12-31';

    BEGIN

    file: = utl_file.fopen (MY_FILE_DIR, file_name |'.) CSV', 'w');

    FOR v_pnjd IN PnJD_cur

    LOOP

    UTL_FILE.put_line (file, v_pnjd.v_empno |) ',' || v_pnjd.v_last_name);

    END LOOP;

    UTL_FILE.fclose (file);

    END;

    The above code is based on the principle that you want to recover the data and put them into the same file (Emp_Data.csv).

  • Unable to generate the complete file with UTL_FILE

    Hello

    Please refer to the next simple room where I am generating a file on the DB server that should contain 100,000 lines of code.

    declare
    l_fil utl_file.file_type;

    cursor c1 is
    Select *.
    of rats_txtio;

    Start

    l_fil: = utl_file.fopen('SRS_CSD_DIR','rats3.txt','w',32767);

    I'm looping c1
    UTL_FILE.put_line (l_fil, to_char (i.SNO));

    UTL_FILE.fflush (l_fil);

    end loop;

    UTL_FILE.fclose (l_fil);

    end;

    rats_txtio is a table which has sno as one of the columns. The table has 100 thousand records, with sno from 1 and ending with 100000.

    However, after you generate the file, when I display the contents of the file on the server, there only 95123 lines, starting with 1 and ending with 95123.

    Let me know, if there is no parameter causing a restriction on the number of lines that can be generated, or is there something missing in the code.

    Thanking you,
    Rocky.

    Can you provide a reproducible test for us case?

    SQL> ed
    Wrote file afiedt.buf
    
      1  declare
      2    l_fil utl_file.file_type;
      3    cursor c1 is
      4    select rownum as sno
      5    from dual
      6    connect by rownum <= 100000;
      7  begin
      8    l_fil := utl_file.fopen('TEST_DIR','rats3.txt','w',32767);
      9    for i in c1 loop
     10      utl_file.put_line(l_fil,to_char(i.sno));
     11      utl_file.fflush(l_fil);
     12    end loop;
     13    utl_file.fclose(l_fil);
     14* end;
    SQL> /
    
    PL/SQL procedure successfully completed.
    
    SQL>
    

    When I open this file in word and examine the properties it tells me there are 100,000 lines.

    Looks ok to me. What you do differently?

    How do you count the number of rows returned by your query?
    How do you count the number of lines in the file?

  • UTL_FILE.fcopy does not work as expected after the upgrade to 10g

    Hi all, I have an Oracle database running in HP - UX 11.31. The database version is 10.2.0.5.0 and it is patched with PSUOct2011_12827745. This database has been actually upgraded to version 10.2.0.4 (no group of hotfixes) on 13 - Dec last year.

    There is a procedure in the database that reads the contents of a directory, and if there are files in this directory, the contents of the file will be read and inserted in the database. After that, the procedure will move the file to another location for archiving purpose. I will summarize below on the procedure:
    Source directory: /home/.../DB_Upload
    Source Dir name: SRC_DIR
    Destination directory: /home/.../DB_Upload/Archive
    Name of destination Dir: DEST_DIR

    Before upgrading the database, the procedure works very well. Since I upgraded to 10.2.0.5 + PSUOCt2011, the procedure still works as expected, but the file in the destination folder becomes 0 bytes, although initially the file from the source directory is nonzero bytes. The procedure contains the following lines which makes the move from the source to the destination file:
    UTL_FILE.fcopy ('SRC_DIR', 'file', 'DEST_DIR', 'file');
    UTL_FILE.fremove ('SRC_DIR', 'file');
    I tried running only the function fcopy by running the query below and I get the same result:
    exec utl_file.fcopy ('SRC_DIR', 'file', 'DEST_DIR', 'file');
    The weird part is that the procedure completed successfully, and no error message only appears. Even alert logs don't show any errors in this procedure.

    After searching for a solution, I found another method called utl_file.frename (...), which can also be used to move the file, so I decided to try it. Here's what I came up with to test:
    exec utl_file.frename ('SRC_DIR', 'file', 'DEST_DIR', 'file');
    Surprisingly, the file is moved to the destination successfully, and the size remains the same from the source (size of 0 bytes is more). Therefore, I changed the procedure to use only the frename() function, and the procedure now works successfully, with files of size zero is not in the destination.

    Is this a bug in the new version of Oracle? This never happens in 10.2.0.4 before the upgrade, and I am very surprised that after the upgrade, this problem appears. Oracle experts, please explain this. Thank you.

    Is a known bug (reported bug 12412502, bug 12345982 and Bug 9926478) to 10.2.0.5 patch group which appears only on the HP - UX Itanium platform...

    There is a work around, copied the text of Bug 9926478:

    WORKAROUND SOLUTION?
    ===========
    Yes

    WORKAROUND INFORMATION
    ======================
    Utl_file.fcopy of execution in a PL/SQL procedure.
    Workaround is acceptable for the customer.

    From My Oracle Support Note ID 1324406.1:

    Patch 12345982 (FILE CREATED FROM UTL_FILE VACUUM. FCOPY on HP - UX ITANIUM 10.2.0.5) is currently available.

    And in the same note, there is a work around using UTL_FILE. GET_RAW and UTL_FILE. PUT_RAW

    But, I think, you already found a better workaround for the cases of displacement... so you can use your workaround or apply the Patch 12345982

    Best regards
    Alfonso Vicente
    [http://www.logos.com.uy/el_blog_de_alfonso]

  • PLSQL utl_file.put_line error after the script running 8 ' e

    Hello
    I wrote a script to export the results of a query to an external file using utl_file.put_line. the script works very well for the first 8 hours.

    anonymous block filled
    anonymous block filled
    anonymous block filled
    anonymous block filled
    anonymous block filled
    anonymous block filled
    anonymous block filled
    anonymous block filled

    When I run the same script for the 9th time, I got an error message

    Error from the 1 in the command line:
    DECLARE
    OutFile utl_file.file_type;
    TYPE rc_a IS REF CURSOR;
    l_rc_a rc_a;
    TELLER_1 INTEGER: = 3;
    ctt1 varchar (2000);
    AA varchar (2000);
    BEGIN
    FOR TELLER_1 IN 3.9

    LOOP

    OutFile: = utl_file.fopen ('DAT_DIR', 'A1_W' |) TELLER_1 | "_KANS. TXT', 'w');

    ctt1: = '

    SELECT
    WORP_XW | ''|''||
    D | ''|''||
    V5_AANTAL_KANS | ''|''||
    V5_AVG_KANS | ''|''||
    V6_AANTAL_KANS | ''|''||
    V6_AVG_KANS | ''|''||
    V7_AANTAL_KANS | ''|''||
    V7_AVG_KANS | ''|''||
    V8_AANTAL_KANS | ''|''||
    V8_AVG_KANS | ''|''||
    V9_AANTAL_KANS | ''|''||
    V9_AVG_KANS
    Of
    (
    Select D, V5_AANTAL_KANS, V5_AVG_KANS, V6_AANTAL_KANS, WORP_XW, ROUND(V6_AVG_KANS,6) V6_AVG_KANS ROUND(V5_AVG_KANS,6),
    V7_AANTAL_KANS, V7_AVG_KANS, V8_AANTAL_KANS, ROUND(V8_AVG_KANS,6) V8_AVG_KANS ROUND(V7_AVG_KANS,6),
    V9_AANTAL_KANS, ROUND(V9_AVG_KANS,6) V9_AVG_KANS
    Of
    (
    Select WORP_XW, D, KAN,
    case VERSIE_VX when "V5" then 5 when "V6" when then 6 "V7" when then 7 "V8" when then 8 "V9" then 9 end as VERSIE_VX
    of VMENS. TOEVAL_BASIS_W' | TELLER_1 | »

    )
    pivot)
    AVG (KAN) as AVG_KANS,
    COUNT (KAN) AS AANTAL_KANS
    by VERSIE_VX (V5, V6, V7, V8, V9 9 8 7 6 5)
    )
    ORDER BY D
    )';

    L_rc_a OPEN FOR ctt1;
    LOOP
    EXTRACTION l_rc_a IN aa;
    EXIT WHEN l_rc_a % NOTFOUND;
    -dbms_output.put_line (aa);
    UTL_FILE.put_line (OutFile, aa, TRUE);
    END LOOP;

    END LOOP;
    UTL_FILE.fclose (outfile);
    END;
    Error report:
    ORA-29283: Ongeldige bestandsbewerking/ORA-29283: invalid file operation
    ORA-06512: in 'SYS. UTL_FILE", regel 536
    ORA-29283: Ongeldige bestandsbewerking/ORA-29283: invalid file operation
    ORA-06512: in rule 14
    29283 00000 - "invalid file operation.
    * Cause: An attempt was made to read from a file or a directory which is
    not exist, or the file or directory access was denied by the
    Operating system.
    * Action: Check access privileges to the file and directory on the file system
    and if reading, check that the file exists.


    The same is true when I use another script writes the results of a query to an external file. Y at - there someone who can tell me why I have an error message after running 8 ' e of this script.

    With respect,
    Michiel van Mens

    The second time through the outer loop, it will fail because you try to open a file that is already open. Move your utl_file.fclose statement of before the last "END LOOP '.

  • Procedure using utl_file.fopen

    Hello
    I want to open a file, read line by line, and if I find a particular word, I want to display the whole line.
    I tried to write a procedure, but not getting desired do not output.

    DECLARE
    x utl_file.file_type;
    y varchar2 (200);
    BEGIN
    x: = utl_file.fopen('TRACE1',DB_ora_111_trc.txt','R');
    LOOP
    BEGIN

    UTL_FILE. GET_LINE(x,y);
    If x = "select".
    dbms_output.put_line (x);
    end if;

    EXCEPTION
    WHEN NO_DATA_FOUND THEN EXIT;
    END;
    END LOOP;
    UTL_FILE.fclose (x);
    END;
    /

    Here I am opening a file of tkprof and trying to grep for select word and if he is found, select all to display query. The above doesn't show any output. Kindly help me as I'm new to coding.

    Thank you

    user10698496 wrote:
    Thank you BlueShadow.I tried to run, but received the error as
    ORA-06502: PL/SQL: digital or value error: character of number conversion error.

    I put the '+ 5' after barcket.

    Oops, my bad. Sorry about that.

    DECLARE
    f utl_file.file_type;
    s varchar2(2000);
    in_select boolean;
    BEGIN
    f := utl_file.fopen('TRACE1','DB_ora_1118250.trc.txt','R');
    in_select := false;
    LOOP
    BEGIN
    UTL_FILE.GET_LINE(f,s);
    if lower(s) like '%select%' or in_select then
    dbms_output.put_line(s);
    if lower(s) like '%from%' then
    dbms_output.put_line('TABLES: '||substr(s,instr(s,'from')+5)); -- +5 to get past the from and the space character after it.
    end if;
    in_select := not(s like '%;'); -- stop when we get to ";" at end of a line.
    end if;
    EXCEPTION
    WHEN NO_DATA_FOUND THEN EXIT ;
    END;
    END LOOP;
    utl_file.fclose(f);
    END;
    / 
    
    SELECT lpad(to_char(NVL(MAX(to_number(serial_num)), 0) + 1), 12, '0')
    FROM
    TABLES:
    SALES WHERE s_id =  :1   AND s_name =  :2
    
    SELECT S_CODE
    FROM
    TABLES:
    S_MAST WHERE s_id =  :1   AND s_name =  :2
    

    If you notice after 'from' the word TABLE is attached due to dbms_output.put_line('TABLES.)
    But he did not cut the name of the table only and shown as output.

    Well, obviously, now we can see the entire SQL statement that you are querying, your table names are not on the same line as your statement 'FROM '.
    This means that it won't be easy to spot where the tables are in the statement.

    Perhaps if you explained what you're actually trying to reach, then we can help you, but looks like you are trying to do something beyond the reach of reason.

    I also tried to put the output in a file

    DECLARE
    f utl_file.file_type;
    s varchar2(2000);
    in_select boolean;
    opfile utl_file.file_type;
    
    BEGIN
    f := utl_file.fopen('TRACE_EXTRACT','nis_trc.txt','R');
    opfile := utl_file.fopen ('TRACE1',,'SELECT.txt','W');
    in_select := false;
    LOOP
    BEGIN
    UTL_FILE.GET_LINE(f,s);
    if lower(s) like '%select%' or in_select then
    dbms_output.put_line(s);
    utl_file.put_line(opfile,s);
    in_select := not(s like '%;'); -- stop when we get to ";" at end of a line.
    
    end if;
    EXCEPTION
    WHEN NO_DATA_FOUND THEN EXIT ;
    END;
    END LOOP;
    utl_file.fclose(f);
    END;
    / 
    
    ERROR at line 1:
    ORA-29283: invalid file operation
    ORA-06512: at "SYS.UTL_FILE", line 536
    ORA-29283: invalid file operation
    ORA-06512: at line 8
    

    The TRACE1 directory exist and I also granted READ/WRITE permissions. Why does this error happen?

    Perhaps because of this...

    opfile := utl_file.fopen ('TRACE1',,'SELECT.txt','W');
    

    You seem to have an extra ',' in your settings.

  • How to check if UTL_FILE was granted to the Public?

    Thanks in advance.

    I'm working on writing a SQL * plus query that can check to see if 'UTL_FILE' was granted to the Public?

    The dba_tab_privs does not provide me with the appropriate information.

    Thank you
      1* select table_name from dba_tab_privs where grantee = 'PUBLIC' AND     PRIVILEGE = 'EXECUTE' and table_name like 'UTL%'
    SQL> /
    
    TABLE_NAME
    ------------------------------
    UTL_RAW
    UTL_IDENT
    UTL_TCP
    UTL_HTTP
    UTL_FILE
    UTL_INADDR
    UTL_SMTP
    UTL_URL
    UTL_ENCODE
    UTL_GDK
    UTL_COMPRESS
    UTL_I18N
    UTL_LMS
    UTL_NLA_ARRAY_DBL
    UTL_NLA_ARRAY_FLT
    UTL_NLA_ARRAY_INT
    UTL_NLA
    UTL_REF
    UTL_COLL
    UTL_MATCH
    UTL_BINARYINPUTSTREAM
    UTL_BINARYOUTPUTSTREAM
    UTL_CHARACTERINPUTSTREAM
    UTL_CHARACTEROUTPUTSTREAM
    UTL_MAIL_INTERNAL
    
    25 rows selected.
    
  • Query output to a txt file

    Hi all

    I have a query which output must be saved in a .txt file. Each line contains a field with concatanated data. Now, it runs in a procedure on the database that uses utl_file functions to save the file on the server. In the calendar on the server runs a tast that verifies the file every 15 minutes one moves the files in this folder in a network directory that users can access. We are migrating to a new environment, and this solution is no longer an option.

    I have the opportunity to create a BI with CSV report as output or create an interactive report and let the user to download output to a CSV file. But then the data are surrounded by double quotes. If it's not ideal.

    The solution I am looking for is: the user gets a dialog box and choose the location where he wants to put the txt file. Then the output of the query is saved to this place as a .txt file. Is this possible in the APEX (APEX 4.0.2)? And if so, how does it work?

    But then the data are surrounded by double quotes. If it's not ideal.

    The reason why most system (not only apex) join the CSV fields using quotes is because it allows the data to have a comma which otherwise, to wrongly analyse data. The file would be completely unnecessary in this case.

    You can generate files of apex anyway you want
    See this post
    Choose any file name and extension, the appropriate mime type and write data using htp.p in according to your desire format it in your file. It is very different than utl_file in the way you generate data (except the mime headers)

  • Query by query column names

    How to get the column names in query by query programmatically?

    For example
          Query: select ename as name, empno, job from EMP t
    
          Column names: name, empno, job 

    Agree with sybrand and Billy.

    (From my library of examples...) for purposes of demonstration...

    As user sys:

    CREATE OR REPLACE DIRECTORY TEST_DIR AS '\tmp\myfiles'
    /
    GRANT READ, WRITE ON DIRECTORY TEST_DIR TO myuser
    /
    

    As myuser:

    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 the header line and the data to write into files separate if necessary.

    for example

    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
    
  • How to write output to a txt file query results

    have a sub query resulting in some records I want to write in a txt file

    Select employee a.empcode a, b the address where a.empcode! = b.emp.code

    You can use UTL_FILE to do so, either specifically for your query or more generically as below:

    As user sys:

    CREATE OR REPLACE DIRECTORY TEST_DIR AS '\tmp\myfiles'
    /
    GRANT READ, WRITE ON DIRECTORY TEST_DIR TO myuser
    /
    

    As myuser:

    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 the header line and the data to write into files separate if necessary.

    for example

    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
    

    The procedure allows for the header and the data to separate files if necessary. Just by specifying the file name "header" will put the header and the data in a single file.

    Adapt to the exit of styles and different types of data are needed.

  • Display of the results of query in Excel on the Web

    Hello

    I try to display data from a query in excel on the web without creating an existing file. I know I can create a CSV using UTL_FILE and post it but I was hoping there was a way to do it without actually creating the file. I have a procedure that resembles

    PROCEDURE displayAsCSV is
    cursor STUD_CURS is
    Select * from students;

    BEGIN
    for STUD_REC loop STUD_CURS
    HTP. Print (' "' |") STUD_REC. FIRST_NAME. » " , " '|| STUD_REC. LAST_NAME. » " ');
    end loop;
    END;

    Anyone know if it is possible to display these results in excel in the browser by altering the MIME types or something similar?

    Thank you

    Check Tom owa_sylk utility with the appropriate mime type.

  • How to extract a portion of text with utl_file

    Hello

    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 text DELIMITED by tabs. I use the notion of package UTL_FILE to read the data. In general, when we use the UTL_FILE. GET_LINE, we read the whole line of text. But I need to read the 10th column in the query or the text delimited by tabs.

    Please advice.
    My query goes something like this:

    declare
    f utl_file.file_type;
    long s;
    c number: = 0;
    Start
    f: = utl_file.fopen('ABC_EXTRACTS','sample1.txt','R');
    loop
    UTL_FILE.get_line (f, s);
    insert into a values (s);
    c: = c + 1;
    end loop;
    exception
    When NO_DATA_FOUND then
    UTL_FILE.fclose (f);
    dbms_output.put_line('No. deles de lignes insérées: ' || c);
    end;

    Or try,

    WITH t AS
    (SELECT '1111'||chr(9)||'2222'||chr(9)||'3333'||chr(9)||'4444'||chr(9)||'5555' col1
    FROM DUAL)
    SELECT regexp_substr (col1, '[^'||chr(9)||']+'||chr(9), 1, 1) col1
    FROM t;
    
    COL1
    1111 
    

    It's search for characters of the string between two tab.
    * 009 *.

    Published by: 009 on March 22, 2010 22:00

  • FOPEN, UTL_FILE. Put_line - how

    I'm trying to execute the PL/SQL block to write a Union query results to a file (called vFILE). The output I'm generating a requirements of special format given to me by my Bank, because it is a store file. I created the formatting in the part of the execution of sql select. How can I this fits in the FOPEN, UTL_FILE. Put_line and FCLOSE commands? Or I have to do something completely different? Note: There are 3 parts to the Union - part 1 query is the header, part 2 is the detail, and part 3 is the trailer. Thank you!

    That's what the output in the file should look like:
    HCORP123 08112009 (header)
    R00000123450000277057000010000001282009SA (retail)
    R00000123450000277058000020000001282009SA (retail)
    R00000123450000277059000010000008062009SA (retail)
    T000001234500000000030000000400000 (trailer)


    DECLARE
    vFile UTL_FILE. TYPE_DE_FICHIER;
    BEGIN
    vFile: = UTL_FILE. FOPEN ('/ devlop, e001, usc, pospay', 'POSPAY_USC2.txt', 'w', 32767);
    FOR x IN)
    SELECT
    'H'||
    RPAD ('USC2 ', 33,' ') |
    TO_CHAR ((SYSDATE), 'MMDDYYYY') |
    LPAD (", 70,' ')
    Of
    DOUBLE
    UNION ALL
    SELECT
    'R'||
    LPAD ((b.BANK_ACCOUNT_NUM), 10, '0').
    LPAD ((a.CHECK_NUMBER), 10, '0').
    LPAD ((a.amount*100), 10, '0').
    To_char ((a.CHECK_DATE), 'MMDDYYYY') |
    MAX (DECODE (UPPER (a.STATUS_LOOKUP_CODE),
    "NEGOTIABLE", "SA"
    'ISSUED', 'SA ',.
    "ERASED", "SA"
    "DISABLED BUT STILL MISSING", "SA"
    "RECONCILED", "SA"
    "EMPTY',"MS. "
    "CONFIGURATION", "SP",.
    "OVERFLOW", "SP",.
    "SPOILED,", "SP", "SA")) |
    RPAD ((a.VENDOR_NAME), 71,' ')
    Of
    USCAP. AP_CHECKS_ALL has,
    USCAP. AP_BANK_ACCOUNTS_ALL b
    WHERE
    b.BANK_ACCOUNT_ID = a.BANK_ACCOUNT_ID and
    b.BANK_ACCOUNT_NAME = a.BANK_ACCOUNT_NAME and
    a.POSITIVE_PAY_STATUS_CODE = "UNSENT" AND
    b.BANK_ACCOUNT_ID = 10063
    GROUP BY
    b.BANK_ACCOUNT_NUM, a.CHECK_NUMBER, a.AMOUNT, a.CHECK_DATE, a.VENDOR_NAME
    UNION ALL
    SELECT
    'T'||
    LPAD ((b.BANK_ACCOUNT_NUM), 10, '0').
    LPAD ((Count (a.CHECK_ID)), 10, '0').
    LPAD ((Sum(a.amount*100)), 13, '0')
    Of
    USCAP. AP_CHECKS_ALL has,
    USCAP. AP_BANK_ACCOUNTS_ALL b
    WHERE
    b.BANK_ACCOUNT_ID = a.BANK_ACCOUNT_ID and
    b.BANK_ACCOUNT_NAME = a.BANK_ACCOUNT_NAME and
    b.BANK_ACCOUNT_ID = 10063
    GROUP BY b.BANK_ACCOUNT_NUM;
    )
    LOOP
    UTL_FILE. Put_line (vFile, x.item1, x.item2,?,?);
    END LOOP;
    UTL_FILE. FCLOSE (vFile);
    END;

    Hello

    Interplay says:
    Hi Frank,.
    I'm a newbie in the forums, and I don't know how other people are able to post / paste formatted code. I type in it and at the time of publication, the formatting is removed. Can you let me know how you could get the "x.item1 | x.Item2' to look like it was stuck in?

    I typed these 6 characters
    (1) left-brace,
    (2) the letter c,
    (3) the letter o,
    (4) the letter d,
    (5) the letter e, and
    (6) right curly - support, i.e.:

    {code}

    exactly as see you above, before this line and again after this line.

    I know how to do the basic put_line function. I can do with a statement SELECT simple from a table when selecting few fields, but this situation is more complex because it is a UNION query that has a header line, multiline retail, and on the line of the trailer. I have included the example of the output formatting that I am doing in the first post, just to illustrate the final result, that I'm looking. If I run the SQL SELECT * more, it looks good, but I try to use the command put_line (because I'm using PL/SQL) to write this same layout in a file.

    Regardless of whether or not the query is a UNION: the mechanics are the same. Make sure that each column you select has a unique name, so you can reference it later. Only the name (or alias) since the first part of the UNION really matters, but it is good programming practice to explicitly assign the same alias in all branches of the UNION, like this:

    FOR x IN (
                SELECT  'H'                         ||
                RPAD('USC2',33,' ')               ||
               TO_CHAR((SYSDATE), 'MMDDYYYY')          ||
               LPAD(' ',70,' ')                    AS txt
          FROM       DUAL
    UNION ALL
          SELECT      'R'                         ||
                LPAD((b.BANK_ACCOUNT_NUM),10,'0')   ||
               LPAD((a.CHECK_NUMBER),10,'0')          ||
               LPAD((a.AMOUNT*100),10,'0')          ||
               TO_CHAR((a.CHECK_DATE), 'MMDDYYYY') ||
               MAX ( CASE  WHEN  UPPER (a.STATUS_LOOKUP_CODE) IN ( 'VOIDED'
                                                               , 'SETUP'
                                               , 'OVERFLOW'
                                               , 'SPOILED,'
                                               )
                        THEN  'SP'
                        ELSE  'SA'
                     END
                   )                         ||
               RPAD((a.VENDOR_NAME),71,' ')               AS txt
         FROM
              USCAP.AP_CHECKS_ALL        a,
              USCAP.AP_BANK_ACCOUNTS_ALL b
         WHERE
              b.BANK_ACCOUNT_ID          = a.BANK_ACCOUNT_ID     AND
              b.BANK_ACCOUNT_NAME          = a.BANK_ACCOUNT_NAME     AND
              a.POSITIVE_PAY_STATUS_CODE     = 'UNSENT'          AND
              b.BANK_ACCOUNT_ID          = 10063
         GROUP BY  b.BANK_ACCOUNT_NUM,
                      a.CHECK_NUMBER,
                a.AMOUNT,
                a.CHECK_DATE,
                a.VENDOR_NAME
    UNION ALL
            SELECT  'T'                         ||
              LPAD((b.BANK_ACCOUNT_NUM),10,'0')     ||
              LPAD((COUNT(a.CHECK_ID)),10,'0')     ||
              LPAD((SUM(a.AMOUNT*100)),13,'0')          AS txt
         FROM
               USCAP.AP_CHECKS_ALL          a,
              USCAP.AP_BANK_ACCOUNTS_ALL      b
         WHERE
              b.BANK_ACCOUNT_ID     = a.BANK_ACCOUNT_ID     and
              b.BANK_ACCOUNT_NAME     = a.BANK_ACCOUNT_NAME     and
              b.BANK_ACCOUNT_ID     = 10063
         GROUP BY b.BANK_ACCOUNT_NUM       -- No ; here
         )
    LOOP
            UTL_FILE.PUT_LINE (vFile, x.txt);
    END LOOP;
    

    In the example above, there are 3 pins to the UNION. Each has 1 column in the SELECT clause, and this column is always called txt. When you need to refer to this column, use the cursor name, followed by a dot, followed by the name of the column: x.txt.

    Furthermore, you should not have an ORDER BY clause? Without one, there is no guarantee that the header will come first, or even related to the bank_account_num lines will be together.

    Appears not to work-"during the validation of code (or any formatted text) on this site, type the 6 characters (small letters only, inside curly braces) before and after the section of text formatted, to keep the spacing" see below... "

    SELECT
    {abce, abcd}
    Of
    {a.table}

    Sorry, I don't know what you mean here. Looks like you are trying to put something else the magic word 'code' inside the braces. Do not. The only thing inside the braces must be the 4 letter word 'code', which must be all lowercase.

Maybe you are looking for