CSV output of a sql query

Hello All,
I have a table named as 'product' having two columns prod_name and prod_status.
Table Name: product
prod_name prod_status
bag A
Pen A
Pencil B
Eraser C
Paper A
Now if I will write a query
select prod_name from product where prod_status='A';
Then it will return me output as:
prod_name
bag
Pen
Paper
But I want output as:
prod_name
bag,Pen,Paper
I have checked solution for this problem on many thread but havent found any good solution. I want it for 10G.
Thanks in advance
Edited by: Tushky on Aug 4, 2010 2:04 AM

It looks quite amazing that you did not found any solution for this porbs on forum. Anyways try the below query, it works in 10g.
To write in CSV file, spool a CSV file and copy the contents....
with c as
(select 'bag' str from dual union all
select 'pen' str from dual union all
select 'paper' str from dual )
select rtrim(xmlagg(xmlelement(e,str||',').extract('//text()')),',')  op
from c
SQL> /
OP
bag,pen,paper

Similar Messages

  • How to Suppress The Output of a SQL Query In Oracle 11gR2

    Hi Friends,
    I am using oracle version 11.2.0.1, I have set a cronjob which will run on every 15 minutes and give us a log file mentioning the execution time taken for that SQL query:-
    For example:
    SQL> set timing on;
    SQL> SELECT objProp FROM aradmin.arschema WHERE (schemaId = 175);
    OBJPROP+
    --------------------------------------------------------------------------------+
    *6\60006\4\0\\60008\40\0\60009\4\0\\60010\4\0\\60018\4\0\\600*
    *22\4\68\1\63\AR:jRL#*
    Elapsed: 00:00:00.00
    The above query will return the output as well as the time taken for execution of the query. I want to suppress the output of the query and only want the time taken to be printed. Is it possible by set commands. I have marked the output as bold and made it Italic.
    Please help me at the earliest.
    Regards,
    Arijit

    >
    I am using oracle version 11.2.0.1, I have set a cronjob which will run on every 15 minutes and give us a log file mentioning the execution time taken for that SQL query:-
    The above query will return the output as well as the time taken for execution of the query. I want to suppress the output of the query and only want the time taken to be printed. Is it possible by set commands. I have marked the output as bold and made it Italic.
    >
    How would that even be useful?
    A query from a tool such as sql*plus is STILL going to send the output to the client and the client. You can keep sql*plus from actually displaying the data by setting autotrace to trace only.
    But that TIME TAKEN is still going to include the network time it takes to send ALL rows that the query returns across the network.
    That time is NOT the same as the actual execution time of the query. So unless you are trying to determine how long it takes to send the data over the network your 'timing' method is rather flawed.
    Why don't you tell us WHAT PROBLEM you are trying to solve so we can help you solve it?

  • How to write the output of an SQL query to a text file?

    I am using Oracle 11g and SQL plus.
    I have a large table called rating.
    Whenever I do
    SQL> select * from rating;
    The output goes much beyond what the SQL Plus screen can show. I want to therefore store the output of this query into a text file.
    How can this be done? Please help. Thanks.

    SQL> SPOOL results.txt
    SQL> select * from rating;
    SQL> SPOOL OFF

  • Script task to convert output from a sql query into send mail task body formatting

    SSIS 2008R2 Version
    Code from script task
       Microsoft SQL Server Integration Services Script Task
       Write scripts using Microsoft Visual C# 2008.
       The ScriptMain is the entry point class of the script.
    using System;
    using System.Data;
    using Microsoft.SqlServer.Dts.Runtime;
    using System.Windows.Forms;
    namespace ST_29dd6843bd6c4aee9b1656c1bbf55ba8.csproj
        [System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
        public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
            #region VSTA generated code
            enum ScriptResults
                Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
                Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
            #endregion
            public void Main()
                Variables varCollection = null;
                string header = string.Empty;
                string message = string.Empty;
                Dts.VariableDispenser.LockForWrite("User::gsEmailMessage");
                Dts.VariableDispenser.LockForWrite("User::gsWebserviceName");
                Dts.VariableDispenser.LockForWrite("User::gsNoOfCallsInADay");
                Dts.VariableDispenser.LockForWrite("User::gsCalledBySystem");
                Dts.VariableDispenser.GetVariables(ref varCollection);
                //Set the header message for the query result
                if (varCollection["User::gsEmailMessage"].Value == string.Empty)
                    header = "Hi, Count is greater then 50 :\n\n";
                    //header = "Execute SQL task output sent using Send Email Task in SSIS:\n\n\n";
                    header += "----------------------------------------------------------------------------------------------------------------------" + "\n";
                    header += string.Format("{0}\t\t\t\t{1}\t\t{2}\n", "WebService Name", "No Of Calls In A Day", "Called By System");
                    header += "----------------------------------------------------------------------------------------------------------------------" + "\n";
                    varCollection["User::gsEmailMessage"].Value = header;
                //Format the query result with tab delimiters
                     message = String.Format("<HTML><BODY><P>{0}</P><P>{1}</P><P>{2}</P></BODY></HTML>",
                                            varCollection["User::gsWebserviceName"].Value,
                                            varCollection["User::gsNoOfCallsInADay"].Value,
                                            varCollection["User::gsCalledBySystem"].Value);
                varCollection["User::gsEmailMessage"].Value = varCollection["User::gsEmailMessage"].Value + message + "\n";
                Dts.TaskResult = (int)ScriptResults.Success;
    Above code will return data in below format and then i send this output in aemail using send mail task.
    Hi, count is greater then 50 :
    WebService Name                                                         
    No Of Calls In A Day                        Called By System
    WebServiceone                                                     1                             
    Internetbutiken
    WebServiceGetdetailstwo                                                  1                             
    Internetbutiken
    Servicenamethree                                                            2                             
    MOB
    As you can see above code is not in align as if we service name is shorter then 2nd column get disallign and its not look good.I need output should be like below.
    Hi, count is greater then 50 :
    WebService Name                                                         
    No Of Calls In A Day                        Called By System
    WebServiceone                                                              1                             
    Internetbutiken
    WebServiceGetdetailstwo                                              1                             
    Internetbutiken
    Servicenamethree                                                          2                             
    MOB
    Please suggest something...
    Thanks 
    SR_MCTS

    See code explained here
    http://microsoft-ssis.blogspot.in/2013/08/sending-mail-within-ssis-part-2-script.html
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs
    This will not help.As I am not creating smtp connectin ,send from ,send to in script task.I am just creating email body from sql output.

  • Unexpected line breaks in output of a sql query

    Hi,
    I have a query which looks like:
    set pages 0
    set feed off
    set newp 0
    set lines 350
    select LPAD(SUBSTR(COLUMN1,1,23),23),LPAD(SUBSTR(COLUMN2,1,42),42), SUBSTR(TO_CHAR(START_TIME,'HH24:MI:SS'),1,8),SUBSTR(TO_CHAR(END_TIME,'HH24:MI:SS'),1,8)
    FROM TABLE1;
    When executed using SQL*Plus this query puts a line break after each column and hence I get a record on several rows on the screen.
    But the last two columns are printed on the same line. I suspect the LPAD is causing some problem.
    I have two databases. It works perfectly on one and not on the other.
    Is there a oracle parameter due to which the result is affected?
    T&R,
    BRK

    Try this:
    set pages 0 feed off newp 0 lines 350 trims on
    select LPAD(SUBSTR(COLUMN1,1,23),23)
         , LPAD(SUBSTR(COLUMN2,1,42),42)
         , TO_CHAR(START_TIME,'HH24:MI:SS')
         , TO_CHAR(END_TIME,'HH24:MI:SS')
    FROM TABLE1;

  • Expected output  for my sql query

    Hi can you please tell me how to get the my expected output from the table work_invoice_hold_t
    where i need to compare company code , tot_cust_no,sto_no,sales_date and trans_type='HOLD'
    for example below i am comparing comp_code 1801 ,tot_cust_no,sto_no and sales_date.... when i compare them i need to get sales date record like
    1801     1504522002      601     120618     1     142          HOLD      Y
    COMP_CODE   TOT_CUST_NO     STO_NO   SALES_DATE   CASH_NO    RECEIPT_NO   TRANS_TYPE  PROCESSED
    2300                  0062090790                121     120306                  3              132                       HOLD                 Y
    1801                  1504522002                601     120306            1              142                        HOLD                 Y
    1801                  1504522002                601     120306            1              142               UNHOLD        3
    1801                  1504522002                 601     120618            1              142                       HOLD           Y
    EXPECTED OUTPUT:
    2300                  0062090790                121     120306                  3              132                       HOLD                 Y
    1801                  1504522002                 601     120618            1              142                       HOLD           Y

    Hi Thank you for providing the necessary help.
    Here is another requirement for my query.
    First query should be merged into second query. In the second query we are using one more table like "I_INVOICE_INFO_T_LOG_V"
    that is when we put both first and second queries together i need to get the output like below:
    601     STO     1504522002     120618     142     1     1801     HOLD
    121     STO     0062090790     120306     132     3     2300     HOLD
    table structure is:
    CREATE TABLE RIMS.I_INVOICE_INFO_T_LOG_V
    REG_DATE VARCHAR2(6 BYTE),
    STO_NO VARCHAR2(3 BYTE),
    SALES_DATE VARCHAR2(6 BYTE),
    CASH_NO NUMBER(5),
    RECEIPT_NO NUMBER(10),
    ORDER_NO NUMBER(10),
    TOT_CUST_NO VARCHAR2(13 BYTE),
    CONTROL_NO NUMBER(10),
    INV_ADM_COST_FR VARCHAR2(1 BYTE),
    VAT_OBLIGED VARCHAR2(1 BYTE),
    ART_NO VARCHAR2(8 BYTE),
    SOLD_QTY NUMBER(10),
    SOLD_AMOUNT NUMBER(10),
    CUR_CODE VARCHAR2(3 BYTE),
    ORIG_INVO VARCHAR2(10 BYTE),
    CUSDEL_NO NUMBER(2),
    SEQ_NO_SORT NUMBER(10),
    GROUP_ID_PROD NUMBER(10),
    GROUP_ID_TXT NUMBER(10),
    CUSDEL_TYPE VARCHAR2(2 BYTE),
    VAT_CODE VARCHAR2(10 BYTE),
    VAT_RATE NUMBER(6,2),
    TIMESTAMP DATE,
    INV_TYPE VARCHAR2(1 BYTE),
    INS_USER VARCHAR2(30 BYTE),
    MACHINE VARCHAR2(64 BYTE),
    SEQ NUMBER(22) NOT NULL
    sample data :
    SET DEFINE OFF;
    Insert into RIMS.I_INVOICE_INFO_T_LOG_V
    (REG_DATE, STO_NO, SALES_DATE, CASH_NO, RECEIPT_NO, ORDER_NO, TOT_CUST_NO, CONTROL_NO, INV_ADM_COST_FR, VAT_OBLIGED, ART_NO, SOLD_QTY, SOLD_AMOUNT, CUR_CODE, CUSDEL_NO, SEQ_NO_SORT, GROUP_ID_PROD, CUSDEL_TYPE, VAT_CODE, VAT_RATE, TIMESTAMP, SEQ)
    Values
    ('120306', '121', '120306', 3, 132,
    0, ' 0062090790', 0, '0', '1',
    '40043234', 8, 20800, 'DKK',
    0, 0, 0, '01',
    '0', 2500, TO_DATE('10/21/2005 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 916052);
    Insert into RIMS.I_INVOICE_INFO_T_LOG_V
    (REG_DATE, STO_NO, SALES_DATE, CASH_NO, RECEIPT_NO, ORDER_NO, TOT_CUST_NO, CONTROL_NO, INV_ADM_COST_FR, VAT_OBLIGED, ART_NO, SOLD_QTY, SOLD_AMOUNT, CUR_CODE, CUSDEL_NO, SEQ_NO_SORT, GROUP_ID_PROD, CUSDEL_TYPE, VAT_CODE, VAT_RATE, TIMESTAMP, SEQ)
    Values
    ('120306', '601', '120306', 1, 142,
    0, ' 1504522002', 0, '0', '1',
    '40047760', 2, 200, 'GBP',
    0, 0, 0, '01',
    '0', 1750, TO_DATE('10/21/2005 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 916053);
    Insert into RIMS.I_INVOICE_INFO_T_LOG_V
    (REG_DATE, STO_NO, SALES_DATE, CASH_NO, RECEIPT_NO, ORDER_NO, TOT_CUST_NO, CONTROL_NO, INV_ADM_COST_FR, VAT_OBLIGED, ART_NO, SOLD_QTY, SOLD_AMOUNT, CUR_CODE, CUSDEL_NO, SEQ_NO_SORT, GROUP_ID_PROD, CUSDEL_TYPE, VAT_CODE, VAT_RATE, TIMESTAMP, SEQ)
    Values
    ('120618', '601', '120618', 1, 142,
    0, ' 1504522002', 0, '0', '1',
    '20057057', 2, 400, 'GBP',
    0, 0, 0, '01',
    '0', 1500, TO_DATE('10/21/2005 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 916054);
    Insert into RIMS.I_INVOICE_INFO_T_LOG_V
    (REG_DATE, STO_NO, SALES_DATE, CASH_NO, RECEIPT_NO, ORDER_NO, TOT_CUST_NO, CONTROL_NO, INV_ADM_COST_FR, VAT_OBLIGED, ART_NO, SOLD_QTY, SOLD_AMOUNT, CUR_CODE, CUSDEL_NO, SEQ_NO_SORT, GROUP_ID_PROD, VAT_CODE, VAT_RATE, TIMESTAMP, SEQ)
    Values
    ('051020', '262', '051020', 11, 16,
    0, ' 1555792009', 0, '0', '1',
    '50043993', 3, 4800, 'GBP',
    0, 0, 0,
    '0', 1750, TO_DATE('10/21/2005 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 916055);
    for example:
    Second query
    SELECT DISTINCT workhold.sto_no AS bu_code,
    'STO' AS Bu_Type,
    AND workhold.processed='Y'...
    and ( first query condition)
    First query.
    WITH  got_cnt        AS
        SELECT  w.*    -- or list columns you want
        ,    COUNT (CASE WHEN trans_type = 'HOLD' THEN 1 END)
                OVER (PARTITION BY  comp_code, tot_cust_no, sales_date)
                    AS  hold_cnt
        ,    COUNT (CASE WHEN trans_type = 'UNHOLD' THEN 1 END)
                OVER (PARTITION BY  comp_code, tot_cust_no, sales_date)
                    AS  unhold_cnt
        FROM    work_invoice_hold_t  w
    SELECT sto_no as bu_code,'STO' as bu_type,tot_cust_no as cust_no,sales_date,receipt_no,cash_no as till_no,comp_code,trans_type-- or list columns you want
    FROM    got_cnt
    WHERE    hold_cnt    = 0
    OR    unhold_cnt    = 0
    First query output:
    601     STO     1504522002     120618     142     1     1801     HOLD
    121     STO     0062090790     120306     132     3     2300     HOLD
    Second Query:
    SELECT DISTINCT workhold.sto_no AS bu_code,
                               'STO' AS Bu_Type,
                               workhold.Tot_Cust_No AS Cust_No,
                               workhold.Sales_Date AS Sales_Date,
                               workhold.Receipt_No,
                               workHOLD.Cash_No AS Till_No,
                               workhold.Comp_Code,
                               workhold.Trans_Type AS on_hold_flag
                 FROM WORK_INVOICE_HOLD_V workhold,
                           I_INVOICE_INFO_T_LOG_V invlog
                WHERE
                TRIM (workhold.Tot_Cust_No) = TRIM (invlog.Tot_Cust_No)
                      AND TRIM (workhold.Cash_No) = TRIM (invlog.Cash_No)
                      AND TRIM (workhold.sales_date) = TRIM (invlog.sales_date)
                      AND TRIM (workhold.Receipt_No) = TRIM (invlog.Receipt_No)
                      AND TRIM (workhold.Sto_No) = TRIM (invlog.Sto_No)
                      AND workhold.processed='Y'
    output for second query:
    601     STO     1504522002     120618     142     1     1801     HOLD
    601     STO     1504522002     120306     142     1     1801     HOLD
    121     STO     0062090790     120306     132     3     2300     HOLD
    expected output:
    after checking the conditions for both 1 and 2 queries i need to get the output like below.
    601 STO 1504522002 120618 142 1 1801 HOLD
    121 STO 0062090790 120306 132 3 2300 HOLDEdited by: 891933 on Oct 2, 2012 1:18 AM

  • Can we generate the output of SQL Query in XML format ..

    Hi Team,
    Can we generate an XML doc for an SQL Query.
    I've seen in SQL Server 2000.It is generating the output of an SQL Query in xml format.
    select * from emp for xml auto
    The output looks like
    <emp EMPNO="7369" ENAME="SMITH" JOB="CLERK" MGR="7902" HIREDATE="1980-12-17T00:00:00" SAL="2800" DEPTNO="20"/><emp EMPNO="7370" ENAME="SMITH" JOB="CLERK" MGR="7902" HIREDATE="1980-12-17T00:00:00" SAL="2800" DEPTNO="10"/>

    Just a little bit of short hand.
    Get the XML out of your database, via HTTP
    Of course the easiest method is just to return an XMLType from a stored procedure and let the calling routine figure out what to do with it. Instead
    of that way though, I'll show you how to do it via HTTP. It's all completely built into 10g and is super easy to use.
    CREATE OR REPLACE VIEW emps_and_depts AS
    SELECT e.employee_id AS "EmployeeId",
    e.last_name AS "Name",
    e.job_id AS "Job",
    e.manager_id AS "Manager",
    e.hire_date AS "HireDate",
    e.salary AS "Salary",
    e.commission_pct AS "Commission",
    XMLFOREST (
    d.department_id AS "DeptNo",
    d.department_name AS "DeptName",
    d.location_id AS "Location"
    ) AS "Dept"
    FROM employees e, departments d
    WHERE e.department_id = d.department_id
    Some people hear web and immediately start salivating about security issues. Let me address that quickly. Just because you have the HTTP and/or
    FTP servers running in the database, that does not mean you have a security problem. For one, I would hope your databases are behind a firewall.
    Second, with the correct architecture (DMZ, app servers, etc) you can make this data available outside the firewall fairly transparently and third,
    just because it's on the web does not mean the data MUST be available on the internet. This is a good way to make your data available on your
    intranet. If you are worried about people INSIDE your firewall, that still doesn't preclude web based access. Follow Oracle security guidelines.
    Before I show you how to get to your data, let's talk about URLs and URIs. A URL is a Uniform Resource Locater and URI is a Uniform Resource
    Identifier. A URL is the way you would identify a document on the net, i.e. http://www.oracle.com is a URL. A URI is a more generic form of a URL.
    Oracle supports three types of URI: HTTPURIType - basically a URL (which would be like the URL above), XDURIType - a pointer to an XDB resource
    (usually an XML document but can be other objects), and DBURIType - a pointer to database objects.
    It's the DBURIType that we're going to concentrate on here. The DBURIType let's us reference database objects using a file/folder paradigm. The
    format for a DBURI is /oradb/<schema>/<table>. Oradb is shorthand for the database; it is not the database name or SID. My database is named XE
    but I still use oradb in the DBURI. For example, the view we created above is in my XE database, is owned by HR (at least in my case) and is called
    EMPS_AND_DEPTS. This can be referenced as /oradb/HR/EMPS_AND_DEPTS.
    If the view had many rows and you wanted only one of them, you can restrict it by including a predicate. The documentation for XDB has a great
    write up on Using DBURIs.In our case, we are going to write out the entire document. Now that you understand that the DBURI is a pointer to
    objects in our instance, we can use that to access the data as a URL.
    The format for the URL call is http://<machinename>:<port>/<DBURI>
    In my case, my XE database is running on a machine called mach1 and is listening on port 8080. So to see the view we created above, I open my
    browser and navigate to: http//mach1:8080/oradb/HR/EMPS_AND_DEPTS
    The created URL will be as http//mach1:8080/oradb/PUBLIC/EMPS_AND_DEPTS
    If your database is set up correctly and listening on port 8080 (the default), your browser should ask you to login. Login as the user who created the
    view (in my case HR). You should now get an XML document displayed in your browser.
    And that's it. It doesn't get much simpler than that. If you get rid of the descriptive text above, it basically comes down to:
    Create a table or view
    Open your web browser
    Enter a URL
    Enter a user ID and password
    View your XML
    If you notice, Oracle formatted the data as XML for us. Our view returns scalar columns and an XML fragment called Dept. Oracle formatted the
    return results into an XML format.
    And as a side note, if you look closely, you'll see that my URL has PUBLIC where I said to put HR. PUBLIC is a synonym for all objects that your
    logged in user can see. That way, if your user has been granted select access on many schemas, you can use PUBLIC and see any of them.

  • Possible APEX BUG - Export to CSV from SQL Query (updateable report)

    I'm getting a the following sql error - just by enabling the Export to a CSV file from a SQL Query (updateable report) and selecting the export link - anyone have an idea what I could as a workaround?
    ORA-06550: line 1, column 45: PLS-00103: Encountered the symbol "1" when expecting one of the following: begin case declare exit for goto if loop mod null pragma raise return select update while with <an identifier> <a double-quoted delimited-identifier> <a bind variable> << close current delete fetch lock insert open rollback savepoint set sql execute commit forall merge pipe
    Error ERR-1000 Unable to determine LOV from "declare function x return varchar2 is begin 1 Not Checked;1 Not Checked,2 Review Passed;2 Review Passed,3 Reviewed w/ Issues;3 Reviewed w/ Issues,4 Not Applicable;4 Not Applicable return null; end; begin wwv_flow_utilities.g_query := x; end;".
    OK
    report error:
    ORA-20001: Error fetching column value: ORA-20001: Query must begin with SELECT or WITH

    Frank,
    I received your email with this same question so I'll just respond here. Our internet-facing hosted site apex.oracle.com allows you to request a workspace and, after the request is approved and the workspace provisioned, to develop applications there. If you already have an application that you need some help with, you can import/install it into your workspace on apex.oracle.com. This makes it easy to demonstrate problems to others who might be able to help.
    Sometimes it will be necessary for you to create developer accounts in your workspace in order for others to use your Application Builder. You can post usernames/passwords here or you can convey those privately to those offering their services. In either case, you'd want to remove or disable those accounts as soon as the problem is resolved. For problems that I ask to see demonstrated on apex.oracle.com, it is not necessary for you to create an account for me. I can do that as our group runs the site. I just need to know your workspace name and application ID.
    Scott

  • Need sql query to convert rows to columns

    Im using oracle 11g.
    I have data in a table as below: Column names are type,month,percentage
    TYPE      MONTH   PERCENTAGE
    A1         JAN-2013     100
    A2         JAN-2013     100
    A3         JAN-2013     95
    A4         JAN-2013     98
    A5         JAN-2013     99
    A6         JAN-2013     90
    A7         JAN-2013     92
    A1         FEB-2013     100
    A2         FEB-2013     99
    A3         FEB-2013     88
    A4         FEB-2013     67
    A5         FEB-2013     98
    A6         FEB-2013     95
    A7         FEB-2013     84
    The desired output using a sql query is as below
    TYPE     JAN-2013     FEB-2013
    A1         100             100
    A2         100             99
    A3         95               88
    A4         98               67
    A5         99               98
    A6         90               95
    A7         92               84

    Try this:
    select * from table_name
    PIVOT(   max(Percentage)
                     for MONTH
                     in ('JAN-2013','FEB-2013')
                     ) ;with data
    with t(TYPE,MONTH,PERCENTAGE) as
    SELECT 'A1', 'JAN-2013', 100
      FROM DUAL
    UNION ALL
    SELECT 'A2', 'JAN-2013', 100
      FROM DUAL
    UNION ALL
    SELECT 'A3', 'JAN-2013', 95
      FROM DUAL
    UNION ALL
    SELECT 'A4', 'JAN-2013', 98
      FROM DUAL
    UNION ALL
    SELECT 'A1', 'FEB-2013', 100
      FROM DUAL
    UNION ALL
    SELECT 'A2', 'FEB-2013', 99
      FROM DUAL
    UNION ALL
    SELECT 'A3', 'FEB-2013', 88
      FROM DUAL
    UNION ALL
    SELECT 'A4', 'FEB-2013', 67
      FROM DUAL
    select * from t PIVOT(   max(Percentage)
                     for MONTH
                     in ('JAN-2013','FEB-2013')
                     ) ;

  • Classic Report CSV output failed to parse SQL query

    Hi,
    I'm trying to get a CSV output from a classic report. I'm generating the report based on a PL/SQL block that will return an SQL query. But when i download the CSV excel just gives me a:
    failed to parse SQL query:
    ORA-00936: Missing expression
    and shows me the query that the application is trying to parse. I'm also using bind variables (page items) in the PL/SQL block that is returning me the SQL query. I think that the reason that it fails to parse the query is that the query that is shown in excel has no bind variable values.
    Anyone got any ideas?

    Hi Arif,
    run your page in debug mode and check out the SQL statement which is actually executed for the report. That might help to diagnose what is going wrong.
    If you wish you can also post the report SQL statement which is getting executed.
    Regards
    Patrick
    My Blog: http://www.inside-oracle-apex.com
    APEX Plug-Ins: http://apex.oracle.com/plugins
    Twitter: http://www.twitter.com/patrickwolf

  • How do i get a output in CSV of a SQL query executed via SQL Command prompt

    Hi All,
    I have a question with reference to SQL command prompt. I have a sql query which runs properly and gives proper execution in SQL Management console in GUI.
    This report is used to pull the free disk space report of our servers
    As i want to schedule it as a report so i want to script it to run via SQL command prompt. I made the script and it works fine if i enter it in SQL command prompt. When i try to extract the output to a CSV File it fails. Below is the details of the command
    i am using to query to pull the data. Can anyone help me in getting the output of this query in SQL command prompt.
    sqlcmd -W -s , -S Servers FQDN
    use operationsmanager
    Go
    Query:"select Path, InstanceName, SampleValue 
    from PerformanceDataAllView pdv with (NOLOCK)
    inner join PerformanceCounterView pcv on pdv.performancesourceinternalid = pcv.performancesourceinternalid
    inner join BaseManagedEntity bme on pcv.ManagedEntityId = bme.BaseManagedEntityId
    where SampleValue < '20' and CounterName='% Free Space' and TimeSampled > '2014-08-06 11:00:00.00'
    order by countername, timesampled" -s "," -o "C:\DataSqlCmd.csv"
    Go
    When i enter the command without the quotes when the query is starting and ending and also without the output command (-s "," -o "C:\DataSqlCmd.csv") it is working and shows the output in the command prompt. Below is the screen shot for
    your reference.
    Due to security reasons i have to erase the server names:
    But when i add the line to extract the output ( -s "," -o "C:\DataSqlCmd.csv") It gives me this error:
    The exact command would be:
    sqlcmd -W -s , -S CINMLVSCOM01.e2klab.ge.com
    use operationsmanager
    Go
    "select Path, InstanceName, SampleValue 
    from PerformanceDataAllView pdv with (NOLOCK)
    inner join PerformanceCounterView pcv on pdv.performancesourceinternalid = pcv.performancesourceinternalid
    inner join BaseManagedEntity bme on pcv.ManagedEntityId = bme.BaseManagedEntityId
    where SampleValue < '20' and CounterName='% Free Space' and TimeSampled > '2014-08-06 11:00:00.00'
    order by countername, timesampled" -s "," -o "C:\DataSqlCmd.csv" -h-1
    Go
    saying the syntax is not correct or some thing as per the below screenshot.
    Can any one please help. Below is just the query whi i use to get the output in SQL management studio.
    Can any one make a command for the below quer so i can directly execute and test for getting the output.
    select Path, InstanceName, SampleValue 
    from PerformanceDataAllView pdv with (NOLOCK)
    inner join PerformanceCounterView pcv on pdv.performancesourceinternalid = pcv.performancesourceinternalid
    inner join BaseManagedEntity bme on pcv.ManagedEntityId = bme.BaseManagedEntityId
    where SampleValue < '20' and CounterName='% Free Space' and TimeSampled > '2014-08-06 11:00:00.00'
    order by countername, timesampled
    Gautam.75801

    Can you try the below query?
    select Path, InstanceName, SampleValue
    from PerformanceDataAllView pdv with (NOLOCK)
    inner join PerformanceCounterView pcv on pdv.performancesourceinternalid = pcv.performancesourceinternalid
    inner join BaseManagedEntity bme on pcv.ManagedEntityId = bme.BaseManagedEntityId
    where SampleValue < 20 and CounterName like '% Free Space' and TimeSampled > '2014-08-06 11:00:00.00'
    order by countername, timesampled
    -- replace the below query part in the below SQLCMD C:\>SQLCMD -S SERVERNAME -E -d operationsmanager -Q "select * from sys.databases ds with (nolock) where name='master'" -s "," -o "F:\PowerSQL\MyData.csv" -h -1
    SQLCMD -S SERVERNAME -E -d OperationsManager -Q "select Path, InstanceName, SampleValue
    from PerformanceDataAllView pdv with (NOLOCK)
    inner join PerformanceCounterView pcv on pdv.performancesourceinternalid = pcv.performancesourceinternalid
    inner join BaseManagedEntity bme on pcv.ManagedEntityId = bme.BaseManagedEntityId
    where SampleValue < '20' and CounterName='% Free Space' and TimeSampled > '2014-08-06 11:00:00.00'
    order by countername, timesampled" -s "," -o "c:\MyData.csv" -h -1
    Refer for the other ways 
    http://dba.stackexchange.com/questions/23566/writing-select-result-to-a-csv-file
    --Prashanth

  • SQL query Output  exceeds 65000 rows in excel

    Hi,
    I have a SQL file attached to my concurrent program. The query in the SQL file returns tab separated output that i need to email as a csv through the same SQL file.
    The issue I am facing is that the query returns about 157000 records but only 65536 are being displayed in the excel worksheet.
    How can I get all the records by accommodating them in multiple worksheets of the same excel file?
    Please help!
    I am using EBS 11i.
    Code I am using in SQL file:
    set pages 3000
    set lines 300
    set heading off
    set term off
    set feedback off
    set verify off
    set echo off
    set serverout off
    spool /tmp/TEST.csv
    select 'Header'
    from dual
    SELECT column1||CHR(9)||column2
    FROM staging_table
    spool off
    set lines 1000 pages 40 head off echo off veri off
    select 'cd /tmp; cat $XX_TOP/install/sql/disclaimer.txt > x.dat; cat '||'/tmp/TEST.csv'||' | uuencode '||'/tmp/TEST.csv'
    ||' > '||substr('/tmp/TEST.csv',1,length('/tmp/TEST.csv')-4)||'.dat >> x.dat'
    ||' ; mail -s ''' ||'&1'||''' '||'&2'||' < x.dat'
    ||' ; rm '||substr('/tmp/TEST.csv',1,length('/tmp/TEST.csv')-4)||'.dat'||' ;'
    from dual
    list
    spool /tmp/email.txt
    spool off
    host chmod 777 /tmp/email.txt
    host /tmp/email.txt
    Thanks
    Edited by: user10648285 on May 13, 2011 5:27 AM

    open a blank Excel (2007 version), go to Data tab, then from External Data click From Text, select the CSV file (That having more than 65k records), click import, then from "start import at row" select 65001 and click next button, select delimiter as Comma, click Next button and filaly finish.
    In this way you will have the data after 65k rows in excel. Now you can simply open that cvs file in excel then you will have first 65k records (remening part will be discarded).
    So now you have two excel files and you can paste it in two diff tab.
    Note - you can repeate this activity if you have more than 130000 records...

  • Saving the output of a .sql file in .csv format

    Hi,
    I am saving the output of a .sql file in .csv format. But the problem is , the record of few columns have "new line" character in it, so when it is getting saved in .csv format, those records are coming in multiple rows, but they should come in one single row in single block. Please advise how to overcome this problem.
    Regards,
    Niraj

    Hi Guys,
    I guess, there is a misunderstanding.
    He is talking about the issue caused as a result of the data containing a "CRLF" ( Carriage return Line feed ) .
    That is mainly a data issue.
    The query i presume, must be right.
    I guess you should be able to fix it using some string functions.
    Some thing similar to this
    CREATE TABLE ASH (NAME VARCHAR2(10))
    SELECT REPLACE(NAME, CHR(13)||CHR(10), 'ISH') FROM ASH;
    SELECT REPLACE(NAME, CHR(10), 'ISH') FROM ASH;
    SELECT REPLACE(NAME, CHR(13), 'ISH') FROM ASH;
    depending on the type of new line whether it is CR or LF. or CRLF.
    Regards
    Ashish/-

  • SQL Query results to CSV as two worksheets

    I'm trying to take two SQL queries and get the results sent to a CSV file on two worksheets.  Looking online I have not found a solid example of using the Excel ComObject to create a CSV then add a new worksheet to the CSV file.  An added bonus
    would be using AutoFit on the columns so everything is easily visible.
    Code found online got me the following script which does work, however it takes 12 minutes to pipe the SQL queries to Excel.  Switching to a CSV and the script executes in 5 seconds.
    This is another nice to have, I was also looking the best way to look at the results (only 1 column) and depending on the length of the data, insert what Excel would call a Cell thereby shifting cells RIGHT but so far have found no clear examples of how
    to accomplish that.  My guess would be modifying my SQL queries but I've posted a question on StackOverFlow and someone suggested modifying the PowerShell Table created from the SQL dataset.Tables
    Code:
    $docs = "C:\Scripts\Output.xlsx"
    If (Test-Path $docs){Remove-Item $docs}
    Function Run-Query {
    param([string[]]$queries,[string[]]$sheetnames)
    ## - Create an Excel Application instance:
    $xlsObj = New-Object -ComObject Excel.Application
    $xlsObj.DisplayAlerts = $false
    $xlsWb = $xlsobj.Workbooks.Add(1)
    ## - Create new Workbook and Sheet (Visible = 1 / 0 not visible)
    $xlsObj.Visible = 0
    $time = 2
    for ($i = 0; $i -lt $queries.Count; $i++){
    $percentage = $i / $time
    $remaining = New-TimeSpan -Seconds ($time - $i)
    $message = "{0:p0} complete" -f $percentage, $remaining
    Write-Progress -Activity "Creating Daily Reboot Spreadsheet" -status $message -PercentComplete ($percentage * 100)
    $query = $queries[$i]
    $sheetname = $sheetnames[$i]
    $xlsSh = $xlsWb.Worksheets.Add([System.Reflection.Missing]::Value, $xlsWb.Worksheets.Item($xlsWb.Worksheets.Count))
    $xlsSh.Name = $sheetname
    ### SQL query results sent to Excel
    $SQLServer = 'ServerName'
    $Database = 'DataBase'
    ## - Connect to SQL Server using non-SMO class 'System.Data':
    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $SqlConnection.ConnectionString = "Server = $SQLServer; Database = $Database; Integrated Security = True"
    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
    $SqlCmd.CommandText = $query
    $SqlCmd.Connection = $SqlConnection
    ## - Extract and build the SQL data object '$Table2':
    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
    $SqlAdapter.SelectCommand = $SqlCmd
    $DataSet = New-Object System.Data.DataSet
    $SqlAdapter.Fill($DataSet)
    $SqlConnection.Close()
    $Table1 = $DataSet.Tables["Table"]
    ## - Build the Excel column heading:
    [Array] $getColumnNames = $Table1.Columns | SELECT ColumnName
    ## - Build column header:
    [Int] $RowHeader = 1
    foreach ($ColH in $getColumnNames)
    $xlsSh.Cells.item(1, $RowHeader).font.bold = $true
    $xlsSh.Cells.item(1, $RowHeader) = $ColH.ColumnName
    $RowHeader++
    ## - Adding the data start in row 2 column 1:
    [Int] $rowData = 2
    [Int] $colData = 1
    foreach ($rec in $Table1.Rows)
    foreach ($Coln in $getColumnNames)
    ## - Next line convert cell to be text only:
    $xlsSh.Cells.NumberFormat = "@"
    ## - Populating columns:
    $xlsSh.Cells.Item($rowData, $colData) = $rec.$($Coln.ColumnName).ToString()
    $ColData++
    $rowData++; $ColData = 1
    ## - Adjusting columns in the Excel sheet:
    $xlsRng = $xlsSH.usedRange
    [void] $xlsRng.EntireColumn.AutoFit()
    }#End For loop.
    #Delete unwanted Sheet1.
    $xlsWb.Sheets.Item('Sheet1').Delete()
    #Set Monday to Active Sheet upon opening Workbook.
    $xlsWb.Sheets.Item('Cert').Activate()
    ## ---------- Saving file and Terminating Excel Application ---------- ##
    $xlsFile = "C:\Scripts\Output.xlsx"
    [void] $xlsObj.ActiveWorkbook.SaveAs($xlsFile)
    $xlsObj.Quit()
    ## - End of Script - ##
    start-sleep 2
    While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsRng)) {'cleanup xlsRng'}
    While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsSh)) {'cleanup xlsSh'}
    While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsWb)) {'cleanup xlsWb'}
    While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsObj)) {'cleanup xlsObj'}
    [gc]::collect() | Out-Null
    [gc]::WaitForPendingFinalizers() | Out-Null
    }#End Function
    $queries = @()
    $queries += "Query1"
    $queries += "Query2"
    $sheetnames = @('Cert','Prod')
    Run-Query -queries $queries -sheetnames $sheetnames

    Here's what I ended up with that accomplishes my goal.  I learned it's not possible to create a CSV with two worksheets since Excel will allow this but the CSV cannot be saved with the second worksheet.  Instead, I create two CSV files then merge
    them into one Excel workbook, one CSV per worksheet.  In my case, this happens in 5 seconds.  There is one thing which must be mentioned, I've seen this script fail the first time it is run but will successfully run the second time.
    Also note, after much trial and error, this code correctly cleans up the Excel ComObject!!  -Thanks go to JRV.
    $docs = "D:\Scripts\MonthlyReboots.xlsx"
    IF (Test-Path $docs){Remove-Item $docs}
    $csv1 = "D:\Scripts\Cert.csv"
    IF (Test-Path $csv1){Remove-Item $csv1}
    $csv2 = "D:\Scripts\Prod.csv"
    IF (Test-Path $csv2){Remove-Item $csv2}
    Function Run-Query {
    param([string[]]$queries,[string[]]$sheetnames,[string[]]$filenames)
    Begin{
    $SQLServer = 'ServerName'
    $Database = 'DataBase'
    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $SqlConnection.ConnectionString = "Server = $SQLServer; Database = $Database; Integrated Security = True"
    $Excel = New-Object -ComObject Excel.Application
    $Excel.Visible = 0
    $dest = $Excel.Workbooks.Add(1)
    }#End Begin
    Process{
    For($i = 0; $i -lt $queries.Count; $i++){
    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
    $SqlCmd.CommandText = $queries[$i]
    $SqlCmd.Connection = $SqlConnection
    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
    $SqlAdapter.SelectCommand = $SqlCmd
    $DataSet = New-Object System.Data.DataSet
    $SqlAdapter.Fill($DataSet)
    $DataSet.Tables[0] | Export-Csv -NoTypeInformation -Path "D:\Scripts\$($sheetnames[$i]).csv" -Force
    }#end for loop.
    }#End Process
    End{
    $SqlConnection.Close()
    #Excel magic test!
    For($i = 0; $i -lt $queries.Count; $i++){
    $loopy = (Resolve-Path -Path $filenames[$i]).ProviderPath
    $Book = $Excel.Workbooks.Open($loopy)
    $next = $Excel.workbooks.Open($loopy)
    $next.ActiveSheet.Move($dest.ActiveSheet)
    $xlsRng = $dest.ActiveSheet.UsedRange
    $xlsRng.EntireColumn.AutoFit() | Out-Null
    $dest.sheets.item('Sheet1').Delete()
    $xlsFile = "D:\Scripts\MonthlyReboots.xlsx"
    [void] $Excel.ActiveWorkbook.SaveAs($xlsFile)
    $Excel.Quit()
    While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsRng)) {'cleanup xlsRng'}
    While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($next)) {'cleanup xlsSh'}
    While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($Book)) {'cleanup xlsWb'}
    While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)) {'cleanup xlsObj'}
    [gc]::collect() | Out-Null
    [gc]::WaitForPendingFinalizers() | Out-Null
    }#End end block.
    }#End function run-query.
    $queries = @()
    $queries += @'
    Select * from table1
    $queries += @'
    Select * from table2
    $sheetnames = @("Cert","Prod")
    $filenames = @("D:\Scripts\Prod.csv","D:\Scripts\Cert.csv")
    Run-Query -queries $queries -sheetnames $sheetnames -filenames $filenames
    Start-Sleep -Milliseconds 50
    Invoke-Item D:\Scripts\MonthlyReboots.xlsx

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

Maybe you are looking for

  • ALE Configuration using BAPI.

    I am adding BAPI in the ALE configuration and as a part of this configuration I have added BAPI in bd64 and I am not understanding how to proceed with other steps. I want to know the output format for this BAPI from SAP.Answers will be rewarded with

  • DELETE ADJACENT DUPLCATES

    Hi Experts, I wonder why delete adjacent duplicate sometimes doesn't work and sometimes doesn't. Any idea? Thanks in advance. Regards, Rose

  • 3FI_SL_C1_TT - Procedure of extracting data with delta

    Dear experts, I try to load FI-SL data with delta. We use extractor 3FI_SL_C1_TT and have implemented the start routine from note 577644 to create 0balance within the transformation. Delta is only available for actuals so we select data only for valu

  • Et_FORM_DATA_ADD issue

    I am catching the et_FORM_DATA_ADD, BeforeAction = Falseevent on deliveries and production receipts. I am then calling a print routine. When we upgraded to 2007 patch 38, select deliveries and production receipts started printing out twice (ie duplic

  • Best Resolutions for HD to Flash videos on website

    Hi, What is your recommendation for the correct size in pixels for a Flash player on a website? We're producing video in Premiere Pro CS4 from original 1920x1080 AVCHD footage shot on Canon HG21 cameras. We can make the Flash player on our website an