Saving result from query into CSV file

Hi folks,
in our application we're generating pages source using general packages (like htp, owa_util, ...). and in this part I'm a really beginner.
I want to modify source one of our page, I want to add functionality to enable save result from query (cursor) into CSV file, to enable user choose place where generated file will be created and also change file name.
I searched this forum and I found procedure, that could be useful:
procedure p_getcsv is
cursor cur is
       select 'a1' col1, 'b1' col2, 'c1' col3 from dual
   union  select 'a2' col1, 'b2' col2, 'c2' col3 from dual
   union  select 'a3' col1, 'b3' col2, 'c3' col3 from dual;
   begin
        -- Set the MIME type
        owa_util.mime_header( 'application/octet', FALSE );
        -- Set the name of the file
        htp.p('Content-Disposition: attachment; filename="test.csv"');
        -- Close the HTTP Header
        owa_util.http_header_close;
        -- Loop through all rows in EMP
        for x in cur
        loop
            -- Print out a portion of a row,
            -- separated by commas and ended by a CR
             htp.prn(x.col1||','|| x.col2||','||x.col3|| chr(13));
        end loop;        
   end;What peace of code should I add to procedure that is generating web page to enable calling this procedure and whole saving process?
Can anybody help me with this?
Many thanks,
Tomas
Message was edited by:
Tomeo

Hi Marc,
thanks for reply, problem is that I'm not using APEX application, I'm just generating web page code straight using oracle general packages.
But I found this solution (maybe some tunning will be good):
In page where I want to display Download i have
  begin
         htp.anchor2 (
                       curl  =>  ... .p_getcsv'||'?term=2005&crn=123,
                       ctext => 'Download Class List'
         HTP.br;
      end;
...si I'm calling p_getcsv procedure:
  procedure p_getcsv( term  IN stvterm.stvterm_code%TYPE DEFAULT NULL,
                       crn   IN sirasgn.sirasgn_crn%TYPE DEFAULT NULL) is
   v_length      NUMBER;
   v_file_name   VARCHAR2 (2000);
   temp_blob  blob;
   line RAW(32767);
   begin
         DBMS_LOB.CREATETEMPORARY(temp_blob, TRUE);
         FOR i IN 1..6  LOOP
            line := UTL_RAW.CAST_TO_RAW(i||','||term||','||crn||',AAA,BBB,CCC'||chr(10));
            DBMS_LOB.WRITEAPPEND(temp_blob, LENGTH(UTL_RAW.CAST_TO_VARCHAR2(line)), line);
         END LOOP;
          v_file_name := 'ClassList.csv';
          v_length  := DBMS_LOB.getlength (temp_blob);
          -- set up HTTP header
             -- use an NVL around the mime type and
             -- if it is a null set it to application/octect
             -- application/octect may launch a download window from windows
           OWA_UTIL.mime_header (NVL ('csv', 'application/octet'), FALSE);
           -- set the size so the browser knows how much to download
           HTP.p ('Content-length: ' || v_length);
           -- the filename will be used by the browser if the users does a save as
           HTP.p (   'Content-Disposition:  attachment; filename="'
              || REPLACE (REPLACE (SUBSTR (v_file_name,
                                           INSTR (v_file_name, '/') + 1
                                   CHR (10),
                                   NULL
                          CHR (13),
                          NULL
              || '"'
             -- close the headers
             OWA_UTIL.http_header_close;
            -- download the BLOB
             WPG_DOCLOAD.download_file (temp_blob);
             -- release temporary blob
             dbms_lob.freetemporary(temp_blob);  
   end;Regards,
Tomas

Similar Messages

  • Select from ODS into .CSV file

    hi guru's !
    I need to build an abap program that reads a number of fields from an ODS (table) and stores this result in a .CSV file.
    I have never done this before so any documentation or examples would be greatly appreciated !
    thanks alread !

    hi,
    http://help.sap.com/saphelp_nw04/helpdata/en/c7/dc833b2ab3ae0ee10000000a11402f/frameset.htm
    Regards,
    Sourabh

  • Saving result from sp_executesql into a variable and using dynamic column name - getting error "Error converting data type varchar to numeric"

    Im getting an error when running a procedure that includes this code.
    I need to select from a dynamic column name and save the result in a variable, but seem to be having trouble with the values being fed to sp_executesql
    DECLARE @retval AS DECIMAL(12,2)
    DECLARE @MonthVal VARCHAR(20), @SpreadKeyVal INT
    DECLARE @sqlcmd AS NVARCHAR(150)
    DECLARE @paramdef NVARCHAR(150)
    SET @MonthVal = 'Month' + CAST(@MonthNumber AS VARCHAR(2) );
    SET @SpreadKeyVal = @SpreadKey; --CAST(@SpreadKey AS VARCHAR(10) );
    SET @sqlcmd = N' SELECT @retvalout = @MonthVal FROM dbo.CourseSpread WHERE CourseSpreadId = @SpreadKeyVal';
    SET @paramdef = N'@MonthVal VARCHAR(20), @SpreadKeyVal INT, @retvalout DECIMAL(12,2) OUTPUT'
    --default
    SET @retval = 0.0;
    EXECUTE sys.sp_executesql @sqlcmd,@paramdef, @MonthVal = 'Month4',@SpreadKeyVal = 1, @retvalout = @retval OUTPUT;
    SELECT @retval
    DECLARE @return_value DECIMAL(12,2)
    EXEC @return_value = [dbo].[GetSpreadValueByMonthNumber]
    @SpreadKey = 1,
    @MonthNumber = 4
    SELECT 'Return Value' = @return_value
    Msg 8114, Level 16, State 5, Line 1
    Error converting data type varchar to numeric.

    Please follow basic Netiquette and post the DDL we need to answer this. Follow industry and ANSI/ISO standards in your data. You should follow ISO-11179 rules for naming data elements. You should follow ISO-8601 rules for displaying temporal data. We need
    to know the data types, keys and constraints on the table. Avoid dialect in favor of ANSI/ISO Standard SQL. And you need to read and download the PDF for: 
    https://www.simple-talk.com/books/sql-books/119-sql-code-smells/
    >> I need to select from a dynamic column name and save the result in a variable, but seem to be having trouble with the values being fed to sp_executesql <<
    This is so very, very wrong! A column is an attribute of an entity. The idea that you are so screwed up that you have no idea if you want
    the shoe size, the phone number or something else at run time of this entity. 
    In Software Engineering we have a principle called cohesion that says a model should do one and only one task, have one and only one entry point, and one and only one exit point. 
    Hey, on a scale from 1 to 10, what color is your favorite letter of the alphabet? Yes, your mindset is that level of sillyity and absurdity. 
    Do you know that SQL is a declarative language? This family of languages does not use local variables! 
    Now think about “month_val” and what it means. A month is a temporal unit of measurement, so this is as silly as saying “liter_val” in your code. Why did you use “sp_” on a procedure? It has special meaning in T-SQL.  
    Think about how silly this is: 
     SET @month_val = 'Month' + CAST(@month_nbr AS VARCHAR(2));
    We do not do display formatting in a query. This is a violation of at the tiered architecture principle. We have a presentation layer. But more than that, the INTERVAL temporal data type is a {year-month} and never just a month. This is fundamental. 
    We need to see the DDL so we can re-write this mess. Want to fix it or not?
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Import data from oracle database table into csv file

    Hi
    I have to import data from a table into a csv file. Could anyone suggest the best method to do it? My application is JSP as frontend and have put business logic in servlet.
    Thanks in advance.

    FastReader from wisdomforce will help you quickly export data into csv file. http://www.wisdomforce.com
    fastreader can be called and executed as an external process ( Runtime.exec(..) ) to extract data from Oracle tables into flat file

  • How to get sql query data and write into csv file?

    I am writing to seek help, in how can I create bat. script which can execute the following logic:
    connection to the database
    run sql query
    create CSV file
    output query data, into CSV file
    save the CSV file
    osql
    -S 84.18.111.111
    -U adw
    -P rem
    -i "c:\query.sql"
    send ""
    sed -e 's/,\s\+/,/g' MCI_04Dec2014.csv > localNoSpaces.csv
    -o "c:\MCI_04Dec2014.csv"
    This what i have so far, and I am little struggling with the logic after creating CSV file. I am unable to get the above script to work, please advice further, where I may be going wrong. 
    Can you create if statement logic within window's script, to check for null parameters or data feeds?
    Any hints would be most appreciated. 

    Thank you for your reply. 
    Apology for posting the code irrelevant to the forum, as I am still novice scripting user.  
    My goal is to create window's script which can compute the above logic and send the final output file (csv), to FTP folder. 
    Can this logic be implemented via bat. script, if so, is there a example or tutorial i could follow, in order to achieve my task. 
    Any help would be much appreciated. 

  • Insert Data into Table from TXT or CSV file !!!!!

    Dear All,
    Recently I have started working on APEX. In Oracle Forms, we used to use TEXT_IO for inserting records into tables from txt files. Now I want to do the same thing in apex 3.2. How can I insert data into tables from txt of csv files.
    Waiting of your valuable suggestions.
    With kind regards,
    Yousuf.

    Yousuf
    wwv_flow_files is used by APEX to hold uploaded files.
    If you incorporate a file browse item on you page, browse for the selected file, then submit the page (having the PL/SQL process described as an on suibmit process) then what I detailed should work.
    If you don't need users to have access to this then just go to Home>Utilities>Data Load/Unload in APEX and there is a handy load utility there that does it all for you.
    Cheers
    Ben

  • Problem in converting table data into CSV file

    Hi All,
    In my Process i need to convert my error table data into csv file,my data is converted as csv file by using OdisqlUnload function,but the column headers are not converted,i use another procedure for converting column headers but iam getting below error ...
    com.sunopsis.sql.SnpsMissingParametersException: Missing parameter string.find, string.find
    SQL: import string import java.sql as sql import java.lang as lang import re sourceConnection = odiRef.getJDBCConnection("SRC") output_write=open('C:/Oracle/Middleware/Oracle_ODI2/oracledi/pro/PRO.txt','r+') myStmt = sourceConnection.createStatement() my_query = "select * FROM E$_LOCAL_F0911Z1" my_query=my_query.upper() if string.find(my_query, '*') > 0: myRs = myStmt.executeQuery(my_query) md=myRs.getMetaData() collect=[] i=1 while (i <= md.getColumnCount()): collect.append(md.getColumnName(i)) i += 1 header=','.join(map(string.strip, collect)) elif string.find(my_query,'||') > 0: header = my_query[7:string.find(my_query, 'FROM')].replace("||','||",',') else: header = my_query[7:string.find(my_query, 'FROM')] print header old=output_write.read() output_write.seek(0) output_write.write (header+'\n'+old) sourceConnection.close() output_write.close()
    And i used below code for converting.......
    import string
    import java.sql as sql
    import java.lang as lang
    import re
    sourceConnection = odiRef.getJDBCConnection("SRC")
    output_write=open('C:/Oracle/Middleware/Oracle_ODI2/oracledi/pro/PRO.txt','r+')
    myStmt = sourceConnection.createStatement()
    my_query = "select FROM E$_COMPANY"*
    *my_query=my_query.upper()*
    *if string.find(my_query, '*') > 0:*
    *myRs = myStmt.executeQuery(my_query)*
    *md=myRs.getMetaData()*
    *collect=[]*
    *i=1*
    *while (i <= md.getColumnCount()):*
    *collect.append(md.getColumnName(i))*
    *i += 1*
    *header=','.join(map(string.strip, collect))*
    *elif string.find(my_query,'||') > 0:*
    *header = my_query[7:string.find(my_query, 'FROM')].replace("||','||",',')*
    *else:*
    *header = my_query[7:string.find(my_query, 'FROM')]*
    *print header*
    *old=output_write.read()*
    *output_write.seek(0)*
    *output_write.write (header+'\n'+old)*
    *sourceConnection.close()*
    *output_write.close()*
    Any one can you help regarding this
    Edited by: 30021986 on Oct 1, 2012 6:04 PM

    This may not be an option for you but in pinch you may want to consider outputing your data to an MS Spreadsheet, then saving it as a CSV. It's somewhat of a cumbersome process, but it will get you by for now.
    You will need to change your content type to application/vnd.ms-excel.
    <% response.setContentType("application/vnd.ms-excel"); %>

  • CLR to get the SQL Server Data into .CSV File

    Hi,
    I transformed 10 columns 1000 rows from the source table to 1 column 1000 rows in the destination table by making the comma separated columns ( Just like ..
    Insert into DestinationTable
    SELECT col1+','+col2 ....
    FROM SourceTable
    Then I want to take this column into CSV file.
    I dont have the rights to command shell.
    I heard that we may use CLR procedure for this. Can someone throw light?

    using System;
    using System.IOM
    using System.Data;
    using System.Data.SqlClient;
    using System.Data.SqlTypes;
    using Microsoft.SqlServer.Server;
    public class ExportFileClass {
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void export_file()
    using (SqlConnection connection = new SqlConnection(
    "context connection=true"))
    connection.Open();
    // Operation to open file goes here.
    SqlCommand command = new SqlCommand("SELECT col FROM YourTable");
    // Consume result set and write rows.
    Build this from the command line:
    sn -k keypair.snk
    csc /target:library /keyfile:keypair.snk exportfile.cs
    Then run in SQL Server (assuming that the files are in C:\temp on the SQL
    Server machine:
    [sql]
    USE master
    go
    -- To be able to create an external-access assembly, we need to load
    -- the key, the assembly is signed with. The key needs a password, but we
    -- don't need to know the password.
    DECLARE @sql nvarchar(MAX),
            @password char(40)
    SELECT @password = convert(char(36), newid()) + 'Ab4?'
    SELECT @sql = 'CREATE ASYMMETRIC KEY slog_loopback FROM FILE = ' +
                  '''C:\temp\keypair.snk'' ' +
                  'ENCRYPTION BY PASSWORD = ''' + @password + ''''
    PRINT @sql
    EXEC(@sql)
    -- And then a login to carry the permission.
    CREATE LOGIN exportfile$asymkey FROM ASYMMETRIC KEY ExportFile
    GRANT EXTERNAL ACCESS ASSEMBLY TO exportfile$asymkey
    go
    -- Now we can go back to our regular database and create the assembly.
    USE youddatabase
    go
    CREATE ASSEMBLY ExportFile FROM 'C:\temp\exportfile.dll'
    WITH PERMISSION_SET = EXTERNAL_ACCESS
    go
    CREATE PROCEDURE ExportFile AS
    EXTERNAL NAME ExportFile.ExportFileClass.export_file
    [sql]
    It is likely that you will have to do ask your DBA to do things in the
    master database.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Export batch data into CSV file using SQL SP

    Hi,
    I have created WCF-Custom receive adapter to poll Sql SP (WITH xmlnamespaces(DEFAULT 'Namespace' and For XML PATH(''), Type) . Get the result properly in batch while polling and but getting error while converting into CSV by using map.
    Please can anyone give me some idea to export SQL data into CSV file using SP.

    How are you doing this.
    You would have got XML representation for the XML batch received from SQL
    You should have a flat-file schema representing the CSV file which you want to send.
    Map the received XML representation of data from SQL to flat-file schema
    have custom pipeline with flat-file assembler on the assembler stage of the send pipeline.
    In the send port use the map which convert received XML from SQL to flat file schema and use the above custom flat-file disassembler send port
    If this answers your question please mark it accordingly. If this post is helpful, please vote as helpful by clicking the upward arrow mark next to my reply.

  • Procedure to save the output of a query into excel file or flat file

    Procedure to save the output of a query into excel file or flat file
    I want to store the output of my query into a file and then export it from sql server management studio to a desired location using stored procedure.
    I have run the query --
    DECLARE @cmd VARCHAR(255)
    SET @cmd = 'bcp "select * from dbo.test1" queryout "D:\testing2.xlsx;" -U "user-PC\user" -P "" -c '
    Exec xp_cmdshell @cmd
    error message--
    SQLState = 28000, NativeError = 18456
    Error = [Microsoft][SQL Server Native Client 10.0][SQL Server]Login failed for user 'user-PC\user'.
    NULL
    Goel.Aman

    Hello,
    -T:
    Specifies that the bcp utility connects to SQL Server with a trusted connection using integrated security. The security credentials of the network user,
    login_id, and password are not required. If
    –T is not specified, you need to specify
    –U and –P to successfully log in.
    -U:
    Specifies the login ID used to connect to SQL Server.
    Note: When the bcp utility is connecting to SQL Server with a trusted connection using integrated security, use the
    -T option (trusted connection) instead of the
    user name and password combination
    I would suggest you take a look at the following article:
    bcp Utility: http://technet.microsoft.com/en-us/library/ms162802.aspx
    A similar thread regarding this issue:
    http://social.msdn.microsoft.com/Forums/sqlserver/en-US/b450937f-0ef5-427a-ae3b-115335c0d83c/bcp-connection-error-sqlstate-28000-nativeerror-18456?forum=sqldataaccess
    Regards,
    Elvis Long
    TechNet Community Support

  • BULK INSERT from a text (.csv) file - read only specific columns.

    I am using Microsoft SQL 2005, I need to do a BULK INSERT from a .csv I just downloaded from paypal.  I can't edit some of the columns that are given in the report.  I am trying to load specific columns from the file.
    bulk insert Orders
    FROM 'C:\Users\*******\Desktop\DownloadURL123.csv'
       WITH
                  FIELDTERMINATOR = ',',
                    FIRSTROW = 2,
                    ROWTERMINATOR = '\n'
    So where would I state what column names (from row #1 on the .csv file) would be used into what specific column in the table.
    I saw this on one of the sites which seemed to guide me towards the answer, but I failed.. here you go, it might help you:
    FORMATFILE [ = 'format_file_path' ]
    Specifies the full path of a format file. A format file describes the data file that contains stored responses created using the bcp utility on the same table or view. The format file should be used in cases in which:
    The data file contains greater or fewer columns than the table or view.
    The columns are in a different order.
    The column delimiters vary.
    There are other changes in the data format. Format files are usually created by using the bcp utility and modified with a text editor as needed. For more information, see bcp Utility.

    Date, Time, Time Zone, Name, Type, Status, Currency, Gross, Fee, Net, From Email Address, To Email Address, Transaction ID, Item Title, Item ID, Buyer ID, Item URL, Closing Date, Reference Txn ID, Receipt ID,
    "04/22/07", "12:00:21", "PDT", "Test", "Payment Received", "Cleared", "USD", "321", "2.32", "3213', "[email protected]", "[email protected]", "", "testing", "392302", "jdal32", "http://ddd.com", "04/22/03", "", "",
    "04/22/07", "12:00:21", "PDT", "Test", "Payment Received", "Cleared", "USD", "321", "2.32", "3213', "[email protected]", "[email protected]", "", "testing", "392932930302", "jejsl32", "http://ddd.com", "04/22/03", "", "",
    Do you need more than 2 rows? I did not include all the columns from the actual csv file but most of it, I am planning on taking to the first table these specfic columns: date, to email address, transaction ID, item title, item ID, buyer ID, item URL.
    The other table, I don't have any values from here because I did not list them, but if you do this for me I could probably figure the other table out.
    Thank you very much.

  • How to SAP data convert into csv file.

    hi,
    i have a one internal table , and i want to extract SAP data into csv file with filed separator ','(comma).
    Thanks

    you can use this coding for slove yours issue
    tables: vbak.
    Use type pool:
    TYPE-POOLS: TRUXS.
    parameters: p_erdat like vbak-erdat.
    DATA: COM TYPE C . For comma SEPERATOR
    data: begin of itab occurs 0,
          vbeln like vbak-vbeln,
          erdat like vbak-erdat,
          end of itab.
    DATA: ITAB1 TYPE TRUXS_T_TEXT_DATA OCCURS 0 .
    COM = ','.
    select vbeln
           erdat
           into table itab
           from vbak
           where erdat = p_erdat.
    FM:
    CALL FUNCTION 'SAP_CONVERT_TO_CSV_FORMAT'
    EXPORTING
       I_FIELD_SEPERATOR          = COM
      I_LINE_HEADER              =
      I_FILENAME                 =
      I_APPL_KEEP                = ' '
      TABLES
        I_TAB_SAP_DATA             =  ITAB
    CHANGING
       I_TAB_CONVERTED_DATA       = ITAB1
    EXCEPTIONS
      CONVERSION_FAILED          = 1
      OTHERS                     = 2
    IF SY-SUBRC <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    FM:
    CALL FUNCTION 'GUI_DOWNLOAD'
      EXPORTING
      BIN_FILESIZE                  =
        FILENAME                      = 'C:\TEST.CSV'
       FILETYPE                       = 'ASC'

  • How to query a csv file

    Hello I am new to cold fusion.
    I am wondering if there is a way to query a csv file using a read from cffile? Currently I have it setup as a cffile read and then I try to query the file using cffquery. Obviously this doesn't work because I have to set a datasource. Is there anyway to do this or any way to set a csv file as a data source? Any help or direction would be greatly appreciated.
    Thanks.

    You would have to read in the csv and create a query using QueryNew(). Once you have the csv in a query format, then you can perform query of queries to do most anything you want on the data. There is probably code already written out there to do the csv to query, you just need to find it. The query of queries is in the documentation. The only gotcha is that query of queries sorting and matching is case sensitive. Hope this helps.

  • How to import data from excel or csv files to Oracle table

    hello everybody,
    I am new here and new in Oracle. I would like to know the steps how to import data from excel or csv files to Oracle table.
    Let say I already have table inside the Oracle. Then my user give me the sets of data inside the Excel Worksheet.
    So, how can I import the excel data into Oracle table.
    Thank you in advance.
    cheers,
    shima

    Even easier. Download JDeveloper 11G from this site.
    Set up the database connection, right click on the table, select Import->Excel and specify your file to load it. On the import pop-up, you must view and update each tab indicating Columns, Data Types, and DML.
    Columns -- move the selected columns that you want to load to the box on the right
    Data Types -- select column name from second column to which the data for each column of the import file should load
    DML -- click this tab to generate the INSERT SQL
    Once done click 'Insert'

  • ADM Error processing results from query: Error: Index 0 out of range

    11.1.2.1
    When running quite a large book, we are getting the following error:
    ADM Error processing results from query: Error: Index 0 out of range
    The individual reports in the books are running fine.
    PS.  The report books that are giving this error run fine on 9.3.1
    Could this be a time-out issue and how do we resolve it?

    what is background datasource Essbase or HFM
    do you have lot of data in pov please try below
    >Do you have pov prompt
    >increase jvm heap size for report server in reporting server
    >Fr log files has some more detail

Maybe you are looking for

  • Intermittent lock up after boot

    My T60 will occasionally lock up after XP boots. No mouse or kbd. I have to press the power button to shut it down and after a reboot, it works fine. IF I play with the mouse cursor as soon as it appears on the screen at boot up, it never locks up. I

  • CRM 2011 JS giving errors

    I added an OnLoad Event to my Opportunity Form.  When the form loads I get the following error:  "Object doesn't support property or method 'setDisable'.  What am I doing wrong? // Microsoft Dynamics CRM 2011 Java Script // Name: New_Opportunity_New_

  • Superdrive: CD works/DVD does not

    I have a situation that I have not been able to find articles on. When I place a CD (audio for instance) into the superdrive of my iBook the appropriate program (iTunes in this case) works. If I place a DVD in the disc will not be able to be read. I

  • I made a MS patch-changer selecting ANY patch FROM MY KEYBOARD'S KEYS!

    Love the Nord Electro 3, hate the sequential up-down button for patch changes, especially with up to 20 per song. Almost decided to sell it and go back to the Nord Stage I had before, sacrificing sound quality for rapid and flexible patch changing ab

  • Why i cannot buy using my itune id?

    Why i can use my itune id? Can i buy gems clash of clan using my itune card?