SQL statement - Display expected results

I have this SQL statement:
SELECT DISTINCT ch.ch_status,cu.customer_id FROM contract co, contract_history ch, customer cu
      WHERE co.co_id = ch.co_id
      AND co.customer_id = cu.customer_id
      AND (cu.passportno= 'S1234567A' )
      AND cu.customer_id != 12345
      AND ch.ch_seqno in (SELECT MAX(ch_seqno) FROM contract_history WHERE co_id = co.co_id)
      and co.co_id IN (SELECT co_id FROM contract_history
      GROUP BY co_id HAVING(SUM(CASE WHEN ch_status = 'a' AND (ch_status = 'd' or ch_status = 's' or ch_status = 'o') THEN 1
                                WHEN ch_status = 'a' THEN 1
                                ELSE 0
                                END) > 0))
      ORDER BY decode(ch.ch_status,'d',1,'a',2,'s',3,'o',4)ASC;With the following results:
CH_STATUS     CUSTOMER_ID
   d                           100
   d                           200
   d                           300
   a                           100
   a                           200How am I suppose to amend my SQL statement in such a way the results will only display this?
Expected Results
CH_STATUS     CUSTOMER_ID
   d                       300
   a                       100
   a                       200Only the ch_status of 'a' will be displayed even though it has status 'd' too. However, if customer_id has only status 'd', it will be displayed.

i am not getting what u r trying to do....
once u have cursor you can use cursor...y u still need with clause,....
but yes its possible
QL>
SQL> Declare
  2   Cursor c1 Is
  3   With t As
  4  (
  5  Select 'd' CH_STATUS ,129 CUSTOMER_ID  From dual Union All
  6  Select 'd'           ,62031            From dual Union All
  7  Select 'd'           ,858347           From dual Union All
  8  Select 'a'           ,129              From dual Union All
  9  Select 'a'           ,62031            From dual
10  ) Select ch_status,customer_id
11    From
12  (
13   Select ch_status, customer_id,
14          Case When ch_status = 'd' And lag(ch_status) over (Partition By customer_id Order By ch_status) = 'a' Then 0 Else 1 End  new_status
15   From t
16   ) Where new_status = 1;
17 
18   r1 c1%Rowtype;
19  Begin
20  Open c1;
21  Loop
22  Fetch c1 Into r1;
23  Exit When c1%Notfound;
24   dbms_output.put_line(r1.CH_STATUS);
25  End Loop;
26  End;
27  /
a
a
d
PL/SQL procedure successfully completed
SQL>

Similar Messages

  • Hiding SQL statement in Query Result Window

    Hi everyone,
    Is it possible to hide the SQL statement from a query result window? This can usually be done by click the orange triangle that is positioned to the left of the SQL string box (to expand and collapse it). The System Queries have this box collapsed per default, is it possible to have this setup as default for all queries, including the custom? If so, please let me know where this can be done.
    Cheers

    You should do this only with SDK programming - dont allow to show the syntax. The next, but problematic way, is the code you have do inside stored procedure and call only this sp inside the query generator window - if you have there some input parameters, you should use filling variables before executing sp and get it as input parameters to sp.

  • Write a query / pl/sql statement for desired results

    Here is the table data:
    FSSETY FSUSER FSOBNM FSA FSCHNG FSDLT FSIOK FSICPY FSATN1
    1 DSTEIN P0030A N N N Y N Y
    1 FINAB001 P0030A Y Y Y Y Y Y
    1 FINAB001 P01012 Y Y Y Y Y Y
    1 DSTEIN P01012 Y Y Y Y Y Y
    1 DSTEIN P01013 Y Y Y Y Y Y
    1 FINAB001 P01013 Y Y Y Y Y Y
    1 FINAB001 P0111 Y Y Y Y Y Y
    1 DSTEIN P0111 Y Y Y Y Y Y
    1 DSTEIN P01111 Y Y Y Y Y Y
    1 FINAB001 P01111 Y Y Y Y Y Y
    1 FINAB001 P0115 Y Y Y Y Y Y
    1 DSTEIN P0115 Y Y Y Y Y Y
    1 DSTEIN P01BDWRD Y Y Y Y Y Y
    1 FINAB001 P01BDWRD Y Y Y Y Y Y
    1 FINAB001 P0411 Y Y Y Y Y Y
    1 DSTEIN P0411 N N N Y N Y
    What I need in results is:
    For each FSOBNM, return the rows with different FSUSER values and non-matching values in fsa OR fschng OR fsdlt OR fsicpy.
    So, the desired output of the query should return the first two rows and the last two rows, as they meet this criteria.
    I need help in the statement that would return the desired results.
    Thanks!
    Edited by: skyfox on 17-May-2012 5:54 PM
    Edited by: skyfox on 17-May-2012 5:54 PM

    Hi Skyfox,
    Below is the query you might be looking into
    SQL>
    SQL> WITH test AS(
      2  SELECT 1 FSSETY, 'DSTEIN' FSUSER, 'P0030A' FSOBNM, 'N' FSA, 'N' FSCHNG, 'N' FSDLT, 'Y' FSIOK, 'N' FSICPY, 'Y' FSATN1 FROM DUAL  UNION ALL
      3  SELECT 1 FSSETY, 'FINAB001' FSUSER, 'P0030A' FSOBNM, 'Y' FSA, 'Y' FSCHNG, 'Y' FSDLT, 'Y' FSIOK, 'Y' FSICPY, 'Y' FSATN1 FROM DUAL  UNION ALL
      4  SELECT 1 FSSETY, 'FINAB001' FSUSER, 'P01012' FSOBNM, 'Y' FSA, 'Y' FSCHNG, 'Y' FSDLT, 'Y' FSIOK, 'Y' FSICPY, 'Y' FSATN1 FROM DUAL  UNION ALL
      5  SELECT 1 FSSETY, 'DSTEIN' FSUSER, 'P01012' FSOBNM, 'Y' FSA, 'Y' FSCHNG, 'Y' FSDLT, 'Y' FSIOK, 'Y' FSICPY, 'Y' FSATN1 FROM DUAL  UNION ALL
      6  SELECT 1 FSSETY, 'DSTEIN' FSUSER, 'P01013' FSOBNM, 'Y' FSA, 'Y' FSCHNG, 'Y' FSDLT, 'Y' FSIOK, 'Y' FSICPY, 'Y' FSATN1 FROM DUAL  UNION ALL
      7  SELECT 1 FSSETY, 'FINAB001' FSUSER, 'P01013' FSOBNM, 'Y' FSA, 'Y' FSCHNG, 'Y' FSDLT, 'Y' FSIOK, 'Y' FSICPY, 'Y' FSATN1 FROM DUAL  UNION ALL
      8  SELECT 1 FSSETY, 'FINAB001' FSUSER, 'P0111' FSOBNM, 'Y' FSA, 'Y' FSCHNG, 'Y' FSDLT, 'Y' FSIOK, 'Y' FSICPY, 'Y' FSATN1 FROM DUAL  UNION ALL
      9  SELECT 1 FSSETY, 'DSTEIN' FSUSER, 'P0111' FSOBNM, 'Y' FSA, 'Y' FSCHNG, 'Y' FSDLT, 'Y' FSIOK, 'Y' FSICPY, 'Y' FSATN1 FROM DUAL  UNION ALL
    10  SELECT 1 FSSETY, 'DSTEIN' FSUSER, 'P01111' FSOBNM, 'Y' FSA, 'Y' FSCHNG, 'Y' FSDLT, 'Y' FSIOK, 'Y' FSICPY, 'Y' FSATN1 FROM DUAL  UNION ALL
    11  SELECT 1 FSSETY, 'FINAB001' FSUSER, 'P01111' FSOBNM, 'Y' FSA, 'Y' FSCHNG, 'Y' FSDLT, 'Y' FSIOK, 'Y' FSICPY, 'Y' FSATN1 FROM DUAL  UNION ALL
    12  SELECT 1 FSSETY, 'FINAB001' FSUSER, 'P0115' FSOBNM, 'Y' FSA, 'Y' FSCHNG, 'Y' FSDLT, 'Y' FSIOK, 'Y' FSICPY, 'Y' FSATN1 FROM DUAL  UNION ALL
    13  SELECT 1 FSSETY, 'DSTEIN' FSUSER, 'P0115' FSOBNM, 'Y' FSA, 'Y' FSCHNG, 'Y' FSDLT, 'Y' FSIOK, 'Y' FSICPY, 'Y' FSATN1 FROM DUAL  UNION ALL
    14  SELECT 1 FSSETY, 'DSTEIN' FSUSER, 'P01BDWRD' FSOBNM, 'Y' FSA, 'Y' FSCHNG, 'Y' FSDLT, 'Y' FSIOK, 'Y' FSICPY, 'Y' FSATN1 FROM DUAL  UNION ALL
    15  SELECT 1 FSSETY, 'FINAB001' FSUSER, 'P01BDWRD' FSOBNM, 'Y' FSA, 'Y' FSCHNG, 'Y' FSDLT, 'Y' FSIOK, 'Y' FSICPY, 'Y' FSATN1 FROM DUAL  UNION ALL
    16  SELECT 1 FSSETY, 'FINAB001' FSUSER, 'P0411' FSOBNM, 'Y' FSA, 'Y' FSCHNG, 'Y' FSDLT, 'Y' FSIOK, 'Y' FSICPY, 'Y' FSATN1 FROM DUAL  UNION ALL
    17  SELECT 1 FSSETY, 'DSTEIN' FSUSER, 'P0411' FSOBNM, 'N' FSA, 'N' FSCHNG, 'N' FSDLT, 'Y' FSIOK, 'N' FSICPY, 'Y' FSATN1 FROM DUAL)
    18  SELECT *
    19    FROM test a
    20   WHERE EXISTS (SELECT 1 FROM test
    21                  WHERE fsobnm = a.fsobnm
    22                    AND fsuser != a.fsuser
    23                    AND (fsa != a.fsa OR fschng != a.fschng OR fsdlt != a.fsdlt OR fsicpy != a.fsicpy))
    24  /
        FSSETY FSUSER   FSOBNM   FSA FSCHNG FSDLT FSIOK FSICPY FSATN1
             1 DSTEIN   P0030A   N   N      N     Y     N      Y
             1 FINAB001 P0030A   Y   Y      Y     Y     Y      Y
             1 FINAB001 P0411    Y   Y      Y     Y     Y      Y
             1 DSTEIN   P0411    N   N      N     Y     N      Y
    SQL>

  • Same sql statement two different results?

    Hi,
    I was wondering if anyone knows why I am getting different
    results on the same query.
    Basically... when I run this query in "view" in sql server, I
    get the results I need, however when I run in Coldfusion, I am
    getting totally different results.... It is a totally different
    result...
    the query:
    SELECT DISTINCT
    tbl_employees.indexid, tbl_employees.[Employee ID] as
    employeeid, tbl_employees.[First Name] as firstname,
    tbl_employees.[Last Name] as lastname,
    tbl_employees.[Supervisor ID] as supervisorid,
    tbl_workaddress_userdata.firstname,
    tbl_workaddress_userdata.lastname,
    tbl_workaddress_userdata.supervisorid,
    tbl_workaddress_userdata.location,
    tbl_workaddress_userdata.employeeid,
    tbl_workaddress_userdata.locationdescription
    FROM tbl_employees FULL OUTER JOIN
    tbl_workaddress_userdata ON tbl_employees.[Employee ID] =
    tbl_workaddress_userdata.employeeid
    WHERE (tbl_employees.[Supervisor ID] = 7) AND
    (tbl_workaddress_userdata.location IS NULL)

    I suspect you and your CF DSN are looking at two different
    DBs...
    Adam

  • SQL*plus not displaying the result of XMLELEMENT

    HI,
    I am using SQL*Plus: Release 10.1.0.4.2
    Connected to: Oracle Database 10g Enterprise Edition Release 10.2.0.4.0
    When I run the following query in SQL*PLUS, I get nothing displayed. However when I run the same query connecting to the same database using SQL Developer then I get the result
    SQL> select XMLELEMENT("form_id",form_id)
    2 FROM collections;
    XMLELEMENT("FORM_ID",FORM_ID)
    In SQL developer
    <form_id>101</form_id>
    I set long and longchuncksize to 32K , and I change linesize, pages, but nothing helped
    Is there any configuration that I have to do, so that SQL*plus display the result of “ select XMLELEMENT("form_id",form_id) query.
    Appreciate you help, thanks

    From a fresh start ;) :
    SQL*Plus: Release 10.1.0.4.2 - Production on Fri Feb 26 15:29:04 2010
    Copyright (c) 1982, 2005, Oracle.  All rights reserved.
    Connected to:
    Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - 64bit Production
    With the Partitioning, OLAP and Data Mining options
    SQL> select xmlelement("value", a.object_name )
      2  from   all_objects a
      3  where  rownum <= 5;
    XMLELEMENT("VALUE",A.OBJECT_NAME)
    SQL> select xmlelement("value", (select b.object_name
      2                              from   all_objects b
      3                              where b.object_name = a.object_name
      4                              )
      5                   )
      6  from   all_objects a
      7  where  rownum <= 5;
    XMLELEMENT("VALUE",(SELECTB.OBJECT_NAMEFROMALL_OBJECTSBWHEREB.OBJECT_NAME=A.OBJE
    <value>ICOL$</value>
    <value>I_USER1</value>
    <value>CON$</value>
    <value>UNDO$</value>
    <value>C_COBJ#</value>
    SQL> show all
    appinfo is OFF and set to "SQL*Plus"
    arraysize 15
    autocommit OFF
    autoprint OFF
    autorecovery OFF
    autotrace OFF
    blockterminator "." (hex 2e)
    btitle OFF and is the first few characters of the next SELECT statement
    cmdsep OFF
    colsep " "
    compatibility version NATIVE
    concat "." (hex 2e)
    copycommit 0
    COPYTYPECHECK is ON
    define "&" (hex 26)
    describe DEPTH 1 LINENUM OFF INDENT ON
    echo OFF
    editfile "afiedt.buf"
    embedded OFF
    escape OFF
    FEEDBACK ON for 6 or more rows
    flagger OFF
    flush ON
    heading ON
    headsep "|" (hex 7c)
    instance "local"
    linesize 80
    lno 9
    loboffset 1
    logsource ""
    long 80
    longchunksize 80
    markup HTML OFF HEAD "<style type='text/css'> body {font:10pt Arial,Helvetica,sans-serif; color:blac
    newpage 1
    null ""
    numformat ""
    numwidth 10
    pagesize 14
    PAUSE is OFF
    pno 1
    recsep WRAP
    recsepchar " " (hex 20)
    release 1002000300
    repfooter OFF and is NULL
    repheader OFF and is NULL
    serveroutput OFF
    shiftinout INVISIBLE
    showmode OFF
    spool OFF
    sqlblanklines OFF
    sqlcase MIXED
    sqlcode 0
    sqlcontinue "> "
    sqlnumber ON
    sqlpluscompatibility 10.1.0
    sqlprefix "#" (hex 23)
    sqlprompt "SQL> "
    sqlterminator ";" (hex 3b)
    suffix "sql"
    tab ON
    termout ON
    timing OFF
    trimout ON
    trimspool OFF
    ttitle OFF and is the first few characters of the next SELECT statement
    underline "-" (hex 2d)
    USER is "HR"
    verify ON
    wrap : lines will be wrapped
    SQL>
    {code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Odd results from SQL statement in JSP

    Hi.
    Getting very strange results from my SQL statement housed in my JSP.
    the last part of it is like so:
    "SELECT DISTINCT AID, ACTIVE, REQUESTOR_NAME, ..." +
    "REQUESTOR_EMAIL" +
    " FROM CHANGE_CONTROL_ADMIN a INNER JOIN CHANGE_CONTROL_USER b " +
    "ON a.CHANGE_CTRL_ID = b.CHANGE_CTRL_ID " +
      " WHERE UPPER(REQUESTOR_NAME) LIKE ? ";   I've set the following variables and statements:
    String reqName = request.getParameter("requestor_name");
    PreparedStatement prepstmt = connection.prepareStatement(preparedQuery);
    prepstmt.setString(1, "%" + reqName.trim().toUpperCase() + "%");
    ResultSet rslts = prepstmt.executeQuery();
    rslts.next();
    int aidn = rslts.getInt(1);          
    int actbox = rslts.getInt(2);     String reqname = rslts.getString(3).toUpperCase();
    String reqemails = rslts.getString(4);
    String bizct = rslts.getString(5);
    String dept = rslts.getString(6);
    String loc = rslts.getString(7);
    Date datereq = rslts.getDate(8);
    String busvp = rslts.getString(9);
    AND SO ONSo then I loop it, or try to with the following:
    <%
      try {
      while ((rslts).next()) { %>
      <tr class="style17">
        <td><%=reqname%></td><td><%=reqemails %></td><td><%=bizct %></td>td><%=dept %></td>
       <td><%=aidn %></td>
      </tr>
      <%
    rslts.close();
    selstmt.close();
    catch(Exception ex){
         ex.printStackTrace();
         log("Exception", ex);
    %>AND so on, setting 13 getXXX methods of the 16 cols in the SQL statement.
    Trouble is I'm getting wildly inconsistent results.
    For example, typing 'H' (w/o quotes) will spit out 20 duplicate records of a guy named Herman, with the rest of his corresponding info correct, just repeated for some reason.
    Typing in 'He' will bring back the record twice (2 rows of the complete result set being queried).
    However, typing in 'Her' returns nothing. I could type in 'ell' (last 3 letters of his name, Winchell) and it will again return two duplicate records, but typing in 'hell' would return nothing.
    Am I omitting something crucial from the while statement that's needed to accurately print out the results set without duplicating it and that will ensure returning it?
    There's also records in the DB that I know are there but aren't being returned. Different names (i.e. Jennifer, Jesse, Jeremy) won't be returned by typing in partial name strings like Je.
    Any insight would be largely appreciated.
    One sidenote: I can go to SQL Plus and accurately return a results set through the above query. Having said that, is it possible the JDBC driver has some kind of issue?
    Message was edited by:
    bpropes20
    Message was edited by:
    bpropes20

    Am I omitting something crucial from the while
    statement that's needed to accurately print out the
    results set without duplicating it and that will
    ensure returning it?Yes.
    In this code, nothing ever changes the value of reqname or any of the other variables.
      while ((rslts).next()) { %>
      <tr class="style17">
        <td><%=reqname%></td><td><%=reqemails %></td><td><%=bizct %></td>td><%=dept %></td>
       <td><%=aidn %></td>
      </tr>
      <%
    } You code needs to be like this:while (rslts.next()) {
      reqname = rslts.getString(3).toUpperCase();
      reqemails = rslts.getString(4);
      bizct = rslts.getString(5);
      dept = rslts.getString(6);
      loc = rslts.getString(7);
      datereq = rslts.getDate(8);
      busvp = rslts.getString(9);
    %>
      <tr class="style17">
        <td><%=reqname%></td><td><%=reqemails %></td><td><%=bizct %></td>td><%=dept %></td>
       <td><%=aidn %></td>
      </tr>
      <%
    There's also records in the DB that I know are there
    but aren't being returned. Different names (i.e.
    Jennifer, Jesse, Jeremy) won't be returned by typing
    in partial name strings like Je.Well, you're half-right, your loop won't display all the rows in the result set, because you call rslts.next(); once immediately after executing the query. That advance the result set to the first row; when the loop is entered, it starts displaying at the 2nd row (or later if there are more next() calls in the code you omitted).

  • Apex 4.0 display image item :BLOB column returned by SQL statement

    Hello
    I'm creating an display image item in apex 4.0. The source is a BLOB column returned by SQL statement.
    When I'm issuing an sql statement like this:
       select lado.blob_content
       from   large_documents      lado
       ,        large_doc_headers    ladh
       where lado.ladh_nr = ladh.nr
       more criteriait works fine.
    When I create a function inside a package with the same query (in a cursor)
    function get_image(some parameters in) return blob
    Following in apex by:
    select get_image(some parameters) from dualI get a
    ORA-06502: PL/SQL: numeric or value error: character string buffer too smallAnybody any idea why this does not work?
    Regards Erik

    Hi Eric,
    the environment assumes varchar2-output by default, which will be limited to 32767 characters and may have problems with binary formats. You could define a blob-variable to select the value into.
    DECLARE
      l_blob BLOB;
    BEGIN
      SELECT get_image(some parameters)
        INTO l_blob
        FROM dual;
    END;
    /If you expect the BLOB-Content to be text (you should consider CLOB then), you may use UTL_RAW.CAST_TO_VARCHAR2 to convert the content. If your object is larger than the maximum varchar2 size, or you want to convert BLOB to CLOB, you might be interested in some converter like described here: {message:id=559749}
    Hope this is what you were searching for.
    -Udo

  • DropDownList using result in sql statement

    hi
    i made a dropdownlist in which i get the data from a sql table.
    when i select a date i wanna press a button and this button starts a procedure which is creating a view on a table in which the where statement is the result of the selected item in the drop down box
    how do i get the selected item in my procedure?
    thanks a lot
    Falk

    ok my problem is how do i get the selected item in this :P1_DATE?
    do i have to declare it anywhere? where do i have to write the var into?
    i am a completely beginner so plz give me a simple how to
    ok i think ur :P1_DATE is the name of my dropdown menu
    so if i try this method i get an error "Bindevariables are not allowed for data definition operations
    i have to creat a view of the table because the table contains more than 100.000 entries and if i want to search s.th. i takes about 4 sec
    i want to do a pre selection with the view so people can select a date in the dop down menu and then the createtd view will contain about 400 entries and if u search in the new view it takes only 1 sec
    i also want to do this because of performing the database
    sorry for my english, hope u will understand all
    Edited by: user10247044 on 19.09.2008 07:11

  • Creating a DataTable from the results of SQL statement

    I am relatively new to VB 2005, ADO and Oracle db. I have perfected an SQL statement that joins 6 tables in an Oracle 10i database and the resulting set retunrs the correct data. I am having difficulty creating and inserting this resulting set into a datatable that could be used in my application. Could someone detail the steps needed to create and fill this table

    http://download.oracle.com/docs/cd/A91202_01/901_doc/appdev.901/a89856/06_ora.htm#1604
    The link above points to Oracle's documentation on using cursor variables. In a nutshell, you want to create a package that defines the cursor type and contains the procedure to open the cursor.
    create package my_package as
    type my_cursor_type is ref cursor;
    procedure my_procedure (out_cursor out my_cursor_type);
    end;
    create package body my_package as
    procedure my_procedure (out_cursor out my_cursor_type) is
    begin
         open my_cursor for
              select ...;
    end;
    end;Now you need to set up your .NET application to read the data.
    OracleConnection con = new OracleConnection("User Id=myuser;Password=mypassword;Data Source=mydatabase");
    OracleParameter[] parms = new OracleParameter[1];
    parms[0] = new OracleParameter("table1_cursor", OracleDbType.RefCursor, ParameterDirection.Output);
    OracleCommand cmd = new OracleCommand("my_package.my_procedure", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddRange(parms);
    DataTable myTable = new DataTable();
    OracleDataAdapter da = new OracleDataAdapter(cmd);
    da.Fill(myTable);

  • How to export the result from executing sql statement to excel file ?

    HI all,
    Great with Oracle SQL Developer, but I have have a trouble as follwing :
    I want to export the result from executing sql statement to excel file . I do easily like that in TOAD ,
    anyone can help me to do that ? Thanks so much
    Sigmasvn

    Hello Sue,
    I just tried to export to excel with the esdev extension and got java.lang.NumberFormatException. I found the workaround at Re: Windows Multi-language env, - how do I set English for application lang?
    open the file sqldeveloper\jdev\bin\sqldeveloper.conf and add the following two lines:
    AddVMOption -Duser.language=en
    AddVMOption -Duser.country=USyet now my date formats in excel are 'american-style' instead of german. For example 01-DEC-01 so excel does not recognize it as date and therefore I can not simply change the format.
    When export to excel will be native to 1.1 perhaps someone can have a look at this 'feature'
    Regards
    Marcus

  • Refering alias of a function result in an sql statement

    Dear Sir,
    How to refer an alias of a function result in sql statement?
    eg.(new_name is the alias)
    select myfunction(name) new_name
    from mytable
    where new_name = '#vincent#';
    I can't refer new_name in the above statement coz it gives an error "invalid column name".
    But I don't want to put the myfunction(name) again in the where clause which will double the job. So, how should I refer to it?
    Please advise.
    Thanks.
    null

    You can not refer to the alias like you are talking. You will have to use myfunction(name) as you have said. Or you can try creating a view with query:
    select myfunction(name) new_name
    from mytable
    and then refer to "new_name".
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by guest2000:
    Dear Sir,
    How to refer an alias of a function result in sql statement?
    eg.(new_name is the alias)
    select myfunction(name) new_name
    from mytable
    where new_name = '#vincent#';
    I can't refer new_name in the above statement coz it gives an error "invalid column name".
    But I don't want to put the myfunction(name) again in the where clause which will double the job. So, how should I refer to it?
    Please advise.
    Thanks.<HR></BLOCKQUOTE>
    null

  • Different result from same SQL statement

    The following SQL statement brings back records using query
    analyzer on the SQL server. However when I run it in a cold fusion
    page it comes back with no results. Any idea why????????
    SELECT COUNT(h.userID) AS hits, u.OCD
    FROM dbo.tbl_hits h INNER JOIN
    dbo.tlkp_users u ON h.userID = u.PIN
    WHERE (h.appName LIKE 'OPwiz%') AND (h.lu_date BETWEEN
    '05/01/07' AND '06/01/07')
    GROUP BY u.OCD
    ORDER BY u.OCD

    Anthony Spears wrote:
    > That didn't work either.
    >
    > But here is something interesting. If we use the dates
    05/01/2007 and
    > 06/01/2007 we get results in SQL Server Query Analyzer
    but not using a cold
    > fusion page. But if we use the dates 05/01/2007 and
    09/01/2007 both get back
    > the same results.
    >
    Are you absolutely, 100% sure that you are connecting to the
    same
    database instance with both CF and Query Analyzer? That kind
    of symptom
    is 9 out of 10 times because the user is looking at different
    data. One
    is looking at production and the other development or an
    backup or
    recent copy or something different.

  • Issue Related to limit the result in prompt by using SQL statement.

    Hello Gurus,
    I am facing one issue rite now with our testing environment in some Dashboard Prompt. it seems like they are working fine in our Development environment.
    basically I am using SQL statement in prompt to limit the values for current + last 2 years in drop down.
    Here is the SQL that I am using SELECT Time."Fiscal Year" FROM "Financials - AP Overview" where Time."Fiscal Year" <= VALUEOF(NQ_SESSION.CURRENT_FSCL_YEAR) AND Time."Fiscal Year" >= (VALUEOF(NQ_SESSION.CURRENT_FSCL_YEAR)-2) ORDER BY TIme."Fiscal Year" desc
    Now it's working fine in our Dev but geeting failed in Test environment.
    it's giving below error.
    Odbc driver returned an error (SQLExecDirectW).
    State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred.
    [nQSError: 43113] Message returned from OBIS.
    [nQSError: 43119] Query Failed:
    [nQSError: 22023] An arithmetic operation is being carried out on a non-numeric type. (HY000)
    SQL Issued: SELECT Time."Fiscal Year" FROM "Financials - AP Overview" where Time."Fiscal Year" <= VALUEOF(NQ_SESSION.CURRENT_FSCL_YEAR) AND Time."Fiscal Year" >= (VALUEOF(NQ_SESSION.CURRENT_FSCL_YEAR)-2) ORDER BY TIme."Fiscal Year" desc
    Please let me know your output.
    Thanking You..

    Couple of possibilities..
    1. environments may be at different patch sets, may be causing the issue.
    2. data in working environment is fine but in other environment.
    to further debug use the same logical sql in both environments and compare the results..
    hope this helps..

  • How to execute entire result set of multiple sql statements via sp_executesql?

    I have a query that generates multiple insert statements (dynamic sql).  So when I execute this my result set is a table of sql insert statements (one insert statment per row in my source data table).  Like so:
                 Select 'INSERT INTO [dbo].[Table_1] ([Col1]) VALUES (' +  SrcData + ')' from SourceDataTbl
    How can I completely automate this and execute all these sql statements via sp_executesql?
    My plan is to completely automate and execute all this via an SSIS package.
    As always any help is greatly appreciated!
    fyi-  This is a very simple version of what I am trying to do.  My query probably plugs in 20+ values from the SourceDataTbl into each of the sql insert statements.

    Ah, a small error in Visakh's post, which I failed to observe, and then I added one on my own.
    DECLARE @SQL Varchar(max)
    SELECT @SQL =
       (SELECT 'INSERT INTO [dbo].[Table_1] ([Col1]) VALUES (' +  SrcData +
                ')' + char(10) + char(13)
        from SourceDataTbl
        FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)')
    EXEC sp_executesql @SQL
    Without ", TYPE" FOR XML returns a string when assigned to a variable. The TYPE thing produces a value of the XML data type, so that we can apply the value method and get string out of the XML.
    And why this? Because:
    DECLARE @str nvarchar(MAX)
    SELECT @str = (SELECT 'Kalle Anka & co' FOR XML PATH(''))
    SELECT @str
    SELECT @str = (SELECT 'Kalle Anka & co' FOR XML PATH(''), TYPE).value('.', 'nvarchar(MAX)')
    SELECT @str
    Although the data type is string when , TYPE is not there, it is still XML and characters special to XML are enticised.
    Confused? Don't worry, for what you are doing, this is mumbo-jumbo.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Problem with SQL Statement for Result Filtering

    Dear Visual Composer Experts,
    Here is another Question from me: I have a SQL Query that is working as the data service
    Select AB.AgingBandID, AB.AgingBand,
    Sum(Case when priority='Emergency' then '1' Else 0 End) as [Emergency],
    Sum(Case when priority='Ugent' then '1' Else 0 End) as Ugent,
    Sum(Case when priority='High' then '1' Else 0 End) as High,
    Sum(Case when priority='Medium' then '1' Else 0 End) as Medium,
    Sum(Case when priority='Low' then '1' Else 0 End) as Low
    from DimAgingBand AB left outer join
    (Select AgingBandID , priority , yeardesc
    from vNotifications where YearDesc = (select year(getdate())-1)) as vN
    on AB.AgingBandID=vN.AgingBandID
    where AB.AgingBandID<>'1'  
    Group by  AB.AgingBandID, AB.AgingBand
    Order by AB.AgingBandID
    That would return me a table as in the following:
         Agingband     E     U     H     M     L
         < 1week     0     0     0     0     1
         1 - 2 weeks     0     0     0     0     0
         2 - 4weeks     0     0     0     0     1
    > 1month     8     2     1     1     6
    Now that I would like to add some parameters to filter the result, so I modify the query and put it in the SQL Statement input port of the same data service. The query is like this:
         "Select AB.AgingBandID, AB.AgingBand,Sum(Case when priority='Emergency' then '1' Else 0 End) as [Emergency],Sum(Case when priority='Ugent' then '1' Else 0 End) as Ugent,Sum(Case when priority='High' then '1' Else 0 End) as High,Sum(Case when priority='Medium' then '1' Else 0 End) as Medium,Sum(Case when priority='Low' then '1' Else 0 End) as Low from DimAgingBand AB left outer join (Select AgingBandID , priority , yeardesc from vNotifications where YearDesc like '2009%' and Branch like '" & if(STORE@selectedBranch=='ALL', '%', STORE@selectedBranch) & "' and MainWorkCentre like '%') as vN on AB.AgingBandID=vN.AgingBandID where AB.AgingBandID<>'1' Group by AB.AgingBandID, AB.AgingBand Order by AB.AgingBandID"
    However this input port query keeps giving me error as NullPointerException. I have actually specified a condition where the query will run if only STORE@selectedBranch != u2018u2019.
    I have other filtering queries working but they are not as complicated query as this one. Could it be possible that query in the input port cannot handle left outer join?
    Could it be anything else?
    Help is very much appreciated.
    Thanks & Regard,
    Sarah

    Hi,
    Thank you very much for your replys. I've tested if the dynamic value of the condition is integer, it's OK
    But if the ClassID type is not integer, it's string, I write  a SQL Statement like:
    "Select DBADMIN.Class.ClassName from DBADMIN.Class where DBADMIN.Class.ClassID = '1' "
    or with dynamic condition:
    "Select DBADMIN.Class.ClassName from DBADMIN.Class where DBADMIN.Class.ClassID = '"&@ClassID&"'"
    or I write the SQL Statement for insert/update/delete data,
    I always have errors.
    I've tested if the dynamic value of the condition is integer, it's OK
    Do you know this problem ?
    Thank you very much & kindly regards,
    Tweety

Maybe you are looking for

  • K9N2 SLI Platinum Blue Screen of Death when installing Windows XP

    My hardware includes: •   MSI K9N2 SLI Platinum Motherboard •   Corsair XMS2 TWIN2X4096-6400C5 •   GeForce 9800 GT 512MB GDDR3 •   AMD Phenom X4 9850 Quad Core Processor, Black Edition 2.5GHz                 4MB Cache 2000MHz [4000 MT/s] FSB •   Ther

  • How to determine which CDockablePane in a group is currently active in Visual Studio 2013

    I understand that to activate a pane, I can do the following: dockablePane->ShowPane(TRUE, FALSE, TRUE); But, in a group of panes, how can I tell which pane is currently active? For instance, let's say there are 3 groups of panes on the screen.  The

  • How the HE** do I get a key back on the keyboard?

    On my brand new MacBook Pro a key just popped off. My last Mac laptop had like 7 keys missing. Now I am irked. How the heck do you get this thing back on?? Remember the good ole days when you just shoved it in there. What are all these little white p

  • Asset Posting as unplanned

    Hi All, When we try to post unplanned depreciation for assets SAP is not allowing as it is a group asset. We need unplanned depreciation as the planned values are not as per requirement. Also, how do we transfer profit and loss GL account balanes to

  • Locale shown in the wrong language in the production server.

    I have an application with a few projects which all have two locales - faroese and english. When I run the application on the default application server on my local machine it works fine with faroese locale but when I deploy to our production server