Export the results of a query to a CSV file

Hello

My requirement is that I need to export the results of a query to a CSV file. Can someone please suggest a way to also include the names of columns in the CSV file?

Thanks in advance.

Annie

Following code comes from asktom. I changed to include the column header. This will get your CSV file desired 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

Thank you
Knani.

Tags: Database

Similar Questions

  • Hot to export the two outputs a script to a csv file

    Hi all

    I have a simple sctipt which is the instant list of two DC in my environment. Currently each line generates a separate CSV file with data.

    Is it possible to create a single file with the output of these two lines data?

    Get-data center-name DC1. Get - vm | Get-snapshot | Select-Object name, Description, PowerState, VM, created, @{Name = 'Host'; Expression = {(Get-VM $_.)} {{VM). $host.name}} | Export ' E:\artur\reports\DC1_snapshot.csv

    Get-data center-name DC2. Get - vm | Get-snapshot | Select-Object name, Description, PowerState, VM, created, @{Name = 'Host'; Expression = {(Get-VM $_.)} {{VM). $host.name}} | Export 'E:\artur\reports\DC2_snapshot.csv '.

    both files will be sent by mail

    Copy & paste the problem.

    The Export-Csv should be of course outside the loop

    get-datacenter -name "blackburn","coventry" | %{
         $dcName = $_.Name
         $_ | get-vm | get-snapshot | `
              Select-Object @{Name="DC"; Expression={$dcName}},VM, Name, Description, PowerState, Created,
                   @{Name="Host"; Expression = {(Get-VM $_.VM).Host.Name}} | `
    } | Export-Csv 'C:\DC_snapshot.csv'
    

    ____________

    Blog: LucD notes

    Twitter: lucd22

  • Write the result of a query in ODI in file

    Hi friends,

    I'm using ODI 11 g.

    In ODI I want to write the output of the query to a file unix below.

    SELECT "H" | RPAD('SB9KT.) KTPRTO. EBSDATA. D0000000 ', '30', ' ') | RPAD (to_char (sysdate, 'YYYYMMDDHHMMSS'), 16, ' ')
    DOUBLE;


    Please suggest any entries.

    Thank you
    Lony

    delete ';

  • Procedure to export the result of the query to an excel or csv

    Hi all

    I have two identical paintings

    EMP_TEST OF THE EMP

    ID ID NAME

    1     SAM                      1        SAM

    2 JOHN 2 ROCK

    3 3 STEVE BRAND

    I need to combine the result under the query and intent to export data to excel using a procedure

    my query is

    Select 'EMP_ID', E1. EMP_ID, AND. EMP_ID from emp E1,

    emp_test AND WHERE E1. EMP_ID = AND. EMP_ID

    UNION

    Select "EMP_NAME", E1. EMP_NAME, AND. Emp E1 EMP_NAME,

    emp_test AND WHERE E1. EMP_ID = AND. EMP_ID

    but I get this error message

    ORA-01790: expression must have same type of corresponding data

    EMP_ID is a number and EMP_NAME is of type varchar.

    I need any idea or suggestion on sub queries.

    (1) I have to combine the result set in a single query.

    (2) I need to write the procedure that will export the result of the query to an excel or csv.

    Thank you.

    As PR has said, there are ways that have already been explained in this forum to write in external files. For your query condition, try this.

    SELECT CASE WHEN (REGEXP_LIKE (T1.ID,'[^ [: alpha:]] "")) THEN 'EMP_ID '.

    ELSE "EMP_NAME' END AS COL_NAME.

    T1.ID,

    T2.ID

    DE)

    SELECT CASE WHEN ID IS NULL THEN NAME ANOTHER TO_CHAR (ID) END AS ID,

    ROW_NUMBER () OVER(ORDER BY RN NULLS FIRST,ID) RN

    DE)

    SELECT ID, NULL,

    NAME,

    RN ID

    FROM EMP

    UNION ALL

    SELECT ID,

    NAME,

    RN NULL

    FROM EMP)) T1.

    (SELECT CASE WHEN ID IS NULL THEN NAME ANOTHER TO_CHAR (ID) END AS ID,)

    ROW_NUMBER () OVER(ORDER BY RN NULLS FIRST,ID) RN

    DE)

    SELECT ID, NULL,

    NAME,

    RN ID

    OF EMP_TEST

    UNION ALL

    SELECT ID,

    NAME,

    RN NULL

    OF EMP_TEST)) T2

    WHERE T1. RN = T2. RN;

    OUTPUT:

    COLUMN-NAME ID ID
    --------  ---------------
    1 1 EMP_ID
    2 2 EMP_ID
    3 3 EMP_ID
    SAM EMP_NAME MARK
    EMP_NAME JOHN JOHN
    EMP_NAME STEVE DARREN

    6 selected lines.

  • Need to print the results of a query in a CASE statement

    I want to print the results of a query in a CASE statement:

    SELECT RUN_STATUS

    Of

    (select check BOX WHEN COUNT (ROW_WID) = 0 THEN 'NO JOBS RAN AFTER' |) (select sysdate - XXAFL_MINUTES MINUTE)

    END RUN_STATUS

    of W_ETL_RUN_SDTL

    where START_TS >

    (sélectionnez sysdate-MINUTES de XXAFL_MINUTES)) where RUN_STATUS is not null; e

    The query above subtracted 5 minutes from SYSDATE and he shoots XXAFL_MINUTES. I am doing this because we could change the number of minutes in the future. I want to print the number of minutes in the case statement.

    If I execute this statement, it throws an error stating:

    ORA-00937: not a single group group function

    00937 00000 - 'not a single-group function.

    * Cause:

    * Action:

    Error on line: 1 column: 96

    How can I include "select sysdate - MINUTES of XXAFL_MINUTES" in the CASE that it calculates the number of minutes and it prints with the results.

    Thanks in advance!

    Hey guys,.

    I found the solution:

    SELECT

    RUN_STATUS | TO_CHAR ((sélectionnez sysdate-MINUTES de XXAFL_MINUTES), 'HH24:MI:SS')

    Of

    (select check BOX WHEN COUNT (ROW_WID) = 0

    THEN "NO JOB RAN.

    END RUN_STATUS

    of W_ETL_RUN_SDTL

    where

    START_TS > (select sysdate - XXAFL_MINUTES MINUTE))

    where

    RUN_STATUS is not null;

    The output:

    NO JOBS RAN AFTER 09:07:54

    Thanks to you all!

  • Insert the result of a query select in another table

    Hello

    I have a strange problem when I try to insert all the results of a query select in another table, using the declaration of the order.

    With the declaration of COMMAND it works fine
    Work:
    ------------------------------
    INSERT INTO ADART01 (SELECT (codart)
    "STOCK". "" CODART_STO ".
    Of
    "DB". ' ' 'ACTIONS');
    ------------------------------

    But if I try to sort the result using the declaration of the ORDER, I have the following error:
    Error: ORA-00907 missing right parenthesis
    ------------------------------
    INSERT INTO ADART01 (SELECT (codart)
    "STOCK". "" CODART_STO ".
    Of
    "DB". "" "ACTIONS"
    ORDER BY
    "STOCK". ("' CODART_STO ASC ');
    ------------------------------

    Any idea?

    Thank you for your help,
    Angel.

    delete "()" to select

    create table test1 (a number, b varchar2(100));
    
    insert into test1
        (a, b)
        select level, 'level ' || level from dual connect by level < 101;
    
    insert into test1
        (a, b)
        select level, 'level ' || level from dual connect by level < 101 order by to_char(sysdate - level, 'D');
    
    select * from test1;
    
    drop table test1;
    
  • defining the results of a query to a variable

    Hi all

    I'm having a problem affecting the results of a query to a variable. What I'm trying to do, is to do an AJAX call to a .cfc file and pass back the results of the function. The main problem is, I'm again moving a block of HTML (resulting from a cfquery in a cfoutput) stored in a variable. My code is something like...

    < name cffunction = "getText" access = "remote" returntype = 'Cancel' >

    < datasource = "" #request.dsn # cfquery "name ="queryTable">"
    SELECT kort, infoB

    Of infoTable

    < / cfquery >


    < cfset result = ' <!-this is the part I'm stuck, I want the table go here. -> ">"

    < table >
    < cfoutput query = "tablequery" >
    < b >
    < td > #infoA # < table > < td > #infoB # < table >
    < /tr >
    < / cfoutput >
    < /table >


    < cfwddx action = "cfml2js" input = "" # result # ' toplevelvariable 'o' = > "

    < / cffunction >

    It is a simplified version of what I want to do, but you get the idea...

    Is it still the right way to go about this?  Thank you

    That's what I get for trying the E-mail response feature!  Are you not happy, that I double checked my post.

    You could do a lot of string concatenation here to do stuff like"& Kort &""& infoB &""> time and time again."  But in reality the tags is so much easier to use.



      

        
      

    #infoA #.#infoB #.

  • I need to return the result of a query on a stored procedure

    I need to return the result of a query to a stored procedure, I mean when I run a stored procedure it returns a result set in a select statement.
    Best regards...

    Hello.

    Do you really want a stored procedure for this?
    Why not just a script that contains the query?

    Assuming that you don't really want a stored procedure, you'll have to decide what to do with the results.
    An option is a slider.

    For example, you can write a procedure of this type to hold the query:

    CREATE OR REPLACE PROCEDURE USP_TEST
    (     out_cursor     OUT     SYS_REFCURSOR
    )
    IS
    BEGIN
         OPEN  out_cursor
         FOR     SELECT     *
              FROM     scott.emp;
    END  USP_TEST;
    /
    SHOW ERRORS
    

    You can move the cursor to another procedure for handling.

    You could test this in SQL * more by creating a variable blond:

    VARIABLE     usp_test_cursor     REFCURSOR;
    
    EXEC  usp_test (:usp_test_cursor);
    
    PRINT     :usp_test_cursor
    
  • 4.0.3 export the result of grid in xlsx for different data type

    Hello

    Using SQL Dev 4.0.3.16 build 16.84 principal.

    Windows 7

    Java 1.7u80

    Run the query, click with the right button on the result of the grid:

    When you export data in xlsx format, why the numbers data type has different type of font.

    -Number / digital-> dialogue

    n.jpg

    -date and varchar2-> Calibri

    v.jpgd.jpg

    Step to reproduce:

    1 run this query

    Select 100 n, '100', to_date (1 January 2015 ',' DD-MM-YYYY "") as d

    Double;

    2. right click on the grid - export

    3. choose the Format: excel 2003 + (xlsx)

    Thank you.

    Buntoro

    This is a known behavior. And I think that there is a feature request to the SQL Developer Exchange, like the export of dates date request and not as text.

    Concerning

    Marcus

  • Is it possible to put the results of a query in a variable to use in the bean class?

    Hello, I am using JDeveloper 12.1.2.0.0

    I like to keep the result of my queries (the method that I created in the AppModule) in a richeTableau or another type of variable, so I can get results and I don't have to make unnecessary after queries. I don't think that the query is the problem but keeping the results.

    I tried to do in using this:

    public String testVFactSales (String conditions) {}

    PreparedStatement query = getDBTransaction () .createPreparedStatement ("" + "select * from v_fact_sales"+ conditions, 0 ");

    ResultSet rs;

    Outcome of the result set;

    Result of the richeTableau;

    String result = null;

    try {}

    query.setString (1, conditions);

    Query.Execute ();

    Query.Execute ();

    result = query.getGeneratedKeys ();

    Query.Close ();

    System.out.println ("result:" + result.toString ());

    return result.toString ();

    } catch (SQLException e) {}

    e.printStackTrace ();

    }

    Return ' ';

    }

    As you can see, I have already tried a few solutions, but so far I have only errors (cannot convert or null exception, when I try to put the result in a richeTableau in my bean class)

    Any ideas?

    It is very important for me, because it would improve the performance of my project a lot.

    Kind regards

    Frederico.

    Although the issue is not 100% responded, I used the idea that Shay told me, where you can create a method in your AppModule to set your where clause!

    Good luck to everyone who has the same problem.

    As an attack similar to what I wanted in the first place, you can check this:

    https://community.Oracle.com/thread/2619669

    Kind regards

    Frederico.

  • The results of F1-QUERY-how to restrict or to SQL with the role of access to the data?

    Hello

    With the help of CC & B 2.3.1.

    I'm configuration of a Zone of F1-OF-QUERY to get and display customer information as level account; the filter criteria will be Geo val SP.

    With our application, we use access to accounts and groups access to the data on users roles to restrict access to sensitive accounts, such as VIP.

    What keywords should I use in the SQL statement to limit the results only for group accounts to which access is included in the Dar of the user?

    Example: If the user has DAR 'STANDARD', it won't see accounts with group access 'VIP '.

    I tried unsucessfully: USER: USER ID,: USER_ID.

    Unsucessfull example:

    Select dar_cd, user_id, expire_dt
    of ci_dar_usr
    Where user_id =: USER_ID
    and expire_dt > =: F1

    Thks,

    Fabien

    Hi, Fabien,

    If you are looking to determine the current user in the box,
    the keyword to use is: USERID

    You can check the zone of F1 "F1-FAVSCR" for its use.

  • assign the value to a selection of the result of a query control

    I want to assign a value to my controls with the result of the query.

    It works for CFINPUT TEXT, but it does not work to SELECT

    I want to know are there any way tp affect my drop-down list value based on the result of questy.

    I have CFSTOREPROC as follows:

    < cfstoredproc procedure = "PSP" >

    < cfprocparam value = '#form. "IDNumber #" CFSQLTYPE = "cf_sql_integer" >

    < name cfprocresult = resultset "spResult" = "1" >

    < / cfstoredproc >

    < type CFINPUT = 'text' id = "txtIDNumber" value = "" #spResult.IDNumber # "/ >"

    I am able to name a TEXT of ENTRY CF as above the code value,

    < select id = "lstNumber" value = "#spResult.lstNumber #" > < / select >

    but it does not affect the value of my result of the query to SELECT entry.

    Is it possible to assign a value to the query result SELECTION control?

    I tried to use JavaScript that works if I pass a number, but it does not work if I pass a query result,

    Your help is very appreciated,

    Kind regards

    Iccsi,

    @Iccsi,

    My bad!  Yes, you will either need to the CFOUTPUT tag (that you commented out in your code) but without specifying a query or change the CFLOOP query CFOUTPUT = "Notes".  If one of these should work:

    OR

    -Carl V.

  • Export the results of the research of several PDF files

    Hi all

    I have a set of over 100 000 documents PDF, and seeks to identify those documents that contain a set of four numbers.  Preforably I would like to export this list in the format in which I can link to each document - ideally an Excel xls document.  Any advice on the export of an index search in Adobe or any other proposed option would be very useful.  Thanks in advance.

    See you soon,.

    Terry

    You will need Acrobat X or higher to do this, but here's how I would perform this task:

    (1) create an index of full text of the document as a whole (and I guess your 100K files all contain searchable text content)

    (2) run your search index via the advanced search of Acrobat functionality

    (3) save results to one. CSV file, which was a long-awaited feature that came to Acrobat X

    (4) when you open it. CSV in Excel (you can save as .xls (x) one more flexibility), you will have a list of file names, then a sublist of the page where the search took place

    (5) from there, you'll need to manipulate the data in the Excel worksheet to list the full filepaths for each line, how you should then be able to open the file directly from your Excel sheet.

    Doing the open to the exact PAGE Excel sheet is a bit more complex, but it is also possible with some VB scripts.  You can search for it on the web if you want an example of code.

    FYI, I approach this concept a little differently in my book, where I use a simple VB script instead of paths, I say just to point out that there are several options to set up the links once you're in Excel.

    Hope that helps!

    Jason Covey

    PDF Litigation Solutions, LLC

    www.pdflitigationguide.com

  • Compare the result of a query with a number and return a message

    Hello
    I have the following query in oracle 9i:

    SELECT COUNT (*)
    OF hourly_files
    WHERE date_received = TO_DATE ((SELECT TO_CHAR (SYSDATE - INTERVAL '1' DAY, 'DDMMYYYY')
    (THE DOUBLE), 'DDMMYYYY');

    This will produce a number of lines required

    I need to compare the number of output with another number hardcoded (threshold) and print an appropriate example message

    If the result of the query above is 18000 and the number of threshold is fixed at 20000, then output a meesage:

    Number of files received less than 2000

    Any help will be very appreciated!

    Thank you.
    SQL> ed
    Wrote file afiedt.buf
    
      1  SELECT CASE WHEN COUNT(*) >5 THEN 'Number is > than 5'
      2              WHEN COUNT(*) <1 THEN 'Its less than 1'
      3  ELSE 'Its in between'
      4  END
      5  FROM emp
      6* WHERE deptno=20
    SQL> /
    
    CASEWHENCOUNT(*)>5
    ------------------
    Its in between
    
    SQL> SELECT COUNT(*) FROM emp
      2  WHERE deptno=10;
    
      COUNT(*)
    ----------
             3
    
  • How to run SQL and export the results to Excel

    My task is to run a custom SQL script and create an Excel file through SQL Developer running from the command line (called by a scheduled script). Is this possible using SQL Developer?

    First, the thing I will try is to run a report user-defined in SQL Developer and save the results in an Excel file. Only 16000 result lines, but took 10 minutes to do the export and still cannot complete. Is there another way to do it?

    Thank you very much.

    Can't be done, but this is requested already exchanging SQL Developer, you can vote here and add weight to the possible future implementation.

    Kind regards
    K.

Maybe you are looking for