Select Query Results to a .csv file????

Hello All,
I have a question in Oracle, if anyone knows how to do this. Please help me.
How can I get the results of select query in Oracle loaded into a Excel file (.csv) file.
Thanks in Advance,
Sarada.

Hi Sarada,
as a csv is nothing more than a list of Comma Separated Values your best shot is to simply read do this with your values. read each value in an iteration add them to a string / stringbuffer and add a "," between them. When you read then next line in the ResultSet you just add a carriage return to the end. Depending on what format you want your csv list in.
After you written all of this into a String you write this out to a file (unless you want to do it slower and write them line by line whenever you read them).
Hope this helps,
Kalle

Similar Messages

  • Exporting query result set into CSV file using Forms

    Hi ,
    My requirement is
    -> I need to create a form where I have a Multi line text box and two button.
    -> When I enter a query in text box and click on Execute button, It should execute a select query.
    -> After execution, Result set needs to be exported into an Excel file.
    Please give a hint how to do this????
    Thanks,
    maddy

    as you are using text item to write SQL query by the user
    so for that you need to use the exec_sql package to parse the text items query and get definitions and values of the columns being
    resulted in the result set of the query.
    once your query is execute to the desired connection then you need to use fetch the result to the CSV file by use of the TEXT_io package
    which will open the text file with .csv extension and you have to pass the each line to that text file with comma separated values as "ss","rr" etc.
    or you can use the ole2 package to call the excel application and then fetch the data of exe_sql query to that.

  • Export query results to a CSV file

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

    Following code is from asktom. I have modified to include column heading. This will get your desired CSV file for a given query.
    create or replace function  dump_csv( p_query     in varchar2,
                                          p_separator in varchar2
                                                        default ',',
                                          p_dir       in varchar2 ,
                                          p_filename  in varchar2 )
    return number
    AUTHID CURRENT_USER
    is
        l_output        utl_file.file_type;
        l_theCursor     integer default dbms_sql.open_cursor;
        l_columnValue   varchar2(2000);
        l_status        integer;
        l_colCnt        number default 0;
        l_separator     varchar2(10) default '';
        l_cnt           number default 0;
         l_colDesc          dbms_sql.DESC_TAB;
    begin
        l_output := utl_file.fopen( p_dir, p_filename, 'w' );
        dbms_sql.parse(  l_theCursor,  p_query, dbms_sql.native );
        for i in 1 .. 255 loop
            begin
                dbms_sql.define_column( l_theCursor, i,
                                        l_columnValue, 2000 );
                l_colCnt := i;
            exception
                when others then
                    if ( sqlcode = -1007 ) then exit;
                    else
                        raise;
                    end if;
            end;
        end loop;
        dbms_sql.define_column( l_theCursor, 1, l_columnValue, 2000 );
        l_status := dbms_sql.execute(l_theCursor);
         dbms_sql.describe_columns(l_theCursor,l_colCnt, l_colDesc);
         l_separator := '';
         for lColCnt in 1..l_colCnt
         loop          
                utl_file.put( l_output, l_separator ||  '"' || Upper(l_colDesc(lColCnt).col_name) || '"');
                   l_separator := p_separator;
         end loop;
         utl_file.new_line( l_output );
        loop
            exit when ( dbms_sql.fetch_rows(l_theCursor) <= 0 );
            l_separator := '';
            for i in 1 .. l_colCnt loop
                dbms_sql.column_value( l_theCursor, i,
                                       l_columnValue );
                utl_file.put( l_output, l_separator ||  '"' ||
                                        l_columnValue || '"');
                l_separator := p_separator;
            end loop;
            utl_file.new_line( l_output );
            l_cnt := l_cnt+1;
        end loop;
        dbms_sql.close_cursor(l_theCursor);
        utl_file.fclose( l_output );
        return l_cnt;
    end dump_csv;The original link is below.
    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:95212348059
    Thanks,
    Karthick.

  • Exporting query results into a csv file using arabic and hebrew chars

    Hi,
    iv'e encountered a problem, using plsql to export a query into a csv file.. the arabic turns into question mark. Do you have any idea why?

    Usually this indicates a mismatch between client and database character set.
    How do you export this query?
    What is your database version?
    What is your client OS?
    T.

  • Show Select query result in the text file.

    Hi all,
    i want to show my select statment records in the text file.
    thanks in advance.
    Mob.

    you cannot do a select in a stored procedure.
    you could do something like
    SQL> set serverout on
    SQL> spool output.txt
    SQL> declare
           x varchar2(40);
         begin
           select * into x from dual;
           dbms_output.put_line(x);
         end;
    X
    SQL> spool offor use the utl_file package (more powerfull, less secure, write on the db-server instead of the sqlplus-client)

  • How to output a query results into a text file

    How to output a query results into a text file instead of outputing it to the screen..
    is there a way for us to write a SQL query which specifies to output the query results to a text file.
    Pls let me know how to do it
    Thanking u in advance
    regards
    Muraly

    Muraly,
    If you are using SQL*Plus 8.1.6 or later, you can also spool output to a file in HTML format, eg
    SET MARKUP HTML ON SPOOL ON PREFORMAT OFF ENTMAP ON
    SPOOL c:\temp\report.html
    SELECT DEPARTMENT_NAME, CITY
    FROM EMP_DETAILS_VIEW
    WHERE SALARY>12000;
    SPOOL OFF
    SET MARKUP HTML ENTMAP OFF
    In iSQL*Plus 9.0.1 (the browser-based interface to SQL*Plus) onwards, you can also send the HTML output to a new web browser window, or an html file -- much easier than the command line method.
    Alison

  • Display the query result in an Excel file??

    hi there..
    am writing one script file that queries my DB and display the query result in an Excel file??
    i.e: if my query is :
    select col1, col2
    from table;
    and i want the results to dispalys in 2 col. in an Excel spreadsheet..
    Appreaciating ur cooperation..
    Mourad

    set colsep to a delimiter that is not normally part of your data like |
    also setup the environment with these other setup commands
    Set Echo Off;
    Set Concat Off;
    Set Pagesize 9999;
    Set Feedback Off;
    Set Verify Off;
    Set Term Off;
    Set Space 0;
    Set Colsep '|'
    Set Underline Off;
    If you wanted to use a comma delimiter the setup would be same but the set colsep='","'
    with the addition of concatenating a " on the first col and last col of the query
    eg.
    -- if first col and last_col are character types then
    SELECT '"'||col1,....,last_col||'"'
    FROM table;
    Otherwise if either is a number they would have to be converted with a TO_CHAR

  • How to Compare 2 CSV file and store the result to 3rd csv file using PowerShell script?

    I want to do the below task using powershell script only.
    I have 2 csv files and I want to compare those two files and I want to store the comparision result to 3rd csv file. Please look at the follwingsnap:
    This image is csv file only. 
    Could you please any one help me.
    Thanks in advance.
    By
    A Path finder 
    JoSwa
    If a post answers your question, please click &quot;Mark As Answer&quot; on that post and &quot;Mark as Helpful&quot;
    Best Online Journal

    Not certain this is what you're after, but this :
    #import the contents of both csv files
    $dbexcel=import-csv c:\dbexcel.csv
    $liveexcel=import-csv C:\liveexcel.csv
    #prepare the output csv and create the headers
    $outputexcel="c:\outputexcel.csv"
    $outputline="Name,Connection Status,Version,DbExcel,LiveExcel"
    $outputline | out-file $outputexcel
    #Loop through each record based on the number of records (assuming equal number in both files)
    for ($i=0; $i -le $dbexcel.Length-1;$i++)
    # Assign the yes / null values to equal the word equivalent
    if ($dbexcel.isavail[$i] -eq "yes") {$dbavail="Available"} else {$dbavail="Unavailable"}
    if ($liveexcel.isavail[$i] -eq "yes") {$liveavail="Available"} else {$liveavail="Unavailable"}
    #create the live of csv content from the two input csv files
    $outputline=$dbexcel.name[$i] + "," + $liveexcel.'connection status'[$i] + "," + $dbexcel.version[$i] + "," + $dbavail + "," + $liveavail
    #output that line to the csv file
    $outputline | out-file $outputexcel -Append
    should do what you're looking for, or give you enough to edit it to your exact need.
    I've assumed that the dbexcel.csv and liveexcel.csv files live in the root of c:\ for this, that they include the header information, and that the outputexcel.csv file will be saved to the same place (including headers).

  • How to call a SP with dynamic columns and output results into a .csv file via SSIS

    hi Folks, I have a challenging question here. I've created a SP called dbo.ResultsWithDynamicColumns and take one parameter of CONVERT(DATE,GETDATE()), the uniqueness of this SP is that the result does not have fixed columns as it's based on sales from previous
    days. For example, Previous day, customers have purchased 20 products but today , 30 products have been purchased.
    Right now, on SSMS, I am able to execute this SP when supplying  a parameter.  What I want to achieve here is to automate this process and send the result as a .csv file and SFTP to a server. 
    SFTP part is kinda easy as I can call WinSCP with proper script to handle it.  How to export the result of a dynamic SP to a .CSV file? 
    I've tried
    EXEC xp_cmdshell ' BCP " EXEC xxxx.[dbo].[ResultsWithDynamicColumns ]  @dateFrom = ''2014-01-21''"   queryout  "c:\path\xxxx.dat" -T -c'
    SSMS gives the following error as Error = [Microsoft][SQL Server Native Client 10.0]BCP host-files must contain at least one column
    any ideas?
    thanks
    Hui
    --Currently using Reporting Service 2000; Visual Studio .NET 2003; Visual Source Safe SSIS 2008 SSAS 2008, SVN --

    Hey Jakub, thanks and I did see the #temp table issue in our 2008R2.  I finally figured it out in a different way... I manage to modify this dynamic SP to output results into
    a physical table. This table will be dropped and recreated everytime when SP gets executed... After that, I used a SSIS pkg to output this table
    to a file destination which is .csv.  
     The downside is that if this table structure ever gets changed, this SSIS pkg will fail or not fully reflecting the whole table. However, this won't happen often
    and I can live with that at this moment. 
    Thanks
    --Currently using Reporting Service 2000; Visual Studio .NET 2003; Visual Source Safe SSIS 2008 SSAS 2008, SVN --

  • Select query resulting in redo?

    Hi All,
    Does select query results in redo? In what cases this happens?
    Regards,
    Sphinx

    mtefft wrote:
    Another possibility is that the SELECT query invokes a PL/SQL function that performs insert, update or delete.
    This is a poor practice for a number of reasons but they are out there.
    Disagree with that. Proof:
    SQL> create table x(y number);                                   
    Table created.                                                   
    SQL> create function f return number as                          
      2  begin                                                       
      3  insert into x values (2);                                   
      4  return 1;                                                   
      5  end;                                                        
      6  /                                                           
    Function created.                                                
    SQL> select dummy, f() from dual;                                
    select dummy, f() from dual                                      
    ERROR at line 1:                                                 
    ORA-14551: cannot perform a DML operation inside a query         
    ORA-06512: at "HR.F", line 3                                     

  • How to insert the select query result into table?

    How to insert the select query result into table?
    SELECT  top 20 creation_time  
            ,last_execution_time 
            ,total_physical_reads
            ,total_logical_reads  
            ,total_logical_writes
            , execution_count 
            , total_worker_time
            , total_elapsed_time 
            , total_elapsed_time / execution_count avg_elapsed_time
            ,SUBSTRING(st.text, (qs.statement_start_offset/2) + 1,
             ((CASE statement_end_offset 
              WHEN -1 THEN DATALENGTH(st.text)
              ELSE qs.statement_end_offset END 
                - qs.statement_start_offset)/2) + 1) AS statement_text
    FROM sys.dm_exec_query_stats AS qs
    CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st
    ORDER BY total_elapsed_time / execution_count DESC;
    Thanks,
    Tirumala

    1. SELECT INTO
    Below method will create table when data is inserted from one table to another table. Its useful when you need exactly same datatype as source table.
    Use AdventureWorks2008R2;
    Go
    ---Insert data using SELECT INTO
    SELECT AddressLine1, City
    INTO BothellAddresses
    FROM Person.Address
    where City = 'Bothell';
    GO
    ---VERIFY DATA
    Select AddressLine1, City
    FROM BothellAddresses
    ---DROP TABLE
    DROP TABLE BothellAddresses
    GO
    2. INSERT INTO SELECT
    Below method will need table to be created prior to inserting data. Its really useful when table is already created and you want insert data from
    another table.
    Use AdventureWorks2008R2;
    Go
    ---Create Table
    CREATE TABLE BothellAddresses (AddressLine1 NVARCHAR(60), City NVARCHAR(30))
    ---Insert into above table using SELECT
    INSERT INTO BothellAddresses(AddressLine1, City)
    SELECT AddressLine1, City
    FROM Person.Address
    where City = 'Bothell';
    ---VERIFY DATA
    Select AddressLine1, City
    FROM BothellAddresses
    ---DROP TABLE
    DROP TABLE BothellAddresses
    GO
    Regards,
    Vishal Patel
    Blog: http://vspatel.co.uk
    Site: http://lehrity.com

  • Select query results into excel file

    Hi,
    I want to put the results of a select query in an csv file(tab separated columns). I dont want to spool command for this . Is there any other method to do this.
    Thanks

    To get data from oracle to excel to use odbc driver to achive this.

  • How to - extract query result set in CSV and make multiple files if result set is huge.

    I have a query which returns millions of rows. I need to extract those rows in CSV files. Having said that i want to keep these files under a limit of 500 MB . Result set can be distributed among multiples files but each file can not be > 500 MB in size.
    How to achieve this?

    You may use this standard! procedure from Blushadow and produce something useful for your need. https://community.oracle.com/message/6499123#6499123

  • Select statement reults to a CSV file, refuses to run

    Hi,
    have this query that outputs to a CSV file, or at least it should.
    Any help resolving this will be greatfully recieved
    Thanks
    set feedback off
    set pages 0
    set lines 120
    spool /gtxappl/Stock_Mirroring/Results/pyfs_Demandstock_supply.csv
    select upper('item_id,shipnode_key,jda_demand')
    from dual;
    select a.item_id || ',' || b.shipnode_key || ',' || sum (b.quantity)
    from yfs_inventory_item a, yfs_inventory_demand b
    where b.demand_type = 'JDA_RSRV.ex'
    and b.inventory_item_key = a.inventory_item_key;
    group by a.item_id, b.Shipnode_KEY
    spool off

    Hi,
    sorry about that. Its running now, was using an older version of the script, this is not the correct one.
    Any idea as to how i could write a shell script so that an application called TWS can execute the SQL and be passed back a success or failure code, 0= success >0= error for a sript very similar to the one mentioned before hand?
    Thanks

  • Saving query results to a flat file

    Hello Experts!
    We have a very specific issue on our current project and I would like to know if any of you have ever done something similar. We are taking query results from BW (after complex calculations, some based on SY-DATE) and saving them to flat files to transfer to a SQL database structure on the Enterprise Portal. From here, the portal team renders the information into more "static" dashboards that include mouse over features and even limited drilldown (i.e. no matter where a user clicks the report always drills down on profit center)
    There are many reasons why the model is set up as such (mostly training of executive level end users), and even though it doesn't mesh with the idea that BW could do this work on its own, we have to work with what we have.
    We have come up with 3 possible ways to save this data to flat files and hopefully someone can tell us which might be the most effective.
    1.) Information Broadcasting. If we broadcast XML files to the portal, will the portals team be able to read that data into a SQL database? Is there another way to use broadcasting to create and send a flat file to specific location?
    2.) RSCRM_BAPI. This transaction seems to not support texts.
    3.) Open Hub. In order to get the open hub to work, we first have to save all of our query results to direct write data store objects using APD. (calculations based on current date, for example, would require daily full loads to the underlying data providers otherwise.)
    What is the best way to accomplish this? Is information broadcasting capable of doing this?
    Thanks!

    Hi Adam,
    Do you have to use flat files to load the information to a SQL database? (if so maybe someone else has a suggestion on which way would be the best).
    I try to stay away from flat file uploads as there is a lot of manual work involved. May I suggest setting up a connection to your SQL table in the DBCON table and then writing a small abap program to push data into the SQL database (which you can automate).
    1) Use APD to push data into a table within BW.
    2) Go to transaction SM30 > table DBCON and setup a new entry specifying the conncection parameters to your SQL database.
    3) In SE38 Write an ABAP program along the folloing lines (assuming the connection you set in DBCON is named conn1:
    data: con_name like dbcon-con_name
    con_name = 'conn1'.
    exec sql.
      set connection :con_name
    endexec.
    ****have a select statement which reads data from your table which the data is saved from the APD into an internal table**********
    ****loop on the internal table and have a SQL insert statement to insert the records into the SQL table as below******
    exec sql.
    insert into <SQL TABLE> (column names seperated by ,)
    values (column names of the internal table seperated by ,)  if the internal table is named itab the columns have to be specified as :itab-column1
    If you decide to take this approach you may find more info on DBCON and the process in sdn. Good Luck!
    endexec.

Maybe you are looking for

  • Is Essbase Server Release 11.1.1.3.0 supported on RHEL5 (5.6) 64-bit OS?

    Guys, I have "Essbase Server Release 11.1.1.3.0 - 64bit" running on "Red Hat Enterprise Linux AS release 4 (Nahant Update 6)". The package number for "Essbase Server Release 11.1.1.3.0" for 32-bit and 64-bit is same e.g. "V17389-01 – Essbase Server"

  • ISE fall-back

    Hi I have 2 ISE 1.2 I configured ISE1(192.168.1.1) as primary for PAN, MNT and PSN and it work fine Now I am configuring ISE2(192.168.2.1) as secondary PAN, MNT and PSN In normal situation, the user are authenticated on ISE1 My goal : If ISE1 is unav

  • Import full events into a new iPhoto library

    I want to divide my iPhoto library into two: one personal, one work.  In creating the new iPhoto library, I exported the events I wanted and imported them into the new library.  Much to my surprise, they were all imported into one event.  I did split

  • AE CS6: Render glitches with timeremap expressions

    Version: 11.0 OS: Mac 10.7.4 Source Footage: .ai files Problem: First of all, we've been using this method for character animation since AE 7.0.  We have had minor glitches here and there, but nothing consistent enough to a real problem.  We're curre

  • My iphone is lock i can't use sim card

    my iphone is lock verssion i can't use sim card ,phone details as below IPHONE 4S 16 GB SERIAL NUMBER  7S037K1FA4S IMEI   012422006920617 COUNTRY LOCK ENGLAND