How to store the output of a statement select * statement in a file?

How to store the output of a statement select * / statement of dsc in a file?

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.

Tags: Database

Similar Questions

  • How to store the original and to remove some duplicate songs in iTunes on a PC Win7, which took place after iTunes to scan for music during a re - install?

    How to store the original and to remove some duplicate songs in iTunes on a PC Win7, which took place after iTunes to scan for music during a re - install?

    I recently had to format my hard drive and reinstall iTunes 12.3.2.35 on my Win7 PC. As part of the re - install iTunes, I clicked on the button scan for music.  This has created duplicates several of my songs.  I deleted then the duplicate songs from iTunes, but when I went to play a few songs a pop-up said "the song would not be because the original could not be found.  You want to locate? "When I tried to locate the song it is not found, but when I pulled the songs out of the trash they could be found.

    How can I keep the original and remove any duplicate songs in iTunes on PC Win7 which took place after iTunes to scan for music during a re - install?

    iTunes can create duplicates if the same content is added several times from outside the media folder when it is about to make copies of everything that is added to the library, or is added from an external drive that hosts the press kit that was disconnected during the launch of iTunes.

    Official notice of Apple on the duplicates is here: find and remove duplicates in your iTunes library. This is a manual process and article fails to explain some of the potential pitfalls such as the lost coast and membership of playlist, or sometimes the same file can be represented by multiple entries in the library as well as a removal and recycling the file will break all the others.

    Use MAJ > display > show items to reproduce exactly to display the duplicates because it is normally a selection more useful. You must manually select all but one of each group to remove. Sort the list by Date added can make easier select appropriate tracks, but it works better when executed immediately after the dupes were created.  If you have several entries in iTunes connected to a same file on the disk hard then don't not send to trash.

    Use my DeDuper script (Windows only) If you are not sure, do not want to do it by hand, or want to maintain ratings, play counts and playlist membership. See this background thread , this post for detailed instructions and Please take note of the warning to back up your library before deduping.

    (If you don't see the menu bar press ALT to temporarily view or CTRL + B to keep displayed.)

    The latest version of the script can put away the dead links as long as there is at least a double live to merge his stats and membership of the playlist and must deal wisely when the same file has been added through multiple paths.

    TT2

  • How to store the result of a query in a variable in the data model

    In a model of date I want to do something like this

    < name of dataTemplate = than one dataSourceRef "HURDetail" = "BRM_DATA_SOURCE" >
    < Parameters >
    < parameter name = "PARAM_THRESHOLD_VALUE" dataType = "number", defaultValue = "0" / >
    < / Parameter >

    < SQLStatement instance name = "Q1" >
    <! [CDATA]
    SELECT count (*) FROM TABLE_NAME
    []] >
    < / sqlStatement >

    -I want to assign the output of the above query to PARAM_THRESHOLD_VALUE so I can use it in future requests...
    -My query is complex, for reason of performance I want to store the output of the query.

    Please suggest how do...
    Made a package with the PARAM_THRESHOLD_VALUE parameter and the function value entry assigns the done variable to work?

    Thank you
    Shiva

    Hey Shiva,

    If you want to use the value of the counter in the other queries in the data model, you can have an alias for the extraction of County and use it as a bind variable in other queries as


    SELECT count (*) PARAM_THRESHOLD_VALUE
    FROM TABLE_NAME
    ]]>

    and can use it in another query as


    SELECT XYZ
    FROM TABLE_NAME2
    WHERE XXX = *: PARAM_THRESHOLD_VALUE *.
    ]]>

    Hope this is what you want.
    Thank you.

  • How to install the output in bridge CC module using an apple OSX 10.9.5 and a miss apple OSX 10.11 this point completely in CC bridge!

    How to install the output in bridge CC module using an apple OSX 10.9.5 and a miss apple OSX 10.11 this point completely in CC bridge!

    Hi abev41080082

    Greetings.

    Concerning

    Rohit

  • How to make the output of the task are an entry in another task

    How to connect the output of a task for I can use it as input for another task?  See this screen below: the task "Invoke the Script" run a PowerShell Script.  The task 'Send E-mail' send an email.  The two tasks work separately.  How can I get the results of my powerShell script that I can use them as content of the task 'Send Email'?

    workflow.jpg

    On the script invoke task you set the attributes of output containing the results of powershell.

    to do this, select the output tab and use an object name that was put in place in powershell results as in the data

    You may need to format, this results in a recognized VMware object I guess in your case it is a string type.

    and then select the e-mail task, select the task from email, click on the small eye looking for icon "view details".

    Select the Visual link

    Select the attributes you setup from the output of the previous task and hang it in the input parameters of the task to email.

    fact

  • How to access the tab 'Save all' when I close several jpeg files that have been adjusted with the "color adjust tool? He is currently making me close and save one at a time. Thanks for any help :)

    How to access the tab 'Save all' when I close several jpeg files that have been adjusted with the "color adjust tool? He is currently making me close and save one at a time.  I've just upgraded to El Capitan.  Thanks for any help :)

    I assume that you use the application overview.

    I can't find an answer to back up everything, but a workaround could be while the file menu options are visible, press the option key

    and the point of the window will become close, if you click on that dialogue will ask you if you want to restore the changes or save

    pressing Save will close the image with the changes and then move to the next image and so on.

  • How to get the string (specified by row and column) of txt file with labview

    Hello world

    How to get the string (specified by row and column) of txt file with labview

    THX

    As far as I know, a text file has no column.  Be more specific.  Do you mean something like the 5th word on line 4, where the words are separated by a space, and lines are separated by a newline character?  You can read from the spreadsheet String function and set the delimiter to a space.  This will produce a 2D channels table.  Then use the table to index and give the line number and column number.

  • How to adjust the boarders of a rectangular selection in the paint without stretching the image.

    Hi, how to set the boarders of a rectangular selection in the paint without him stretch the image?

    I'm afraid this is a limitation (and personally, I find frustrating) paint. Essentially, you get a chance to make a selection. A trick I learned is to zoom as high as possible, start a corner of the selection, and then (while holding down the left button of the mouse to the operation drag) hold Ctrl key while turning the mouse scroll wheel to zoom out giving a larger surface to complete the dragged selection.

  • How to get the mobile applications other than phonegap Build Service apk file in Dreamweaver CM³

    How to get the mobile applications other than phonegap Build Service apk file in Dreamweaver CM³

    Dreamweaver is a tool, not an install Android of web authoring tool.

  • How to activate the warning "no pixel is selected?

    How to activate the warning "no pixel is selected?

    When I selected an empty layer in photoshop, it lets warn me WARNING: no pixels were selected.  How activate this setting prompt warning again?  Thank you.

    Have you tried"reset all warning dialog boxes" in Photoshop > Preferences > General.

  • How to format the output of a .sql script that has select statements.

    Hello

    I have a .sql script which is having several select statements. Each Select statement is to have hundreds of Table columns.

    When we run the .sql script, we are unable to read the output.

    Please let know us the commands that we include for better readable output format.

    You work with the lin standard set 80.
    Increase this setting to set lin 3000 or more.

  • (Best practices) How to store the adjustment curve values?

    I got two sets of data, Xreal and Xobserved, abbreviated Xr and Xo. Xreal is a data set that contains the values of sensor from a reliable source (it's a pain to collect data for), and Xobserved is a set of data containing the values from a less reliable source, but much less maintenance, sensor. I'll create a VI that receives the entry of these two sources of data, stores it in a database (text file or csv) and crosses some estimators of this database. The output of the VI will be best approximation of linear adjustment (using regression, not the Xreal) of the input value of Xobserved.

    What are best practices for storage Xreal and Xobserved? In addition, I'm not too known using best VI made, take CSV files for entry? How would format it best?

    '

    Keep things simple.  Convert the table to CSV file and write to a text file.  See attached example.

  • view the output of dbms_output statement in Toad

    Hi expert,

    I use dbms_output instruction in proceudre and run it into a toad, but he must run ' set serveroutput we "display output statement dbms_output.

    But how can I achieve this functionality in Toad.

    Thank you very much

    >

    Hello

    I use dbms_output instruction in proceudre and run into a frog, but it
    should run "set serveroutput on" to display the output of statement dbms_output.
    But how can I achieve this functionality in Toad.

    At the bottom of your window, there are number of tabs. One of them is
    DBMS_Output. There is a small red button on the left side. Click on this button.
    It turns green. Then, your output is visible - you can click on it and scroll
    upward through your results.

    In the future, ask questions of Toad in a forum of Toad.

    HTH,

    Paul...

  • Don't know how to test the output of the PL/SQL function

    I have a function in the package '. " XCCC_PO_APPROVALLIST_S1' called 'does_cpa_exist ':
       FUNCTION does_cpa_exist(
          p_document_id              IN       NUMBER
       )
          RETURN BOOLEAN
       IS
          l_cpa_exists VARCHAR2(100);
       BEGIN
          SELECT 'Y'
            INTO l_cpa_exists
            FROM po.po_requisition_lines_all prla
               , ap.ap_suppliers pv
               , ap.ap_supplier_sites_all pvsa
           WHERE prla.vendor_id = pv.vendor_id
             AND prla.vendor_site_id = pvsa.vendor_site_id
             AND pv.vendor_id = pvsa.vendor_id
             AND prla.requisition_header_id = p_document_id
             AND EXISTS(
                    SELECT pha.vendor_id
                      FROM po.po_headers_all pha
                     WHERE pv.vendor_id = pha.vendor_id
                       AND pvsa.vendor_site_id = pha.vendor_site_id
                       AND pha.org_id = fnd_profile.VALUE('ORG_ID')
                       AND pha.type_lookup_code = 'CONTRACT'
                       AND pha.authorization_status = 'APPROVED');
    
          RETURN TRUE;
    
          IF (p_document_id IS NULL)
          THEN
             RETURN FALSE;
          END IF;
       EXCEPTION
          WHEN OTHERS
          THEN
             RETURN FALSE;
       END does_cpa_exist;
    The pl/sql valid and commits OK in TOAD.

    I ran the sql in the EBS, and took the path of the workflow looks like that function returned a value of false.

    I pass to the function a document_id.

    I was wondering how I might test the output of the function from TOAD?

    I tried:
    select XCCC_PO_APPROVALLIST_S1.does_cpa_exist(1017934) from dual;
    But get errors:
    ORA-06552: PL/SQL: Statement ignored
    ORA-06553: PLS-382: expression is of wrong type
    I do probably bad 101 things here, but I would still ask thinking and risk of being shouted at.

    Any advice appreciated,

    Thank you

    I was wondering how I might test the output of the function from TOAD?

    Try

    begin
      if xccc_po_approvallist_s1.does_cpa_exist (1017934)
      then
        dbms_output.put_line ('True');
      else
        dbms_output.put_line ('False');
      end if;
    end;
    /
    
  • can I store the output of boolean values in a table?

    the codification output here is '1' and '0'...
    I want to store only '1' and '0' in a table...

    but I can't do it please help me...

    How to store?...

    DECLARE
    EID VARCHAR2 (20);
    BOOLEAN BL: = TRUE;
    BEGIN
    SELECT EMP_NO
    IN EID
    OF LEAVE_FORM
    WHERE EMP_NO = 1;
    BL: = TRUE;
    DBMS_OUTPUT. Put_line (sys. DIUTIL.bool_to_int (BL));
    insert into t1 (BL) values; - error
    EXCEPTION
    When no_data_found then
    BL: = FALSE;
    DBMS_OUTPUT. Put_line (sys. DIUTIL.bool_to_int (BL));
    END;

    Published by: 794244 on February 9, 2011 03:11

    No, you can't. BOOLEAN is no SQL, PL/SQL data type. You did not post structure of table t1. Assumimg t1 column has the number value, use:

    DECLARE
        BL BOOLEAN := TRUE;
        N  NUMBER;
    BEGIN
        N:= sys.DIUTIL.bool_to_int(BL);
        DBMS_OUTPUT.PUT_LINE(N);
        insert into t1 values(N);
        BL := FALSE;
        N:= sys.DIUTIL.bool_to_int(BL);
        DBMS_OUTPUT.PUT_LINE(N);
        insert into t1 values(N);
    END;
    /
    select * from t1
    /
    
            BL
    ----------
             1
             0
    
    SQL>  
    

    SY.

Maybe you are looking for