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.

Tags: Database

Similar Questions

  • How constantly write data in a txt file

    Hello
    first of all, sorry for the bad English, but I have a problem to write data continuously to the txt file... I have a chart 2D with values based 2 sliders (sliders values) and some functions I want to interpolate the value by using the bilinear method... and after that the value of the sliders, interpolated value and the value of the closest points, I want to write to a file txt... for every 2-3 seconds perhaps, it would be ideal to be formatted as ::
    x y f f1 f2 f3 f4
    ..   ..  .. . .. .   ..   ...  . ..
    ... ...  ..    ...   ...   ...   ...

    but... first of all I have a problem with writing data, because every time he deletes old data and simply write a new and it is not horizontal... I am very very new to this (it's obvious) and any help will be very grateful 
    Thank you

    Diane beat me to it, I made a few changes to your code, so I'll post it anyway.

    As proposed, please go through the tutorials.

    I added an entry to the worksheet at the end node just to show it can be done at the end so. Table of building on a while loop is not very efficient memory, but it's just to show you what can be done. If you plan to go this route, initialize an array and use the subset to the table replace.

    All the best.

  • How about the text of the .txt file output?

    This is my code:

    #include "iostream.h".

    #include 'fstream.h.

    ofstream myfile;

    MyFile.Open ("C:\test.txt");

    MyFile < < 'text ';

    MyFile.Close ();

    But it occurs the error C1083: cannot open include file: 'iostream.h': no such file or directory.

    How about the text of the .txt file output?

    I would suggest that you do in the InDesign style to match...

    InterfacePtr stream (StreamUtil::CreateFileStreamWrite (...);

    if(Stream->GetStreamState() == kStreamStateGood) {}

    flow-> XferByte (buf, size);

    flow-> Flush();

    }

    flow-> Close();

    There are lazy as CreateFileStreamWriteLazy equivalent methods.

    Deferred methods will open the file in the application, but you will always get a valid pointer.

    See docs on its use.

  • Pulse TTL-PCI-6503 write in a log .txt file

    Hello, I need to connect the PCI-6503 data output to a log .txt file. This PCI-6503 map reads a pulse sent from another PCI-6503 located in another computer. I want to just save the .txt file if a pulse is received. I know how to create and write to the .txt file, but do not know how to write the DAQmx data in this file. Could someone help?

    Thank you in advance!

    Hi a2h,.

    To only write when there is data emerging from the Daqmx read, you can use the table Emply?. VI to determine if there are real (like the pulse) from the unit and then data of yarn that a structure of case that will write to a text file in the case of false.

    Peter W.

  • 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)

  • How to save data in a txt file.

    Does anyone know why the txt file is empty with no content?

    FILE * f = fopen ("/ shared/documents/save.dat", "w");
    {if(f==null)}
    fprintf (stderr, "Failed to create output. txt\n");
    _exit(2) (1);
    }
    fprintf (f, "Hello World");

    File is created, but the file txt empt without 'Hello World '.

    Ha ha solved.

    fclose (f);

  • write data to a txt file

    Hello.

    I use visa and serial Protocol in my vi n want to save the data from MCU in labview to txt file format which, in the data record in each row not each tab.

    I want to just save not given time. Meanwhile, I plot the data in the chart.

    I search in the forum and consider the posts but can't find a solution.


  • How to print output in a single file at the command prompt

    Hi all

    I am running windows, 11.2.0.1 64bits.

    want the output to a single file below.

    dBV file is D:\ORACLE\ORADATA\ISITEPROD\SYSTEM01. DBF blocksize is 8192 logfile = D:\Newfolder\logs\New\SYSTEM01. DBF.log

    dBV file is D:\ORACLE\ORADATA\ISITEPROD\SYSAUX01. DBF blocksize is 8192 logfile = D:\Newfolder\logs\New\SYSAUX01. DBF.log

    dBV file is D:\ORACLE\ORADATA\ISITEPROD\UNDOTBS01. DBF blocksize is 8192 logfile = D:\Newfolder\logs\New\UNDOTBS01. DBF.log

    dBV file is D:\ORACLE\ORADATA\ISITEPROD\USERS01. DBF blocksize is 8192 logfile = D:\Newfolder\logs\New\USERS01. DBF.log

    dBV file is D:\ORACLE\ORADATA\TS_SITE. DBF blocksize is 8192 logfile = D:\Newfolder\logs\New\TS_SITE. DBF.log

    I don't want 5 different .log files, (it is a batch file content), I want only 1 file output (with the data of all the outputs of annexed cmds).

    Please guide me.

    Kind regards

    Syed

    Hello

    This could help you.

    https://bitbach.WordPress.com/2009/08/14/redirecting-DBV-output-to-a-file/

  • How to display random lines from txt file

    Good morning (or evening all). I am creating an application and want to display random lines of a text file. I know how to create a text file using file connections, but how can I read the random lines of her?

    OK I got it.

    For beginners like me to have a problem in the future, I was not specify my path correctly. It is not enough to land your .txt in the /res folder and wait for the Simulator to load. You must load from SD card or device memory.

    Use the method found here:

    http://www.weask.us/entry/J2ME-BlackBerry-read-write-text-file

    to use it's as simple as that

    StringfName = "file:///SDCard/Blackberry/text.txt";

    String printLine = readTextFile (fName);

    label.setText (printLine);

    Somewhere in your project directory create a directory called SDCard (I did in my res folder).

    In the Simulator go to switch SD card, then load Select Directory and select the new directory of the SD card. This will create the structure of the SD card in the Simulator. Simply move your .txt in the SDCard/Blackberry directory and run your application.

  • How to write Modbus data in a file or a matrix?

    Hello:

    I can monitor my data through RS-485 port using 'Master Series MB query', and successfully, I can show signals using the waveform.

    But I can't save the data during the test in a table or write to a file. (see attachment and picture)

    How can I write them to a file or a spreadsheet correctly?

    When I try to read 'file as' and this graph, I can not every graph, there simply a knot!

    is the data type "registers entry" needs a special procedure?

    What is the problem?

    Thank you.

    A fundamental flaw that I see is that you have to write file as configured to rename and replace any existing file when you call the function.

  • How to write data from the INI file for the control of the ring

    Hai,

    I need to write the data read from the INI file to a control of the RING. Doing this operation using variants I get the error.

    I will be happy if someone help me. I have attached the file special INI and VI.


  • How to write variables in the spreadsheet file

    I run an application in run in continuous mode.

    One of the variables change over time (it is inside a while loop and is part of the task of data acquisition). I want to record all the values this variable can take during execution and save them in a spreadsheet file?

    How this can be done?

    Give this example look on.  I am open a file before the beginning of my main loop and its closure after the main loop.  Inside the loop, I am formatting my data in a string of tabs.  I then save this string in the file.

  • Text output to a .txt file

    Hello
    I was wondering if there is a way for the output strings (or Variables) in text files. Any help would be appreciated... Thanks :)

    Dan_pc wrote:
    > A Flash projector...
    >
    > Thanks in advance!

    SWF in html, we could use such as asp or php and server-side comes to
    projector, you will need third party tools as flash itself has simply not these
    capacity. Check http://flashjester.com/?section=tricks_jtools_jsave
    It does exactly what you need and it's the only one I know and use long
    at the time.

    --
    Best regards

    Urami

    --


    If you want to send me a message - DO NOT LAUGH at MY ADDRESS

  • How to copy and paste a txt file in another directory

    It seems very simple. I used the "copy" of the function of advanced file. It worked fine until I created a standalone one. He made mistake and did not do what he did.

    Any idea?

    Thank you

    Opt_Ottawa

    Maybe a problem of path.  Remember that when you build your program into an executable, the executable file is added to the path, and you end up with a path of band more needed to get where you were during development.

    Do you have a miscarriage 7 has occurred to the new file?

  • Question about how to calculate an additional column in the query result.

    Hello PL/SQL gurus and experts.

    I use Oracle Database 11 g Enterprise Edition Release 11.2.0.1.0 - 64-bit Production version


    Currently, I have the data in the following manner-
    drop table T2;
    create table T2(Year, MastTot, BechTot, Tot) as select
    '2008', '20000', '450000', '470000' from dual union all select
    '2008', '50000', '324000', '374000'  from DUAL union all select
    '2009', '25000', '450000', '475000'  from dual union all select
    '2009', '250000', '324000', '574000' from DUAL union all select
    '2010', '120000', '450000', '570000' from dual union all select
    '2010', '52000', '324000', '376000'  from DUAL union all select
    '2011', '220000', '450000', '670000' from dual union all select
    '2011', '52000', '324000', '376000'  from DUAL ;
    I want that data to present the following year (production).
    Year     MastTot     %Change     BechTot     %Change     Tot     %Change     %Total
    2009     275000     292.86     774000     0     1049000     24.29     27
    2010     172000     -37.45     774000     0     946000     -9.82     24.35
    2011     272000     58.14     774000     0     1046000     10.57     26.92
    Total     789000     313.54     3096000     0     3885000     25.04     78.28
    I use the following sql query-
    select decode(grouping(Year), 0, Year, 'Total') Year,
           To_Char(sum(MastTot), '999,999,999,999,999,999,999.99')  "MastTot",
           To_Char(sum(BechTot), '999,999,999,999,999,999,999.99')  "BechTot",
           To_Char(sum(Tot), '999,999,999,999,999,999,999.99')  "Tot",
           round((sum(Tot)/nullif(max(total_amount),0)) * 100, 2) "%Total"
      From
    (
    select Year,
           sum(MastTot) MastTot,
           sum(BechTot) BechTot,
           sum(Tot) Tot,
           SUM(Tot) over() total_amount
      From t2
    group by Year,Tot
    )
    where Year>'2008'
     group by grouping sets((Year),())
    order by Year
    But I am not able to read the % change column. Kindly help me with this.
    All the efforts and assistance in this regard is very appericated and I will be thankful to you...

    user555994 wrote:
    Thanks for the reply JAC,

    you are making reference to the line in the code

    round((sum(Tot)/nullif(max(total_amount),0)) * 100, 2) "%Total"
    

    Here, I'm looking for the Total % against the maximum value of the tot...

    SQL> with t
      2  as (
      3  select year,masttot,lag(masttot) over(order by year) prevm,
      4      BechTot,lag(BechTot) over(order by year) prevb,
      5      tot,lag(Tot) over(order by year) prevt,
      6      sum(tot) over(order by null) sm_t
      7  from(
      8  select Year,
      9         sum(MastTot) MastTot,
     10         sum(BechTot) BechTot,
     11         sum(Tot) Tot
     12  From t2
     13  group by Year
     14   ))
     15  select year,sum(masttot) masttot,
     16     sum(((masttot-prevm)/prevm)*100) Perc_m,
     17         sum(BechTot) bechtot,
     18         sum(((BechTot-prevb)/prevb)*100) Perc_b,
     19         sum(tot) tot,sum(((tot-prevt)/prevt)*100) Perc_t,
     20         sum((tot/sm_t)*100)  perc_total
     21  from t
     22  where year > 2008
     23  group by rollup(year);
    
          YEAR    MASTTOT     PERC_M    BECHTOT     PERC_B        TOT     PERC_T PERC_TOTAL
    ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------
          2009     275000 292.857143     774000          0    1049000 24.2890995  27.001287
          2010     172000 -37.454545     774000          0     946000 -9.8188751 24.3500644
          2011     272000 58.1395349     774000          0    1046000 10.5708245 26.9240669
                   719000 313.542132    2322000          0    3041000 25.0410489 78.2754183
    

Maybe you are looking for

  • A31 no sound

    From one day to the next my glorious old A31 just make the sound disapperead. No device, no Panel, nothing. Working at night and the next day, everything no longer works. I tried to reinstall the driver but I got a failure. Tried system restore, but

  • XP on vista system by mistake

    I was going to reformat the hd in my netbook that works under Xp, but it doesn't have an optical drive. Put the drive in the pc and forgot about recovery and then we had a power failure and when it restarted it installed xp on my vista system don't w

  • Why my Windows Phone app (for desktop) does not open?

    I connect my WP8 to my laptop. Open Windows Phone app to sync music. And this happens: The signature of the whole problem: Signature of the problem: Problem event name: CLR20r3 Signature of the problem 01: windowsphone.exe Signature of the problem 02

  • Windows 7 - cannot open programs

    I bought an Acer laptop and now I am unable to open any programs. When I click to open a program, he asked what I'd like to open with. I can only open my computer. Used to Norton even opened.  The laptop has Windows 7 Home. Can someone help me? PLEAS

  • Thermal paste or thermal Pad?

    Hi I have a M17x which came with two Nvidia Geforce GTX 280 m SLI graphics cards, as I can switch between hybrid and discrete graphics modes I believe is the saying, It also has the third on board graphic chip Nvidia Geforce 9400, which is where my q