"Invalid Column" on multiple where clauses with subqueries and cfqueryparam

I'm seeing a behavior in the coldfusion cfquery that I'd like to find an exmplanation for .  I've got a query that does a subquery in the select portion and if I have multiple where lines, I get an "invalid column name" message for my second where clause, but only when I'm using cfqueryparam
For example on the following I get "Invalid column name 'position_id'"
SELECT   department_staff_tbl.*,
         (   SELECT   max(bookmark_id)
             FROM     bookmarked_items_tbl
             WHERE    item_id = department_staff_tbl.staff_id
         ) AS bookmark_id
FROM     department_staff_tbl
WHERE    department_id = <cfqueryparam value="#arguments.deptid#"  cfsqltype="cf_sql_integer">
AND     position_id   = <cfqueryparam value="#arguments.posid#"   cfsqltype="cf_sql_integer">
AND     staff_id      = <cfqueryparam value="#arguments.staffid#" cfsqltype="cf_sql_integer">
If I change the order of my where clause so staff_id is first, then it tells me "department_id" is an invalid column.
If I only have one where clause, it works.  (i.e. WHERE position_id = <cfqueryparam value="#arguments.posid#" cfsqltype="cf_sql_integer">).
If I remove the where clause from my subquery (WHERE     item_id = department_staff_tbl.staff_id) it works.
It also works if I remove the cfqueryparam from my where clause so that my query looks like this:
SELECT   department_staff_tbl.*,
         (   SELECT   max(bookmark_id)
             FROM     bookmarked_items_tbl
             WHERE    item_id = department_staff_tbl.staff_id
         ) AS bookmark_id
FROM     department_staff_tbl
WHERE    department_id = #arguments.deptid#
AND     position_id   = #arguments.posid#
AND     staff_id      = #arguments.staffid#
Any thoughts?

I see two tables. So can the server. So, use qualified column-names.
SELECT   department_staff_tbl.*,
         (   SELECT   max(bookmarked_items_tbl.bookmark_id)
             FROM     bookmarked_items_tbl
             WHERE    bookmarked_items_tbl.item_id = department_staff_tbl.staff_id
         ) AS bookmark_id
FROM     department_staff_tbl
WHERE    department_staff_tbl.department_id = <cfqueryparam value="#arguments.deptid#"  cfsqltype="cf_sql_integer">
AND      department_staff_tbl.position_id   = <cfqueryparam value="#arguments.posid#"   cfsqltype="cf_sql_integer">
AND      department_staff_tbl.staff_id      = <cfqueryparam value="#arguments.staffid#" cfsqltype="cf_sql_integer">

Similar Messages

  • Where clause with XMLExists and join on another table

    Hi,
    We have table like:
    drop table xml_tbl;
    create table xml_tbl (
    xml_msg_id integer,
    xml_msg_text xmltype
    insert into xml_tbl values
    (1, '<main><id>1</id></main>') ;
    insert into xml_tbl values --(xml_msg_id,xml_msg_text)
    (1, '<main><id>2</id></main>') ;
    Another table like:
    create Table Table1
    ( id1 int);
    Insert into Table1 values(2);
    Insert into Table1 values(3);
    We need to have a view on top of the table xml_tbl where /main/id should have only those values which are in id1 column of table Table1.
    Something like
    CREATE OR REPLACE VIEW V_xml_tbl
    xml_msg_text
    AS
    SELECT T.xml_msg_text
    FROM xml_tbl T
    WHERE XMLEXISTS (
    'declare namespace Namesp1 ="Abc:Set";
    let $Results as xs:boolean := fn:exists($p/main/id in (Select id1 from Table1)) --Now here I know I can't do Select id1 from
    Table1*
    return if ($Results ) then true() else ()'
    PASSING T.xml_msg_text AS "p");
    Actually in the real scenario Table1 will have many IDs and xml_tbl has many XML files..
    So I am stuck on how to do it. Please help.
    Thanks..
    Edited by: user8941550 on Nov 20, 2012 7:19 PM

    One of these two :
    SQL> select t.xml_msg_text
      2  from xml_tbl t
      3  where exists (
      4    select null
      5    from table1 t1
      6    where t1.id1 = xmlcast(
      7                     xmlquery('/main/id' passing t.xml_msg_text returning content)
      8                     as integer
      9                   )
    10  );
    XML_MSG_TEXT
    <main>
      <id>2</id>
    </main>
    SQL> select t.xml_msg_text
      2  from xml_tbl t
      3     , xmltable('/main' passing t.xml_msg_text
      4         columns id integer path 'id'
      5       ) x
      6  where exists (
      7    select null
      8    from table1 t1
      9    where t1.id1 = x.id
    10  );
    XML_MSG_TEXT
    <main>
      <id>2</id>
    </main>
    And a third one, using XMLExists :
    SQL> select t.xml_msg_text
      2  from xml_tbl t
      3  where xmlexists (
      4    'fn:collection("oradb:/DEV/TABLE1")/ROW[ID1=$d/main/id]'
      5    passing t.xml_msg_text as "d"
      6  );
    XML_MSG_TEXT
    <main>
      <id>2</id>
    </main>
    Execution Plan
    Plan hash value: 3633580934
    | Id  | Operation           | Name    | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT    |         |     2 |   116 |     8   (0)| 00:00:01 |
    |*  1 |  FILTER             |         |       |       |            |          |
    |   2 |   TABLE ACCESS FULL | XML_TBL |     2 |   116 |     3   (0)| 00:00:01 |
    |   3 |   NESTED LOOPS      |         |     1 |     5 |     5   (0)| 00:00:01 |
    |   4 |    TABLE ACCESS FULL| TABLE1  |     2 |     6 |     3   (0)| 00:00:01 |
    |*  5 |    XPATH EVALUATION |         |       |       |            |          |
    Predicate Information (identified by operation id):
       1 - filter( EXISTS (SELECT 0 FROM "DEV"."TABLE1"
                  "SYS_ORAVW_2",XPATHTABLE('/main/id' PASSING :B1 COLUMNS "C_00$" XMLTYPE
                  PATH '.', "C_01$" XQEXVAL CHAR PATH '.')  "P" WHERE
                  TO_BINARY_DOUBLE("ID1")=TO_BINARY_DOUBLE("P"."C_01$")))
       5 - filter(TO_BINARY_DOUBLE("ID1")=TO_BINARY_DOUBLE("P"."C_01$"))The plan is similar to that of the second query above (XMLTable/EXISTS).
    Still using XMLExists, a plan similar to the first query (EXISTS/XMLCast/XMLQuery) can be achieved by casting id to an integer datatype :
    SQL> select t.xml_msg_text
      2  from xml_tbl t
      3  where xmlexists (
      4    'fn:collection("oradb:/DEV/TABLE1")/ROW[ID1=xs:int($d/main/id)]'
      5    passing t.xml_msg_text as "d"
      6  );
    XML_MSG_TEXT
    <main>
      <id>2</id>
    </main>
    Execution Plan
    Plan hash value: 1149640166
    | Id  | Operation          | Name    | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT   |         |     1 |    61 |     7  (15)| 00:00:01 |
    |*  1 |  HASH JOIN SEMI    |         |     1 |    61 |     7  (15)| 00:00:01 |
    |   2 |   TABLE ACCESS FULL| XML_TBL |     2 |   116 |     3   (0)| 00:00:01 |
    |   3 |   TABLE ACCESS FULL| TABLE1  |     2 |     6 |     3   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       1 - access("ID1"=SYS_XQ_ATOMCNVCHK(TO_NUMBER(SYS_XQ_UPKXML2SQL(SYS_XQ
                  EXVAL(SYS_XQEXTRACT(SYS_MAKEXML(0,"T"."SYS_NC00003$"),'/main/id'),1,50,3
                  3792,8192),50,1,0)),2,37))
    Note
       - Unoptimized XML construct detected (enable XMLOptimizationCheck for more information)Check each one on your real scenario to see which show best performance.
    (I would tend to say the ones involving streaming evaluation)
    Edited by: odie_63 on 5 nov. 2012 12:24
    Edited by: odie_63 on 5 nov. 2012 12:38

  • How can I pass multiple condition in where clause with the join table?

    Hi:
    I need to collect several inputs at run time, and query the record according to the input.
    How can I pass multiple conditions in where clause with the join table?
    Thanks in advance for any help.
    Regards,
    TD

    If you are using SQL-Plus or Reports you can use lexical parameters like:
    SELECT * FROM emp &condition;
    When you run the query it will ask for value of condition and you can enter what every you want. Here is a really fun query:
    SELECT &columns FROM &tables &condition;
    But if you are using Forms. Then you have to change the condition by SET_BLOCK_PROPERTY.
    Best of luck!

  • Problem with column alias: Unknown column 'avg_rating' in 'where clause'

    Hello,
    I have a basic sql statement as follows:
    SELECT
    e.establishment_id,
    e.establishment_name,
    avg(r.rating) avg_rating
    FROM
    establishment e,
    rating r,
    comment com,
    establishment_country ec,
    country_ref cou
    where
    etc...
    and avg_rating >= 1
    and 0=0
    group by e.establishment_id
    order by e.establishment_idI have used a column alias for "avg(r.rating)" and named it "avg_rating".
    It works in my Mysql Query browser without problem but when I run it from Java I get this:
    java.sql.SQLException: Unknown column 'avg_rating' in 'where clause'
        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2928)
        at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1571)
        at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1666)
        at com.mysql.jdbc.Connection.execSQL(Connection.java:2988)
        at com.mysql.jdbc.Connection.execSQL(Connection.java:2917)
        at com.mysql.jdbc.Statement.executeQuery(Statement.java:824)
        at org.jboss.resource.adapter.jdbc.WrappedStatement.executeQuery(WrappedStatement.java:145)
        at arcoiris.SearchSessionBean.performSearch(SearchSessionBean.java:73)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:585)
        at org.jboss.invocation.Invocation.performCall(Invocation.java:345)
        at org.jboss.ejb.StatelessSessionContainer$ContainerInterceptor.invoke(StatelessSessionContainer.java:214)
        at org.jboss.resource.connectionmanager.CachedConnectionInterceptor.invoke(CachedConnectionInterceptor.java:149)
        at org.jboss.ejb.plugins.StatelessSessionInstanceInterceptor.invoke(StatelessSessionInstanceInterceptor.java:154)
        at org.jboss.webservice.server.ServiceEndpointInterceptor.invoke(ServiceEndpointInterceptor.java:54)
        at org.jboss.ejb.plugins.CallValidationInterceptor.invoke(CallValidationInterceptor.java:48)
        at org.jboss.ejb.plugins.AbstractTxInterceptor.invokeNext(AbstractTxInterceptor.java:106)
        at org.jboss.ejb.plugins.TxInterceptorCMT.runWithTransactions(TxInterceptorCMT.java:335)
        at org.jboss.ejb.plugins.TxInterceptorCMT.invoke(TxInterceptorCMT.java:166)
        at org.jboss.ejb.plugins.SecurityInterceptor.invoke(SecurityInterceptor.java:153)
        at org.jboss.ejb.plugins.LogInterceptor.invoke(LogInterceptor.java:192)
        at org.jboss.ejb.plugins.ProxyFactoryFinderInterceptor.invoke(ProxyFactoryFinderInterceptor.java:122)
        at org.jboss.ejb.SessionContainer.internalInvoke(SessionContainer.java:624)
        at org.jboss.ejb.Container.invoke(Container.java:873)
        at org.jboss.ejb.plugins.local.BaseLocalProxyFactory.invoke(BaseLocalProxyFactory.java:415)
        at org.jboss.ejb.plugins.local.StatelessSessionProxy.invoke(StatelessSessionProxy.java:88)
        at $Proxy172.performSearch(Unknown Source)
        at arcoiris.SearchManagedBean.performSearch(SearchManagedBean.java:171)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:585)
        at com.sun.faces.el.MethodBindingImpl.invoke(MethodBindingImpl.java:126)
        at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:72)
        at javax.faces.component.UICommand.broadcast(UICommand.java:312)
        at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:267)
        at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:381)
        at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:75)
        at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:200)
        at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:90)
        at javax.faces.webapp.FacesServlet.service(FacesServlet.java:197)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
        at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:81)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
        at org.jboss.web.tomcat.security.CustomPrincipalValve.invoke(CustomPrincipalValve.java:39)
        at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:159)
        at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:59)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856)
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744)
        at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
        at org.apache.tomcat.util.net.MasterSlaveWorkerThread.run(MasterSlaveWorkerThread.java:112)
        at java.lang.Thread.run(Thread.java:595)Can anyone help please?
    Thanks in advance,
    Julien Martin.

    I am having the similiar problem, the query in java creator IDE works fine after i upgraded the J-connector and changed DataSource type for MySQL to mysql-connector-java-5.0.4-bin.jar. but still i cannot bind any control in the form to the aliased column. this is really frustrating. can anyone from Sun Developer explain?
    THX

  • Generate a where clause with outer join criteria condition: (+)=

    Hi,
    In my search page, I use Auto Customization Criteria mode, and I build where clause by using get Criteria():
    public void initSrpQuery(Dictionary[] dic, String userName) {
    int dicSize = dic.length;
    StringBuffer whereClause = new StringBuffer(100);
    Vector parameters = new Vector(5);
    int clauseCount = 0;
    int bindCount = 1;
    for(int i=0; i < dicSize; i++){
    String itemName = (String)(dic.get(OAViewObject.CRITERIA_ITEM_NAME));
    Object value = dic[i].get(OAViewObject.CRITERIA_VALUE);
    String joinCondition = (String)dic[i].get(OAViewObject.CRITERIA_JOIN_CONDITION);
    String criteriaCondition = (String)dic[i].get(OAViewObject.CRITERIA_CONDITION);
    String criteriaDataType = (String)dic[i].get(OAViewObject.CRITERIA_DATATYPE);
    String viewAttributename = (String)dic[i].get(OAViewObject.CRITERIA_VIEW_ATTRIBUTE_NAME);
    String columnName = findAttributeDef(viewAttributename).getColumnNameForQuery();
    if((value != null) /*&& (!("".equals((String).trim())))*/){
    if(clauseCount > 0){
    whereClause.append(" AND ");
    whereClause.append(columnName + " " + criteriaCondition + " :");
    whereClause.append(++bindCount);
    parameters.addElement(value);
    clauseCount++;
    If I want to generate following where clause:
    select
    ,emp.name
    ,emp.email
    ,emp.salesrep_number
    ,comp.name
    ,gs.srp_goal_header_id
    ,gs.status_code
    ,gs.start_date
    ,gs.end_date
    from g2c_goal_shr_emp_assignments_v emp
    ,jtf_rs_salesreps rs
    ,xxg2c_srp_goal_headers_all gs
    ,cn_comp_plans_all comp
    where 1 = 1
    and rs.salesrep_id = gs.salesrep_id (+)
    and gs.comp_plan_id = comp.comp_plan_id (+)
    and gs.period_year (+) = :1 -- :1 p_fiscal_year
    How can I generate a where clause with outer join : gs.period_year (+) = :1 ? Will I get '(+)=' from get(OAViewObject.CRITERIA_CONDITION)?
    thanks
    Lei

    If you are using SQL-Plus or Reports you can use lexical parameters like:
    SELECT * FROM emp &condition;
    When you run the query it will ask for value of condition and you can enter what every you want. Here is a really fun query:
    SELECT &columns FROM &tables &condition;
    But if you are using Forms. Then you have to change the condition by SET_BLOCK_PROPERTY.
    Best of luck!

  • Join and Multiple where clauses: which is better??

    There was an argument between a colleague and I. He prefers building his views joining many tables with many where clause while I am cute with my join which is simpler and more understandable for me. So, it started an argument on which is a superior way of joining tables.
    I will actually like to know we is faster and better: using JOINs or using multiple where clauses to retrieve values from multiple tables.?

    Dave:
    "Are we talking about the difference between Oracle Joins and ANSI Joins?
    e.g.
    Select d.dept_name, e.emp_name
    from dept d, emp e
    where d.dept_id = e.dept_id"
    That is not really an "Oracle Join". That syntax works on just about every SQL database I have ever worked with. The (+) syntax for an outer join is Oracle specific, but some other databases use a similar style for outer joins (something like a.c += b.c or a.c *= b.c).
    OP:
    There are things you can do with the ANSI style syntax that either cannot be done, or cannot be done as easily, with Oracle's syntax. Most notably, outer joining one table to more than one other tables, and FULL OUTER joins.
    Having said that, in my experience, both are rather rare occurrences, so I tend to stick to doing the jopins in the WHERE clause because that is what I am used to.
    John

  • Where clause with time stamp

    Hii,
    I have an issue with using where clause with time stamp. My requirement is to
    select * from driver_on_policy
    where last_change_datetime = '2001-03-06 19:00:06'
    date is in this form 6/3/2001 7:00:06 PM
    thnks
    sam

    If you want to use '6/3/2001 7:00:06 PM', then
    where last_change_datetime = to_timestamp('6/3/2001 7:00:06 PM','DD/MM/YYYY HH:MI:SS PM')If you can use a literal string in ANSI standard YYYY-MM-DD HH24:MI:SS format, then just
    where last_change_datetime = timestamp '2001-03-06 19:00:06' (That 'DD/MM' might need to be switched around to 'MM/DD' if you are in America.)
    Message was edited by:
    William Robertson

  • SQL query in SQL_REDO Logminor showing where clause with ROWID

    SQL query in SQL_REDO Logminor showing where clause with ROWID. I dont wanted to use rowid but wanted to use actual value.
    OPERATION SQL_REDO SQL_UNDO
    DELETE delete from "OE"."ORDERS" insert into "OE"."ORDERS"
    where "ORDER_ID" = '2413' ("ORDER_ID","ORDER_MODE",
    and "ORDER_MODE" = 'direct' "CUSTOMER_ID","ORDER_STATUS",
    and "CUSTOMER_ID" = '101' "ORDER_TOTAL","SALES_REP_ID",
    and "ORDER_STATUS" = '5' "PROMOTION_ID")
    and "ORDER_TOTAL" = '48552' values ('2413','direct','101',
    and "SALES_REP_ID" = '161' '5','48552','161',NULL);
    and "PROMOTION_ID" IS NULL
    and ROWID = 'AAAHTCAABAAAZAPAAN';
    DELETE delete from "OE"."ORDERS" insert into "OE"."ORDERS"
    where "ORDER_ID" = '2430' ("ORDER_ID","ORDER_MODE",
    and "ORDER_MODE" = 'direct' "CUSTOMER_ID","ORDER_STATUS",
    and "CUSTOMER_ID" = '101' "ORDER_TOTAL","SALES_REP_ID",
    and "ORDER_STATUS" = '8' "PROMOTION_ID")
    and "ORDER_TOTAL" = '29669.9' values('2430','direct','101',
    and "SALES_REP_ID" = '159' '8','29669.9','159',NULL);
    and "PROMOTION_ID" IS NULL
    and ROWID = 'AAAHTCAABAAAZAPAAe';
    Please let me know solution/document which will convert SQL redo rowid value with actual value.
    Thanks,

    Please enclose your output within tag so that people here can read it easily and help you. Also the reason that why you want to remove rowid?
    Salman
    Edited by: Salman Qureshi on Mar 20, 2013 3:53 PM                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Where clause with a combination of And and Or statements - Basic question

    Hi,
    I have a where clause with a combination of And and Or statements... May I know which one would run first
    Here is the sample
    WHERE SITE_NAME = 'Q' AND ET_NAME IN ('12', '15') AND TEST_DATE > DATE OR SITE_NAME = 'E' AND ET_NAME IN ('19', '20')
    can you please explain how this combination works
    Thanks in advance

    Hi,
    This reminds me of a great story. It's so good, it probably didn't really happen, but it's so good, I'm going to repeat it anyway.
    IBM once had an "executive apptitude test" that they would give to job applicants. There were some questions you might call general knowlege or trivia questions, and each question had a weight (for example, answering an unimportant queestion might score one point, an important question might be 5 points.) One of the questions was "What is the standard width of a mobile home?", and the weight of the question was -20: answering the question correctly did serious harm to your score. The reasoning was that the more you knew about mobile homes, the less likely you were to be their kind of executive.
    Now, as to your question, the correct answer is: I don't know. I don't want to know. Mixing ANDs and ORs without grouping them in parentheses is a really bad idea. Even if you get it right, it's going to confuse the next person who has to look at that code. Use parentheses to make sure the code is doing what you want it to do.
    If you really want to find out, it's documented in the SQL language manual. Look up "Operators, prcedence"
    http://docs.oracle.com/cd/E11882_01/server.112/e26088/operators001.htm#sthref815
    You can easily do an experiment, using scott.emp, or even dual, where
    WHERE  (x AND y)
    OR      zproduces different results from
    WHERE   x
    AND     (y OR z)

  • Dynamic where clause with loop statement

    Hi all,
    is it possible to use a dynamic where clause with a loop statement?
    Can you please advise me, how the syntax needs to be?
    Thanks for your suggestions,
    kind regards, Kathrin!

    Hi Kathrin,
               If u are in ECC 6.0, please go through the code...
              REPORT  zdynamic_select.
    TYPES:
      BEGIN OF ty_sales,
        vbeln  TYPE vbak-vbeln,            " Sales document
        posnr  TYPE vbap-posnr,            " Sales document item
        matnr  TYPE vbap-matnr,            " Material number
        arktx  TYPE vbap-arktx,            " Short text for sales order item
        kwmeng TYPE vbap-kwmeng,           " Order quantity
        vkorg TYPE vbak-vkorg,             " Sales organization
        kunnr TYPE vbak-kunnr,             " Sold-to party
        netwr TYPE vbak-netwr,             " Net Value of the Sales Order
      END OF ty_sales.
    DATA :
      gt_sales TYPE STANDARD TABLE OF ty_sales,
      wa_sales TYPE ty_sales.
    DATA: ob_select TYPE REF TO cl_rs_where.
    DATA: ob_from   TYPE REF TO cl_rs_where.
    DATA: ob_where  TYPE REF TO cl_rs_where,
          gv_source TYPE abapsource.
    START-OF-SELECTION.
    *Step 1 : Prepare the select fields.
      PERFORM zf_build_select.
    *Step 2 : Build the from clause for the select
      PERFORM zf_build_from.
    *Step 3 : Build the where clause for the select
      PERFORM zf_build_where.
    *Step 4 : Execute the dynamic select
      SELECT (ob_select->n_t_where)
          FROM (ob_from->n_t_where)
            INTO CORRESPONDING FIELDS OF TABLE gt_sales
            WHERE (ob_where->n_t_where).
      LOOP AT gt_sales INTO wa_sales.
        WRITE :   /5 wa_sales-vbeln,
                  15 wa_sales-vkorg,
                  20 wa_sales-kunnr,
                  40 wa_sales-netwr,
                  50 wa_sales-posnr,
                  60 wa_sales-matnr,
                  70 wa_sales-arktx,
                  90 wa_sales-kwmeng.
      ENDLOOP.
    *&      Form  zf_build_select
    FORM zf_build_select .
      CREATE OBJECT ob_select.
    *Build the table name/field name combination
    *Add Sales order header fields
      CLEAR gv_source.
      CALL METHOD cl_rs_where=>build_tabname_fieldname
        EXPORTING
          i_tabname   = 'VBAK'
          i_fieldname = 'VBELN'
          i_sign      = '~'
        IMPORTING
          e_combined  = gv_source.
    *Add the where line
      CALL METHOD ob_select->add_line
        EXPORTING
          i_line = gv_source.
      CLEAR gv_source.
      CALL METHOD cl_rs_where=>build_tabname_fieldname
        EXPORTING
          i_tabname   = 'VBAK'
          i_fieldname = 'VKORG'
          i_sign      = '~'
        IMPORTING
          e_combined  = gv_source.
    *Add the where line
      CALL METHOD ob_select->add_line
        EXPORTING
          i_line = gv_source.
      CLEAR gv_source.
      CALL METHOD cl_rs_where=>build_tabname_fieldname
        EXPORTING
          i_tabname   = 'VBAK'
          i_fieldname = 'KUNNR'
          i_sign      = '~'
        IMPORTING
          e_combined  = gv_source.
    *Add the where line
      CALL METHOD ob_select->add_line
        EXPORTING
          i_line = gv_source.
      CLEAR gv_source.
      CALL METHOD cl_rs_where=>build_tabname_fieldname
        EXPORTING
          i_tabname   = 'VBAK'
          i_fieldname = 'NETWR'
          i_sign      = '~'
        IMPORTING
          e_combined  = gv_source.
    *Add the where line
      CALL METHOD ob_select->add_line
        EXPORTING
          i_line = gv_source.
    *Add Sales order item fields
      CALL METHOD cl_rs_where=>build_tabname_fieldname
        EXPORTING
          i_tabname   = 'VBAP'
          i_fieldname = 'POSNR'
          i_sign      = '~'
        IMPORTING
          e_combined  = gv_source.
    *Add the where line
      CALL METHOD ob_select->add_line
        EXPORTING
          i_line = gv_source.
      CLEAR gv_source.
      CALL METHOD cl_rs_where=>build_tabname_fieldname
        EXPORTING
          i_tabname   = 'VBAP'
          i_fieldname = 'MATNR'
          i_sign      = '~'
        IMPORTING
          e_combined  = gv_source.
    *Add the where line
      CALL METHOD ob_select->add_line
        EXPORTING
          i_line = gv_source.
      CLEAR gv_source.
      CALL METHOD cl_rs_where=>build_tabname_fieldname
        EXPORTING
          i_tabname   = 'VBAP'
          i_fieldname = 'ARKTX'
          i_sign      = '~'
        IMPORTING
          e_combined  = gv_source.
    *Add the where line
      CALL METHOD ob_select->add_line
        EXPORTING
          i_line = gv_source.
      CLEAR gv_source.
      CALL METHOD cl_rs_where=>build_tabname_fieldname
        EXPORTING
          i_tabname   = 'VBAP'
          i_fieldname = 'KWMENG'
          i_sign      = '~'
        IMPORTING
          e_combined  = gv_source.
    *Add the where line
      CALL METHOD ob_select->add_line
        EXPORTING
          i_line = gv_source.
    ENDFORM.                    " zf_build_select
    *&      Form  zf_build_from
    FORM zf_build_from .
      CREATE OBJECT ob_from.
    *Add opening bracket
      CALL METHOD ob_from->add_opening_bracket
      CLEAR gv_source.
    *Add the join condition.This can be made
    *fully dynamic as per your requirement
      gv_source = 'VBAK AS VBAK INNER JOIN VBAP AS VBAP'.
    *Add the where line
      CALL METHOD ob_from->add_line
        EXPORTING
          i_line = gv_source.
      CLEAR gv_source.
    *Add the join condition.This can be made
    *fully dynamic as per your requirement
      gv_source = 'ON VBAKVBELN = VBAPVBELN'.
    *Add the where line
      CALL METHOD ob_from->add_line
        EXPORTING
          i_line = gv_source.
    *Add the closing bracket
      CALL METHOD ob_from->add_closing_bracket
    ENDFORM.                    " zf_build_from
    *&      Form  zf_build_where
    FORM zf_build_where .
      DATA :
      lv_field TYPE REF TO data,
      lv_field_low TYPE REF TO data,
      lv_field_high TYPE REF TO data.
      CREATE OBJECT ob_where.
    *Add the field VBELN : Sales Document
    *Use this method if you want to assign a single value to a field
    *Set the value for VBELN : Sales Document Number
    CALL METHOD ob_where->add_field
       EXPORTING
         i_fieldnm  = 'VBAK~VBELN'
         i_operator = '='
         i_intlen   = 10
         i_datatp   = 'CHAR'
       IMPORTING
         e_r_field  = lv_field.
    CALL METHOD ob_where->set_value_for_field
       EXPORTING
         i_fieldnm = 'VBAK~VBELN'
         i_value   = '0000120020'.
    *Use this method if you want to assign a range of values
    *Set a range for the Sales Document number
      CALL METHOD ob_where->add_field_between_2values
        EXPORTING
          i_fieldnm      = 'VBAK~VBELN'
          i_intlen       = 10
          i_datatp       = 'CHAR'
        IMPORTING
          e_r_field_low  = lv_field_low
          e_r_field_high = lv_field_high.
      CALL METHOD ob_where->set_2values_for_field
        EXPORTING
          i_fieldnm    = 'VBAK~VBELN'
          i_value_low  = '0000120020'
          i_value_high = '0000120067'.
    *Set the 'AND' Clause
      CALL METHOD ob_where->add_and.
    *Add the field MATNR : Material
      CALL METHOD ob_where->add_field
        EXPORTING
          i_fieldnm  = 'MATNR'
          i_operator = '='
          i_intlen   = 18
          i_datatp   = 'CHAR'
        IMPORTING
          e_r_field  = lv_field.
    *Set the value for the Material field
      CALL METHOD ob_where->set_value_for_field
        EXPORTING
          i_fieldnm = 'MATNR'
          i_value   = '000000000050111000'.
    *Set the 'AND' Clause
      CALL METHOD ob_where->add_and
    *Add the field VKORG
      CALL METHOD ob_where->add_field
        EXPORTING
          i_fieldnm  = 'VKORG'
          i_operator = '='
          i_intlen   = 4
          i_datatp   = 'CHAR'
        IMPORTING
          e_r_field  = lv_field.
    *Set the value for VKORG : Sales Organization
      CALL METHOD ob_where->set_value_for_field
        EXPORTING
          i_fieldnm = 'VKORG'
          i_value   = 'GMUS'.
    ENDFORM.                    " zf_build_where

  • Mysterious where clause with japanese

    enviroment:
    PL/SQL Develope, Version 7.1.0.1337, Windows XP Professional 5.1 Build 2600 (Service Pack 2)
    Here is the problem, when i add a where clause with japanese, the data evaporated:
    SQL> select * from ja_test;
    EXECUTABLE_NAME DESCRIPTION
    XX00MRP0411C 需要供給データ作成マネージャ
    SQL> select * from ja_test j where j.description = '需要供給データ作成マネージャ';
    EXECUTABLE_NAME DESCRIPTION
    SQL>
    thanks in advance!

    Thanks for replies and Sorry for my rashness, maybe the following
    scripts could explain the problem more well. I create a table named
    ja_test with two fields(EXECUTABLE_NAME and DESCRIPTION), both of the
    type is varchar2, and there is only one record in the table,
    but the DESCRIPTION contains JAPANESE characters, when i use a where
    clause like this "where j.executable_name = 'XX00MRP0411C';", everything
    seems work fine, but when the where clase include JAPANESE characters
    like this "j.description = '需要供給データ作成マネージャ';", even if
    the "j.description" is copied form database, no records returned:
    SQL> select * from ja_test j where j.executable_name = 'XX00MRP0411C';
    EXECUTABLE_NAME DESCRIPTION
    XX00MRP0411C 需要供給データ作成マネージャ
    SQL> select * from ja_test j where j.description = '需要供給データ作成マネージャ';
    EXECUTABLE_NAME DESCRIPTION
    SQL> desc ja_test;
    Name Type Nullable Default Comments
    EXECUTABLE_NAME VARCHAR2(30)
    DESCRIPTION VARCHAR2(240) Y
    SQL>

  • Where Clause With Multiple Rows

    I am tracking Objects called Incidents. Incidents can be made up of an undetermined number of questions and answers, such that my table structure to store these incidents looks as follows:
    INCIDENT_ID     QUESTION_ID     ANSWER_ID
    10001             49100         100 ("YES")
    10001             49101         275 ("5 HOURS")
    10002             49100         102 ("NO")
    10002             49101         276 ("10 HOURS")I allow my users to enter complex queries, such as "give me all incidents where question 49100 equals YES AND question 49101 equals 5 or less, OR where 49100 equals NO and 49101 is greater than 5", etc...
    My problem is how to handle these types of complex queries. Right now, I bring all of the rows into a Java object, and then I can analyze the results using Java (this works elegantly and allows me to have very complex formulas).
    However, if I have to deal with millions of Incidents and Answers, bringing them all into Java seems to be very time consuming. I'd like to be able to handle everything in the database. Because I allow my users to enter the queries through a "query builder", I can't control how many conditions they might have. In other words, if I try to use inner queries in the WHERE clause, I may exceed limits.
    It would be easiest if I could translate this vertical table into a temporary horizontal table, and then run my query on this horizontal table. My problem is that some of my questions have 1000s of answers (where they might be picking from a large select list), and therefore I can't do sums and counts on all the choices in separate columns. If I try a bit field for each column, once again I can run out of space because of the 1000s of possible answers.
    Has anyone faced this issue before? What choices do I have to make this all work in the database without having to parse the results in Java?
    Michael

    I was under the impression that each medication uses a unique id itself (defined perhaps by the medical insurance industry) and that itemized lists contain that code. And thus the user can type in the code.
    If so then one could handle the interface using both of the following methods.
    - The user can type in the id (this is validated.)
    - The user can push a button to bring up a dialog that provides the list and also provides an intelligent search option. (Or the id field can just be an aspect of the intelligent search.)
    Even in a small doctor's office experienced users will probably know the common ids and it would be simpler for them to type that in. In a processing center this would be more important as the time to process each transaction directly impacts the bottom line. This becomes much more relevant when the users are paid bonuses based on how many transactions they process (and managers might get that as well.)

  • Urgent: Performance problem with where clause using IN and an OR condition

    Select statement is:
    select fl.feed_line_id
    from ap_expense_feed_lines_all fl
    where ((:1 is not null and
    fl.feed_line_id in (select distinct r2.object_id
    from xxdl_pcard_wf_routing_lists r2,
         per_people_f hr2
    where upper(hr2.full_name) like upper(:1||'%')
              and hr2.person_id = r2.person_id
    and r2.fyi_list is null
              and r2.sequence_number <> 0))
    or
    (:1 is null))
    If I modify the statement to remove the "or (:1 is null))" part at the bottom of the where clause, it returns in .16 seconds. If I modify the statement to only contain the "(:1 is null))" part of the where clause, it returns in .02 seconds. With the whole statement above, it returns in 477 seconds. Anyone have any suggestions?
    Explain plan for the whole statement is:
    (1) SELECT STATEMENT CHOOSE
    Est. Rows: 10,960 Cost: 212
    FILTER
    (2) TABLE ACCESS FULL AP.AP_EXPENSE_FEED_LINES_ALL [Analyzed]
    (2) Blocks: 8,610 Est. Rows: 10,960 of 209,260 Cost: 212
    Tablespace: APD
    (6) TABLE ACCESS BY INDEX ROWID HR.PER_ALL_PEOPLE_F [Analyzed]
    (6) Blocks: 4,580 Est. Rows: 1 of 85,500 Cost: 2
    Tablespace: HRD
    (5) NESTED LOOPS
    Est. Rows: 1 Cost: 4
    (3) TABLE ACCESS FULL XXDL.XXDL_PCARD_WF_ROUTING_LISTS [Analyzed]
    (3) Blocks: 19 Est. Rows: 1 of 1,303 Cost: 2
    Tablespace: XXDLD
    (4) UNIQUE INDEX RANGE SCAN HR.PER_PEOPLE_F_PK [Analyzed]
    Est. Rows: 1 Cost: 1
    Thanks in advance,
    Peter

    Thanks for the reply, but I have already checked what you are suggesting and I am pretty sure those are not causing the problem. The hr2.full_name column has an upper index and the (4) line of the explain plan shows that index being used. In addition, that part of the query executes on its own quickly.
    Because the sql is not displayed in an indented format on this page it is a little hard to understand the structure so I am going to restate what is happening.
    My sql is:
    select a_column
    from a_table
    where ((:1 is not null) and a_column in (sub-select statement)
    or
    (:1 is null))
    The :1 bind variable is set to a varchar2 entered on the screen of an application.
    If I execute either part of the sql without the OR condition, performance is good.
    If the :1 bind variable is null with the whole sql statement (so all rows or a_table are returned), performance is still good.
    If the :1 bind variable is a not-null value with the whole sql statement, performance stinks.
    As an example:
    where (('wa' is not null) and a_column in (sub-select statement)) -- fast
    where (('wa' is null)) -- fast
    where (('' is not null) and a_column in (sub-select statement) -- fast
    or
    ('' is null))
    where (('wa' is not null) and a_column in (sub-select statement) -- slow
    or
    ('wa' is null))

  • Referencing Aggregated Column Value in Where Clause

    Hello -
    I'm trying to determine how I can accomplish the following in the most straightforward, efficient way.
    Among other things, I'm selecting the following value from my table:
    max(received_date) as last_received_dateI also need to evaluate the "last_received_date" value as a condition in my where clause. However, I can't reference my aliased "last_received_date" column value, and when I try to evaluate max(received_date) in the where clause, I get the "group function is not allowed here" error.
    Does anyone know of a good workaround?
    Thanks,
    Christine

    Hi,
    Column aliases can be used in the ORDER BY clause: aside from that, they cannot be used in the same query where they are defined. The workarounds are
    (a) define the alias in a sub-query, and use it in a super-query, like Someoneelse did, or
    (b) repeat the aliased expression, as in the HAVING-clause, below.
    Aggregate functions are computed after the WHERE-clause. (That explains why you can do things like
    SELECT  MAX (received_date) last_received_date_2008
    FROM    table_x
    WHERE   TO_CHAR (received_date, 'YYYY')  = '2008';).
    The HAVING-clause is like the WHERE-clause, but it is applied after the aggregate functions are computed, e.g.
    SELECT    deptno
    ,         MAX (recieved_date)  AS last_received_date
    FROM      table_x
    GROUP BY  deptno
    HAVING    MAX (received_date)    > SYSDATE - 7   -- Only show deptartments with activity in the last week
    ;

  • Where clause with Bind Variable in ViewObject

    As per recomendations from Jdev team they say that using Bind varialbles in where clause will improve the performance (Option 1) But it is causing us to create more view objects.
    Example : Lets say we have a View Object EmpVO
    Option 1:
    ViewObject vo=context.getViewObject("EmpVO");
    vo.setWhereClause("EMPNO=?");
    vo.setWhereClauseParam(0,st);
    (or)
    Option 2:
    vo.setWhereClause("EMPNO="+st);
    If we want to use same View Object "EmpVO" in another Action Class
    ViewObject vo1=context.getViewObject("EmpVO");
    vo1.setWhereClause("DEPTNO=?");
    vo1.setWhereClauseParam(0,str);
    It this case it throws an error saying BIND VARIABLE already exits. So we have to make another View Object.
    Where as if we did not use bind variable but used Option 2 approach the same view object can be used in multiple pages.(at the expense of performance as per Jdev team)
    Are we doing something wrong here or are there other ways to use the same view object when using bind variable in where clause.
    Thanks

    I haven't been using BC4J for a while, but I seem to recall that the recommendations are that you don't set the where clause at runtime: You're supposed to define your view with the bind parameter already in it.
    So you'd probably define an EmpsForEmpNoVO and type "EMPNO = ?" in the where box. (There are other ways of finding a single row/entity and one of those may well be more efficient. Perhaps a better example of where you might want a view of employees is WHERE DEPTNO = ?.)
    IIRC, all instances of a particular type of view share the same definition, so you have to be careful if you alter that at runtime. However, I think everything's set up so that you can have many different (and separate) resultsets for a single view (instance) - meaning that it's possible to "run" a view for (e.g.) two different ids. (It's definitely possible to create two different instances of a view from its definition - and the resultsets will definitely be separate then. I think there's a "create" method on the application module; I remember that "find..." always returns the same instance of the view.)
    Hope that's a push in the right direction (since no-one else had replied - and I hope not too much has changed since 9.0.3)....
    Mike.

Maybe you are looking for

  • Need advise : Risks of using  materialized views

    Hi - I need some advise on whether using a materilzied view can help in teh folloiwng scenario. Scenario : You have a large tables which has sy 60 million rows, This is a demand management application which accesses this data at various aggregate lev

  • How to I use Microsoft Word to create or edit documents on my ipad2?

    I have a PC laptop, an ipad2 and iphone 4s. I would like to do school work on my ipad2. How to I create documents with microsoft word on my ipad? Or if I have an assignment saved as a word.doc on my pc, how can I edit it or save it on my ipad? Thanks

  • Interlaced and choppy looking video

    Hi, I have a 16:9 NTSC Motion menu I am trying to encode in compressor for DVDSP. Unfortunately, when compressed with DVD: Best Quality 90 minutes preset (even at 23.97 FPS, progressive) it still looks choppy with interlace artifacting. If I drop it

  • Options now that Startup disc is almost full?

    I have a Macbook Pro, running Mac OS X 10.7.4.   It just ran through its 3 year waranty period in January but not before having its entire back screen replaced as well as the 2 x 2Gb ram cards intergrated into the motherboard all due to a video issue

  • How to add composition to Media Encoder using Script?

    On AE CS6 I used to add compositions to render queue using scripts. (jsx). Since Adobe depreciated some encoders scripts can not use those presents. I want to switch to Adobe Encoder and I want to add compositions to its queue using scripts. Is there