Left join and where clause with not equal ( ) returns too many rows

Say I have something like this
Table A
=========
Id
OrderNum
Date
StoreName
AddressKey
Table B
========
Id
StreetNumber
City
State
select a.* from [Table A] a
left join [Table B] b on a.AddressKey = b.Id
where a.StoreName <> 'Burger place'
The trouble is that the above query still returns rows that have StoreName = 'Burger place'
One way Ive handled this is to use a table expression, select everything into that, then select from the CTE and apply the filter there.  How could you handle it in the same query however?

Hi Joe,
Thanks for your notes.
INT SURROGATE PRIMARY KEY provides a small footprint JOIN ON column. Hence performance gain and simple JOIN programming.  In the Addresses table, address_id is 4 bytes as opposed to 15 bytes san. Similarly for the Orders table.
INT SURROGATE PRIMARY KEY is a meaningless number which can be duplicated at will in other tables as FOREIGN KEY.  Having a meaningful PRIMARY KEY violates the RDBMS basics about avoiding data duplication.  If I make CelebrityName (Frank Sinatra)
a PRIMARY KEY, I have to duplicate "Frank Sinatra" as an FK wherever it needed as opposed to duplicating SURROGATE PRIMARY KEY CelebrityID (79) a meaningless number.
This is how we design in SQL Server world.
QUOTE from Wiki: "
Advantages[edit]
Immutability[edit]
Surrogate keys do not change while the row exists. This has the following advantages:
Applications cannot lose their reference to a row in the database (since the identifier never changes).
The primary or natural key data can always be modified, even with databases that do not support cascading updates across related
foreign keys.
Requirement changes[edit]
Attributes that uniquely identify an entity might change, which might invalidate the suitability of natural keys. Consider the following example:
An employee's network user name is chosen as a natural key. Upon merging with another company, new employees must be inserted. Some of the new network user names create conflicts because their user names were generated independently (when the companies
were separate).
In these cases, generally a new attribute must be added to the natural key (for example, an
original_company column). With a surrogate key, only the table that defines the surrogate key must be changed. With natural keys, all tables (and possibly other, related software) that use the natural key will have to change.
Some problem domains do not clearly identify a suitable natural key. Surrogate key avoids choosing a natural key that might be incorrect.
Performance[edit]
Surrogate keys tend to be a compact data type, such as a four-byte integer. This allows the database to query the single key column faster than it could multiple columns. Furthermore a non-redundant distribution of keys causes the resulting
b-tree index to be completely balanced. Surrogate keys are also less expensive to join (fewer columns to compare) than
compound keys.
Compatibility[edit]
While using several database application development systems, drivers, and
object-relational mapping systems, such as
Ruby on Rails or
Hibernate, it is much easier to use an integer or GUID surrogate keys for every table instead of natural keys in order to support database-system-agnostic operations and object-to-row mapping.
Uniformity[edit]
When every table has a uniform surrogate key, some tasks can be easily automated by writing the code in a table-independent way.
Validation[edit]
It is possible to design key-values that follow a well-known pattern or structure which can be automatically verified. For instance, the keys that are intended to be used in some column of some table might be designed to "look differently from"
those that are intended to be used in another column or table, thereby simplifying the detection of application errors in which the keys have been misplaced. However, this characteristic of the surrogate keys should never be used to drive any of the logic
of the applications themselves, as this would violate the principles of
Database normalization"
LINK: http://en.wikipedia.org/wiki/Surrogate_key
Kalman Toth Database & OLAP Architect
SQL Server 2014 Database Design
New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014

Similar Messages

  • SQL subquery returning too many rows with Max function

    Hello, I hope someone can help me, I been working on this all day. I need to get max value, and the date and id where that max value is associated with between specific date ranges. Here is my code , and I have tried many different version but it still returning
    more than one ID and date
    Thanks in advance
    SELECT
      distinctbw_s.id, 
    avs.carProd,cd_s.RecordDate,
    cd_s.milkProductionasMilkProd,
    cd_s.WaterProductionasWaterProd
    FROMtblTestbw_s
    INNERJOINtblTestCpcd_sWITH(NOLOCK)
    ONbw_s.id=cd_s.id   
    ANDcd_s.recorddateBETWEEN'08/06/2014'AND'10/05/2014'
    InnerJoin
    (selectid,max(CarVol)ascarProd
    fromtblTestCp
    whererecorddateBETWEEN'08/06/2014'AND'10/05/2014'
     groupby 
    id)avs
    onavs.id=bw_s.id
    id RecordDate carProd       MilkProd WaterProd
    47790 2014-10-05   132155   0 225
    47790 2014-10-01   13444    0 0
    47790 2014-08-06   132111    10 100
    47790 2014-09-05   10000    500 145
    47790 2014-09-20   10000    800 500
    47791 2014-09-20   10000    300 500
    47791 2014-09-21   10001    400 500
    47791 2014-08-21   20001    600 500
    And the result should be ( max carprod)
    id RecordDate carProd       MilkProd WaterProd
    47790 2014-10-05   132155  0 225
    47791 2014-08-21   20001    600 500

    Help your readers help you.  Remember that we cannot see your screen, do not know your data, do not understand your schema, and cannot test a query without a complete script.  So - remove the derived table (to which you gave the alias "avs")
    and the associated columns from your query.  Does that generate the correct results?  I have my doubts since you say "too many" and the derived table will generate a single row per ID.  That suggests that your join between the first
    2 tables is the source of the problem.  In addition, the use of DISTINCT is generally a sign that the query logic is incorrect, that there is a schema issue, or that there is a misunderstanding of the schema. 

  • Oracle UPDATE syntax with JOIN and WHERE clause

    I need to update one of my tables, and can't seem to get the syntax right. I've tried a 4 different approaches, but not having any luck.  Any help would be greatly appreciated.
    Attempt #1: Error: SQL command not properly ended
    UPDATE TESTDTA.F4941
    SET TESTDTA.F4941.RSDSTN=TESTDTA.F4981.FHRTDQ,TESTDTA.F4941.RSUMD1=TESTDTA.F4981.FHUOM
    FROM TESTDTA.F4941
    INNER JOIN TESTDTA.F4981
    ON TESTDTA.F4941.RSSHPN  = TESTDTA.F4981.FHSHPN
    WHERE TESTDTA.F4941.RSSHPN = 647143
    AND TESTDTA.F4941.RSDSTN = 0
    AND TESTDTA.F4941.RSADDJ  > 110365
    AND TESTDTA.F4981.FHCGC1  = 'DIS';
    Attempt #2: Error report: SQL Error: ORA-00904: "TESTDTA"."F4981"."FHUOM": invalid identifier 00904. 00000 - "%s: invalid identifier"
    UPDATE (SELECT TESTDTA.F4941
    FROM TESTDTA.F4941
    INNER JOIN TESTDTA.F4981
    ON TESTDTA.F4941.RSSHPN  = TESTDTA.F4981.FHSHPN
    WHERE TESTDTA.F4941.RSSHPN = 647143
    AND TESTDTA.F4941.RSDSTN = 0
    AND TESTDTA.F4941.RSADDJ  > 110365
    AND TESTDTA.F4981.FHCGC1  = 'DIS')
    SET TESTDTA.F4941.RSDSTN=TESTDTA.F4981.FHRTDQ,TESTDTA.F4941.RSUMD1=TESTDTA.F4981.FHUOM
    Attempt #3: Error report: SQL Error: ORA-00904: "TESTDTA"."F4941": invalid identifier 00904. 00000 - "%s: invalid identifier"
    UPDATE (SELECT *
    FROM TESTDTA.F4941
    INNER JOIN TESTDTA.F4981
    ON TESTDTA.F4941.RSSHPN  = TESTDTA.F4981.FHSHPN
    WHERE TESTDTA.F4941.RSSHPN = 647143
    AND TESTDTA.F4941.RSDSTN = 0
    AND TESTDTA.F4941.RSADDJ  > 110365
    AND TESTDTA.F4981.FHCGC1  = 'DIS')
    SET TESTDTA.F4941.RSDSTN=TESTDTA.F4981.FHRTDQ,TESTDTA.F4941.RSUMD1=TESTDTA.F4981.FHUOM;
    Attempt #4: Error: ORA-00925: missing INTO keyword 00925. 00000 - "missing INTO keyword"
    MERGE TESTDTA.F4941
    USING TESTDTA.F4981
    ON (TESTDTA.F4941.RSSHPN  = TESTDTA.F4981.FHSHPN
    AND TESTDTA.F4941.RSSHPN = 647143
    AND TESTDTA.F4941.RSDSTN = 0
    AND TESTDTA.F4941.RSADDJ  > 110365
    AND TESTDTA.F4981.FHCGC1  = 'DIS'
    WHEN MATCHED THEN
    UPDATE SET TESTDTA.F4941.RSDSTN=TESTDTA.F4981.FHRTDQ
       ,TESTDTA.F4941.RSUMD1=TESTDTA.F4981.FHUOM;

    thank you for the attempt, but I get this error trying your method...
    Error report:
    SQL Error: ORA-01779: cannot modify a column which maps to a non key-preserved table
    01779. 00000 -  "cannot modify a column which maps to a non key-preserved table"
    *Cause:    An attempt was made to insert or update columns of a join view which
               map to a non-key-preserved table.
    *Action:   Modify the underlying base tables directly.
    as for the background of what I'm trying to...
    I have 2 tables, one that has shipments with no miles (F4941 / Routing Steps), and another that does have miles (F4981 / Freight Audit History).
    I want to update the miles & UnitOfMeasure columns for all shipments in the F4941 that currently have 0 miles with the miles found in the F4981 which are connected by Shipment number.  Here's my same script, with simpler naming.
    UPDATE RoutingSteps
    SET RoutingSteps.Miles=FreightAuditHistory.Miles,RoutingSteps.UnitOfMeasure=FreightAuditHistory.UnitOfMeasure
    FROM RoutingSteps
    INNER JOIN FreightAuditHistory
    ON RoutingSteps.ShipmentNumber  = FreightAuditHistory.ShipmentNumber
    WHERE RoutingSteps.ShipmentNumber = 647143
    AND RoutingSteps.Miles = 0
    AND RoutingSteps.ShipmentDate  > 110365
    AND FreightAuditHistory.Category  = 'DIS';
    hope this helps visualize my intent

  • Left outer join using date range returns too many rows

    I am trying to pull data for a website.
    Names table:
    company_name varchar2(30)
    julian_day varchar2(3)
    logins number(3)
    login_errors number(3)
    Given a julian date range (e.g. 250-252), I am displaying the information from the Names table.
    The problem is that I also need to display changes (increases/decreases) in the data. I do that by coloring the text based on a 10% increase/decrease. Data for the 3 days 250-252 would be compared to data for the previous 3 days 247-249.
    Not all companies will report data on all days, so some gaps in the data may exist. Therefore, I cannot do just a simple join.
    I am trying to write a query that will give me this information if the user chooses days 250-252.
    Company_name
    sum(logins) for days 250-252
    sum(login_errors) for days 250-252
    sum(logins) for days 247-249
    sum(login_errors) for days 247-249
    The query I'm using is:
    select cur.company_name, sum(cur.logins),
    sum(cur.login_errors), sum(old.logins), sum(old.login_errors)
    FROM names cur LEFT OUTER JOIN names old
    ON cur.company_name = old.company_name
    WHERE cur.adate>='250' and cur.adate<='252'
    and old.adate>='247' and old.adate<='249'
    GROUP by cur.company_name
    Given this data:
    Company_name adate logins login_errors
    ABC 247 10 10
    ABC 248 20 20
    ABC 249 30 30
    ABC 250 15 15
    ABC 251 25 25
    ABC 252 35 35
    My problem is that it returns:
    adate cur.logins cur.login_err old.logins old.login_err
    250 15 15 60 60
    251 25 25 60 60
    252 35 35 60 60
    How can I get it to only give me the one "old" day's data? I went with the LEFT OUTER JOIN because it's possible that there is no data for an "old" day.
    Thanks in advance.....

    Your problem stems from the join itself, and would be the same even without the OUTER JOIN. With your data, there are 3 records in cur and 3 records in old. The join matches each record in cur to each record in old resulting in 9 records in total. Without the SUM, this is clear:
    SQL> SELECT cur.company_name, cur.logins, cur.login_errors,
      2         old.logins, old.login_errors, cur.adate cad, old.adate oad
      3  FROM names cur LEFT OUTER JOIN names old
      4                 ON cur.company_name = old.company_name
      5  WHERE cur.adate>=250 and cur.adate<=252 and
      6        old.adate>=247 and old.adate<=249;
    COMPANY_NA     LOGINS LOGIN_ERRORS     LOGINS LOGIN_ERRORS        CAD        OAD
    ABC                35           35         10           10        252        247
    ABC                25           25         10           10        251        247
    ABC                15           15         10           10        250        247
    ABC                35           35         20           20        252        248
    ABC                25           25         20           20        251        248
    ABC                15           15         20           20        250        248
    ABC                35           35         30           30        252        249
    ABC                25           25         30           30        251        249
    ABC                15           15         30           30        250        249
    9 rows selected.You can do this with only one reference to the table.
    SELECT company_name,
           SUM(CASE WHEN adate BETWEEN 250 and 252 THEN logins ELSE 0 END) curlog,
           SUM(CASE WHEN adate BETWEEN 250 and 252 THEN login_errors ELSE 0 END) curerr,
           SUM(CASE WHEN adate BETWEEN 247 and 249 THEN logins ELSE 0 END) oldlog,
           SUM(CASE WHEN adate BETWEEN 247 and 249 THEN login_errors ELSE 0 END) olderr
    FROM names
    WHERE adate BETWEEN 247 and 252
    GROUP BY company_nameHTH
    John

  • CONNECT BY with CROSS JOIN and WHERE not executing as described in doc

    Hello all,
    please see these two statements. They are the same, but the 1st uses t1 INNER JOIN t2 while the snd uses a CROSS JOIN with WHERE.
    The 2nd statement shows one row more than the first, but the CROSS JOIN with WHERE is the same as the INNER JOIN.
    The result would be OK if Oracle did:
    JOIN -> CONNECT BY PRIOR -> WHERE
    But according to the docs it does:
    JOIN (and WHEREs for JOINS) -> CONNECT BY PRIOR -> Rest of WHERE
    See http://docs.oracle.com/cd/E11882_01/server.112/e26088/queries003.htm#SQLRF52332 for details. There it says:
    Oracle processes hierarchical queries as follows:
    A join, if present, is evaluated first, whether the join is specified in the FROM clause or with WHERE clause predicates.
    The CONNECT BY condition is evaluated.
    Any remaining WHERE clause predicates are evaluated.
    +.....+
    Is this a bug? I'd say yes, because it differs from the docs and it also is not what people are used to ("a,b WHERE" is the same as "a INNER JOIN b").
    Thanks,
    Blama
    --Statement 1:
    WITH t1
    AS
    (SELECT 1 a, 2 b FROM DUAL UNION ALL
    SELECT 2 a, 3 b FROM DUAL UNION ALL
    SELECT 3 a, 4 b FROM DUAL UNION ALL
    SELECT 4 a, 5 b FROM DUAL UNION ALL
    SELECT 5 a, 6 b FROM DUAL),
    t2 AS
    (SELECT 1 c FROM DUAL UNION ALL
    SELECT 2 c FROM DUAL UNION ALL
    SELECT 3 c FROM DUAL UNION ALL
    SELECT 5 c FROM DUAL)
    SELECT DISTINCT t1.a, t2.c, t1.b, level, SYS_CONNECT_BY_PATH(t1.a, '/') Path
    FROM t1 INNER JOIN t2
    ON t1.a = t2.c
    CONNECT BY t1.a = PRIOR t1.b
    START WITH t1.a = 1
    ORDER BY
    1,2,3;
    --Result:
    --1     1     2     1     /1
    --2     2     3     2     /1/2
    --3     3     4     3     /1/2/3
    --Statement 2:
    WITH t1
    AS
    (SELECT 1 a, 2 b FROM DUAL UNION ALL
    SELECT 2 a, 3 b FROM DUAL UNION ALL
    SELECT 3 a, 4 b FROM DUAL UNION ALL
    SELECT 4 a, 5 b FROM DUAL UNION ALL
    SELECT 5 a, 6 b FROM DUAL),
    t2 AS
    (SELECT 1 c FROM DUAL UNION ALL
    SELECT 2 c FROM DUAL UNION ALL
    SELECT 3 c FROM DUAL UNION ALL
    SELECT 5 c FROM DUAL)
    SELECT DISTINCT t1.a, t2.c, t1.b, level, SYS_CONNECT_BY_PATH(t1.a, '/') Path
    FROM t1 CROSS JOIN t2
    WHERE t1.a = t2.c
    CONNECT BY t1.a = PRIOR t1.b
    START WITH t1.a = 1
    ORDER BY
    1,2,3;
    --Result:
    --1     1     2     1     /1
    --2     2     3     2     /1/2
    --3     3     4     3     /1/2/3
    --5     5     6     5     /1/2/3/4/5My details:
    Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
    PL/SQL Release 11.2.0.2.0 - Production
    CORE     11.2.0.2.0     Production
    TNS for Solaris: Version 11.2.0.2.0 - Production
    NLSRTL Version 11.2.0.2.0 - Production

    blama wrote:
    Hello Paul,
    that means that "a,b" isn't the same as "a CROSS JOIN b".
    I don't think that that is really the case.
    Do you have docs on this one?No explicit docs just (my) logic - having said that, I suppose it is implied that if you are doing ANSI style joins, it's not the where clauses that
    are specifying the join.
    If you do t1,t2 where t1.a=t2.a then Oracle figures out the kind of join from the (relevant) where clauses and treats the other where clauses after the CONNECT BY.
    If you do t1 cross join t2 where t1.a=t2.a then you are saying the join is completely specified by the CROSS JOIN - i.e it's Cartesian. Oracle doesn't look at the where clauses for this. Therefore
    all where clauses are treated as 'other' and are evaluated after the CONNECT BY.
    So, in my mind it's 10g that has the bug.

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

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

  • Absolute dynamic select query with dynamic join and where

    Has anyone ever tried creating an absolutely dynamic SELECT query with dynamic Join and Where conditions.
    I have a requirement of creating such a query in an Utility Class, and i have written the code. But its throwing my sysntax errors.
    Please let me know where am I going wrong OR is it really possible to create such a dynamic Query??
        SELECT (FIELDS) INTO TABLE IT_TABLES
          FROM ( (ME->TABLE1)  inner join ( me->table2 )
          on ( on_condition ) )
          WHERE (me->where_fields).
    Ags.

    It worked for me in a following way:
    select * into corresponding fields of table <result_table>
            from (join_string)
            where (l_where).
    Where the contents of join_string were dynamically build using concatenation. So it will be something like
    concatenate ME->TABLE1 'as a INNER JOIN' me->table2 'as b ON (' into join_string separated by space.
    <...>
    add here matching/reference colums, something like
    concatenate 'a~' me->TABLE1_JOIN_COL into temp1.
    concatenate 'b~' me->TABLE2_JOIN_COL into temp2.
    concatenate join_string temp1 '=' temp2 into join_string separated by space.
    <...>
    concatenate join_string ')' into join_string separated by space.
    And then use similar approach for l_where variable.

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

  • Query in the where clause is not allowed

    Hi all,
    I have a table m_vehicle that stores 1 or more than 1 rows of data for each person. But the partner's schema requires that 0 or 1 vehicle license plate data be sent with the xml file. I have the following nested select statement inside a bigger one and it does not work,
    select xmlelement("VehicleLicensePlate",
         (case when mv.lic_plate_state is not null then
              xmlelement("PlateState", mv.lic_plate_state)
         end), -- end of plate state
         (case when mv.lic_plate_no is not null then
              xmlelement("PlateNumber", xmlelement("ID", mv.lic_plate_no))
         end),
         (case when mv.lic_plate_year is not null then
              xmlelement("PlateExpiryYear", mv.lic_plate_year)                                                  
         end)
         ).extract('/*')
    from m_vehicle mv where mv.mni_id = 1083650
    and mv.seq_no = (select max(mv2.seq_no) from m_vehicle mv2
    where mv2.mni_id = mv.mni_id) and mv.lic_plate_no is not null
    But it works when I run it alone and gets the latest row for the person. It does not work either if I join this table with other tables. My root element select is from dual because I have to supply lots of SOAP and other artifacts in the xml. Is it because I have this root select from dual that the query in the where clause does not work? How do I make it work so that I get 0 or one row only from the table? My solution was to write a function that returns each part of the license plate data using dymanic sql and call it in the xmlelement function. It works but I would like to use plain sql instead.
    Thanks.
    Ben

    By the way, the error I get is this,
    ERROR:
    ORA-31011: XML parsing failed
    ORA-19202: Error occurred in XML processing
    LPX-00216: invalid character 3 (0x3)
    Error at line 1
    ORA-06512: at "SYS.XMLTYPE", line 111
    Ben

  • Error while using REMAP_TABLE and WHERE clause  together in IMPDP

    I am trying to move some records from a very large table to another small table.
    I am facing trouble while using REMAP_TABLE and WHERE clause together in IMPDP.
    Problem is data filter is not getting applied and all records are getting imported.
    here is how I have simulated this. please advice.
    CREATE TABLE TSHARRHB.TMP1
      A  NUMBER,
      B  NUMBER
    begin
    Insert into TSHARRHB.TMP1
       (A, B)
    Values
       (1, 1);
    Insert into TSHARRHB.TMP1
       (A, B)
    Values
       (2, 2);
    COMMIT;
    end;
    expdp system/password TABLES=tsharrhb.TMP1 DIRECTORY=GRDP_EXP_DIR DUMPFILE=TMP1.dmp REUSE_DUMPFILES=YES LOGFILE=EXP.log PARALLEL=8
    impdp system/password DIRECTORY=GRDP_EXP_DIR DUMPFILE=TMP1.dmp LOGFILE=imp.log PARALLEL=8 QUERY='TSHARRHB.TMP1:"WHERE TMP1.A = 2"'  REMAP_TABLE=TSHARRHB.TMP1:TMP3 CONTENT=DATA_ONLY
    Import: Release 11.2.0.1.0 - Production on Fri Dec 13 05:13:30 2013
    Copyright (c) 1982, 2009, Oracle and/or its affiliates.  All rights reserved.
    Connected to: Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
    With the Partitioning, Automatic Storage Management, OLAP, Data Mining
    and Real Application Testing options
    Master table "SYSTEM"."SYS_IMPORT_FULL_01" successfully loaded/unloaded
    Starting "SYSTEM"."SYS_IMPORT_FULL_01":  system/********@GRD6.RBSG DIRECTORY=GRDP_EXP_DIR DUMPFILE=TMP1.dmp LOGFILE=SSD_93_TABLES_FULL_EXP.log PARALLEL=8 QUERY=TSHARRHB.TMP1:"WHERE TMP1.A = 2" REMAP_TABLE=TSHARRHB.TMP1:TMP3 CONTENT=DATA_ONLY
    Processing object type TABLE_EXPORT/TABLE/TABLE_DATA
    . . imported "TSHARRHB"."TMP3"                           5.421 KB       2 rows
    Job "SYSTEM"."SYS_IMPORT_FULL_01" successfully completed at 05:13:33
    here I am expecting only 1 record to get imported but both the records are getting imported. please advice.

    The strange thing compared to your output is that I get an error when I have table prefix in the query block:
    Connected to: Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
    With the Partitioning, OLAP, Data Mining and Real Application Testing options
    Master table "SYSTEM"."SYS_IMPORT_FULL_01" successfully loaded/unloaded
    Starting "SYSTEM"."SYS_IMPORT_FULL_01":  system/******** DUMPFILE=TMP1.dmp LOGFILE=imp.log PARALLEL=8 QUERY=SYSADM.TMP1:"WHERE TMP1.A = 2" REMAP_TABLE=SYSADM.TMP1:TMP3 CONTENT=DATA_ONLY
    Processing object type TABLE_EXPORT/TABLE/TABLE_DATA
    ORA-31693: Table data object "SYSADM"."TMP3" failed to load/unload and is being skipped due to error:
    ORA-38500: Unsupported operation: Oracle XML DB not present
    Job "SYSTEM"."SYS_IMPORT_FULL_01" completed with 1 error(s) at Fri Dec 13 10:39:11 2013 elapsed 0 00:00:03
    And if I remove it, it works:
    Connected to: Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
    With the Partitioning, OLAP, Data Mining and Real Application Testing options
    Master table "SYSTEM"."SYS_IMPORT_FULL_01" successfully loaded/unloaded
    Starting "SYSTEM"."SYS_IMPORT_FULL_01":  system/******** DUMPFILE=TMP1.dmp LOGFILE=imp.log PARALLEL=8 QUERY=SYSADM.TMP1:"WHERE A = 2" REMAP_TABLE=SYSADM.TMP1:TMP3 CONTENT=DATA_ONLY
    Processing object type TABLE_EXPORT/TABLE/TABLE_DATA
    . . imported "SYSADM"."TMP3"                             5.406 KB       1 out of 2 rows
    Job "SYSTEM"."SYS_IMPORT_FULL_01" successfully completed at Fri Dec 13 10:36:50 2013 elapsed 0 00:00:01
    Nicolas.
    PS: as you can see, I'm on 11.2.0.4, I do not have 11.2.0.1 that you seem to use.

  • 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

  • Where clause is not being passed to the report

    I just upgraded my crystal reports from 10.0 to 11 R2. Reports were working fine in 10.0 version,
    Reports are called from vb.net (vissual studio 2005). When I was running this reports using crystal 10.0 and visual studio 2005, it was working fine, After the upgrade report runs but I am noticing that where clause is not being passed to the reports.It generates report as there is no where clause and produces multiple pages report.

    I believe you are encountering an issue documented in [this|https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/oss_notes_boj/sdn_oss_boj_bip/sap(bD1lbiZjPTAwMQ==)/bc/bsp/spn/scn_bosap/notes.do] note.
    Ludek

  • Qualifying Expression and WHERE CLAUSE Extension

    I would like to know the exact difference between 'Qualifying Expression and WHERE CLAUSE Extension'. Since both are meant to contain some CONDITION that would facilitate the Edit Check's success, So I am sometimes a bit confused with these too as to when to use what.
    Can someone help Please??

    As you can tell from my previous posts (requests!) - I'm a newbie to OC.
    From the documentation - it appears that both Qualifying expression and Where Clause work the same way but the way they execute is different.
    Qualifying expression is applied after the fetch (key fields and question response data from DCM cursor i.e., after the cursor fetches the data) and Where clause filters before QG fetch.
    HTH

  • 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                                                                                                                                                                                                                                                                                                                                                                                                                                   

Maybe you are looking for