Syntax errors in update query with inner joins and sub query.

Below is the query:
UPDATE sp_CFQ_Coord_Corrections 
INNER JOIN (CFQ_Coord_Corrections 
INNER JOIN CFQ_Referrals ON CFQ_Coord_Corrections.CorrID = CFQ_Referrals.RecID) 
ON sp_CFQ_Coord_Corrections.ID = CFQ_Referrals.RecID 
SET CFQ_Coord_Corrections.MatchFound = 1, 
CFQ_Coord_Corrections.RecTblID = [CFQ_Referrals].[RecTblID], 
sp_CFQ_Coord_Corrections.MatchFound = 1
WHERE (((CFQ_Coord_Corrections.MatchFound)=0) 
AND ((sp_CFQ_Coord_Corrections.MatchFound)=0) 
AND ((CFQ_Coord_Corrections.RecImported)=1) 
AND ((CFQ_Referrals.RecFileName)='COORDCORR_SPOINT') 
AND ((CFQ_Referrals.RecCombKey)='No.Match') 
AND ((sp_CFQ_Coord_Corrections.RecImported)=1));
Error messages seen when executed:
Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'INNER'.
Msg 102, Level 15, State 1, Line 10
Incorrect syntax near 'CFQ_Coord_Corrections'.
Please help.....

Below is the query:
UPDATE sp_CFQ_Coord_Corrections 
INNER JOIN (CFQ_Coord_Corrections 
INNER JOIN CFQ_Referrals ON CFQ_Coord_Corrections.CorrID = CFQ_Referrals.RecID) 
ON sp_CFQ_Coord_Corrections.ID = CFQ_Referrals.RecID 
SET CFQ_Coord_Corrections.MatchFound = 1, 
CFQ_Coord_Corrections.RecTblID = [CFQ_Referrals].[RecTblID], 
sp_CFQ_Coord_Corrections.MatchFound = 1
WHERE (((CFQ_Coord_Corrections.MatchFound)=0) 
AND ((sp_CFQ_Coord_Corrections.MatchFound)=0) 
AND ((CFQ_Coord_Corrections.RecImported)=1) 
AND ((CFQ_Referrals.RecFileName)='COORDCORR_SPOINT') 
AND ((CFQ_Referrals.RecCombKey)='No.Match') 
AND ((sp_CFQ_Coord_Corrections.RecImported)=1));
Error messages seen when executed:
Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'INNER'.
Msg 102, Level 15, State 1, Line 10
Incorrect syntax near 'CFQ_Coord_Corrections'.
Please help.....
sp_CFQ_Coord_Corrections is a table and not a stored procedure.
are these both tables "sp_CFQ_Coord_Corrections" and "CFQ_Coord_Corrections" different ??

Similar Messages

  • Update statement with inner join issues

    I have searched for the answer on this and not really 100%....so figured I would ask...be nice :)
    what have I done wrong? Or am I just going about this the wrong way? I have looked at the oracle docs and I can't find an example showing me this. I do see where you SET values based on the select query results. I want to update the result of a query based on the join with static values....
    UPDATE table.a
    SET table.a_STATUS=9,table.a.INDEX = 'N'
    WHERE (SELECT table.a INNER JOIN table.b ON (table.a.COMPANY = table.b.COMPANY) AND (table.a.PO_NUMBER =table.b.PO_NUMBER) AND (table.a.PO_RELEASE =table.b.PO_RELEASE) AND (table.a.PO_CODE =table.b.PO_CODE) AND (table.a_STATUS=1) AND (table.b.CLOSED_FL = 'Y'));

    Hi,
    Welcome to the forum!
    user11360811 wrote:
    I have searched for the answer on this and not really 100%....so figured I would ask...be nice :)
    what have I done wrong? Or am I just going about this the wrong way? I have looked at the oracle docs and I can't find an example showing me this. I do see where you SET values based on the select query results. I want to update the result of a query based on the join with static values....
    UPDATE table.aThat's updating a table called A in a schema called TABLE (which is not a good name for any user-named object). Are those really your table and schema names? Perhaps you meant to have an underscore instead of a dot:
    UPDATE  table_ais much, much more reasonable. It means the table name is TABLE_A (a perfectly good name) in the current schema.
    SET table.a_STATUS=9,table.a.INDEX = 'N'
    WHERE ( ...There's a syntax error. You can't just say
    "WHERE (sub-query)"; it has to be
    "WHERE EXISTS (sub-suery)" or
    "WHERE (sub-query) = some_value" or
    "WHERE some_value IN (sub_query)", or something similar. WHERE can never be used without some kind of comparison operator, such as EXISTS, = or IN.
    SELECT table.a INNER JOIN table.b ON ...Here are some more syntax errors. The correct syntax for any query is
    SELECT  column_list
    FROM    table_name ...If table.a is your (first) table name, then you're missing the list of columns to SELECT, and the mandatory keyword FROM.
    (table.a.COMPANY = table.b.COMPANY) AND (table.a.PO_NUMBER =table.b.PO_NUMBER) AND (table.a.PO_RELEASE =table.b.PO_RELEASE) AND (table.a.PO_CODE =table.b.PO_CODE) AND (table.a_STATUS=1) AND (table.b.CLOSED_FL = 'Y'));Some general advice about UPDATE:
    If it's not obvious how to use UPDATE to do what you want, then there's a good chance that UPDATE is the wrong tool for the job. MERGE might be much simpler, and more efficient as well. This is especially likely if you need to join the table that's being updated to some other table.
    Whenever you have a problem, please post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved. That way, the people who want to help you can re-create the problem and test their ideas.
    Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
    Simplify the problem as much as possible. Remove all tables and columns that play no role in this problem.
    If you're asking about a DML statement, such as UPDATE, the CREATE TABLE and INSERT statements should re-create the tables as they are before the DML, and the results will be the contents of the changed table(s) when everything is finished.
    Always say which version of Oracle you're using (for example, 11.2.0.2.0).
    See the forum FAQ {message:id=9360002}
    Edited by: Frank Kulash on Jan 17, 2013 4:58 PM

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

  • Hi! Everyone, I have some problems with JOIN and Sub-query; Could you help me, Please?

    Dear Sir/Madam
    I'm a student who is interested in Oracle Database and
    I have some problems with JOIN and Sub-query.
    I hope so many of you could help me.
    if i use JOIN without sub-query, may it be faster or not?
    SELECT field1, field2 FROM tableA INNER JOIN tableB
    if i use JOIN with sub-query, may it be faster or not?
    SELECT field1,field2,field3 FROM tableA INNER JOIN (SELECT field1,field2 FROM tableB)
    Thanks in advance!

    Hi,
    fac30d8e-74d3-42aa-b643-e30a3780e00f wrote:
    Dear Sir/Madam
    I'm a student who is interested in Oracle Database and
    I have some problems with JOIN and Sub-query.
    I hope so many of you could help me.
    if i use JOIN without sub-query, may it be faster or not?
    SELECT field1, field2 FROM tableA INNER JOIN tableB
    if i use JOIN with sub-query, may it be faster or not?
    SELECT field1,field2,field3 FROM tableA INNER JOIN (SELECT field1,field2 FROM tableB)
    Thanks in advance!
    As the others have said, the execution plan will give you a better idea about which is faster.
    If you're trying to see how using (or not using) a sub-query affects performance, make the rest of the queries as similar as possible.  For example, include field3 in both queries, or ignore field3 in both queries.
    In this particular case, I guess the optimizer would do the same thing either way, but that's just a guess.  I can't see your execution plans.
    In general, simpler code is faster, and better in other ways, too.  In this case
    tableB
    is simpler than
    (SELECT field1, field2  FROM tableB)
    Why do you want a sub-query in this example?

  • Trying to convert SELECT query to Update query with INNER JOINS

    Assalam O Alaikum!
    I've tried to convert this query of mine but failed.
    I wish to use it for update datasource in data GridView. I'm fetching data with it but converting it to update is not helping giving multiple errors.
    I tried to share the pic but they don't let me do so. Its actually a gridView with check boxes. check the item and update it..
    Here is the query. Please help me with that.
    <pre>
    SELECT [rightsId], [saveRights], [updateRights],
    [viewRights], [deleteRights], [printRights],
    [processRights], [verifyRights], [unProcessRights],
    [unVerifyRights], CONVERT(VARCHAR(100),tblGroup.groupId)as groupId, convert(varchar(100),tblmenu.[menuId])as menuid
    FROM [tblRights] inner join tblMenu ON
    tblMenu.menuId=tblRights.menuId INNER JOIN
    tblGroup ON tblGroup.groupId=tblRights.rightsId
    </pre>

    code is fine the above query works fine with the fetching(select) but when I try to write it with update it doesn't. Here is the asp code. I'm doing nothing with c# or vb.
      <asp:GridView ID="GridView1" runat="server" AllowPaging="True"
                DataSourceID="ratGrid" AutoGenerateColumns="False"
                CssClass="GridViewStyle" Width="100%" AllowSorting="True" AutoGenerateEditButton="True" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2">
                <Columns>
                    <asp:BoundField DataField="rightsId" HeaderText="rightsId" ItemStyle-Width="75px" SortExpression="rightsId" Visible="False">
                    <ItemStyle Width="75px" />
                    </asp:BoundField>
                    <asp:CheckBoxField DataField="saveRights" HeaderText="Save" SortExpression="saveRights" />
                    <asp:CheckBoxField DataField="updateRights" HeaderText="Update" SortExpression="updateRights" />
                    <asp:CheckBoxField DataField="viewRights" HeaderText="View" SortExpression="viewRights" />
                    <asp:CheckBoxField DataField="deleteRights" HeaderText="Delete" SortExpression="deleteRights" />
                    <asp:CheckBoxField DataField="printRights" HeaderText="Print" SortExpression="printRights" />
                    <asp:CheckBoxField DataField="processRights" HeaderText="Process" SortExpression="processRights" />
                    <asp:CheckBoxField DataField="verifyRights" HeaderText="Verify" SortExpression="verifyRights" />
                    <asp:CheckBoxField DataField="unProcessRights" HeaderText="UnProcess" SortExpression="unProcessRights" />
                    <asp:CheckBoxField DataField="unVerifyRights" HeaderText="UnVerify" SortExpression="unVerifyRights" />
                    <asp:BoundField DataField="groupId" HeaderText="groupId" ReadOnly="True" SortExpression="groupId" Visible="False" />
                    <asp:BoundField DataField="menuid" HeaderText="menuid" SortExpression="menuid" ReadOnly="True" Visible="False" />
                </Columns>
                <RowStyle CssClass="RowStyle" BackColor="#FFF7E7" ForeColor="#8C4510" />
                <PagerStyle CssClass="PagerStyle" ForeColor="#8C4510" HorizontalAlign="Center" />
                <SelectedRowStyle CssClass="SelectedRowStyle" BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
                <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
                <HeaderStyle CssClass="HeaderStyle" BackColor="#A55129" Font-Bold="True" ForeColor="White" />
                <AlternatingRowStyle CssClass="AltRowStyle" />
                <SortedAscendingCellStyle BackColor="#FFF1D4" />
                <SortedAscendingHeaderStyle BackColor="#B95C30" />
                <SortedDescendingCellStyle BackColor="#F1E5CE" />
                <SortedDescendingHeaderStyle BackColor="#93451F" />
            </asp:GridView>
            <asp:SqlDataSource ID="ratGrid"
                 runat="server"
                ConnectionString="<%$ ConnectionStrings:Conn_Str %>"
                SelectCommand="SELECT [rightsId], [saveRights], [updateRights],
    [viewRights], [deleteRights], [printRights],
    [processRights], [verifyRights], [unProcessRights],
    [unVerifyRights], CONVERT(VARCHAR(100),tblGroup.groupId)as groupId, convert(varchar(100),tblmenu.[menuId])as menuid
    FROM [tblRights] inner join tblMenu ON
    tblMenu.menuId=tblRights.menuId INNER JOIN
    tblGroup ON tblGroup.groupId=tblRights.rightsId"
               FilterExpression="menuId like '{0}%' and [groupId] like '{1}%'" >
                            <FilterParameters>
                <asp:ControlParameter ControlID="ddlmenu" Name="menu"
                        PropertyName="SelectedValue" Type="String" />
                <asp:ControlParameter ControlID="ddlgroup" Name="Country"
                        PropertyName="SelectedValue" Type="String" />
                </FilterParameters>
            </asp:SqlDataSource>
    Your table needs key(s) and you need to assign the key as DataKeys property for the GridView to make your UpDate and Delete work without coding.

  • Update Query with Inner Joins

    Dear Experts,
    Update Employee set desicode = o.dcod from employee e inner join operator o on
    e.employee_id = o.employe_id
    waiting for suggestions,

    The other thread from yesterday that Satyaki mentioned Update.
    William:
    The SQL Server syntax from the OP is their version of an updateable join view. One interesting quirk of the implementation is that it does not require a unique key in the joined table, and will not error even if there are multiple rows that could update a row in the main table. I am still trying to figure out how it decides which row to use for the update, or if it actually updates multiple times and last update wins.
    John

  • Select Query with Inner Join

    Dear Experts,
    I have writen a inner join code with MKPF and MSEG which taking too much time, while I have used index.
    Indexes are:
    MSEG
    MATNR
    WERKS
    LGORT
    BWART
    SOBKZ
    MKPF
    BUDAT
    MBLNR
    My Select Query is :
      SELECT B~MATNR
                   B~MAT_KDAUF
                   B~MAT_KDPOS
                   B~BWART
                   B~MENGE
                   B~MEINS
                   B~AUFNR
        INTO TABLE IT_MSEG
        FROM MKPF AS A
          INNER JOIN MSEG AS B
             ON AMBLNR EQ BMBLNR
            AND AMJAHR EQ BMJAHR
        WHERE A~BUDAT IN BUDAT
          AND B~MATNR IN MATNR
          AND B~WERKS IN WERKS
          AND B~LGORT IN LGORT
          AND B~BWART IN BWART.

    hi,
    you can use  for all entries  it will work faster then joins
    About it:*
    FOR ALL ENTRIES WHERE
    Syntax
    ... FOR ALL ENTRIES IN itab WHERE ... col operator itab-comp ...
    Effect
    If the addition FOR ALL ENTRIES is specified before the language element WHERE, then the components comp of the internal table itab can be used as operands when comparing with relational operators.
    The internal table itab must have a structured line type and the component comp must be compatible with the column col.
    The logical expression sql_cond of the WHERE condition can comprise various logical expressions by using AND and OR. However, if FOR ALL ENTRIES is specified, there must be at least one Comparison with a column of the internal table itab, which can be specified either statistically or dynamically (Release 6.40 and higher). In a statement with a SELECTstatement with FOR ALL ENTRIES, the addition ORDER BY can only be used with the addition PRIMARY KEY.
    The whole logical expression sql_cond is evaluated for each individual line of the internal table itab. The resulting set of the SELECT statement is the union of the resulting sets from the individual evaluations. Duplicate lines are automatically removed from the resulting set. If the internal table itab is empty, the whole WHERE statement is ignored and all lines in the database are put in the resulting set.
    Notes
    In Release 6.10 and higher, the same internal table can be specified after FOR ALL ENTRIES and after INTO.
    The addition FOR ALL ENTRIES is only possible before WHERE conditions of the SELECT statement.
    Example
    Exporting all flight data for a specified departure city. The relevant airlines and flight numbers are first put in an internal table entry_tab, which is evaluated in the WHERE condition of the subsquent SELECT statement.
    PARAMETERS p_city TYPE spfli-cityfrom.
    TYPES: BEGIN OF entry_tab_type,
             carrid TYPE spfli-carrid,
             connid TYPE spfli-connid,
           END OF entry_tab_type.
    DATA: entry_tab   TYPE TABLE OF entry_tab_type,
          sflight_tab TYPE SORTED TABLE OF sflight
                           WITH UNIQUE KEY carrid connid fldate.
    SELECT carrid connid
           FROM spfli
           INTO CORRESPONDING FIELDS OF TABLE entry_tab
           WHERE cityfrom = p_city.
    SELECT carrid connid fldate
           FROM sflight
           INTO CORRESPONDING FIELDS OF TABLE sflight_tab
           FOR ALL ENTRIES IN entry_tab
           WHERE carrid = entry_tab-carrid AND
                 connid = entry_tab-connid.
    hope it will help you
    Rahul sharma
    Edited by: RAHUL SHARMA on Sep 11, 2008 8:10 AM

  • Update statement with inner join

    Hello everyone. I am am trying to do an update statement with an inner join. I have found several examples of SQL statements that work with Sql server and mysql but they don't work in Oracle. Does anyone know the proper way in Oracle 10G? I am trying to update all fields in one table from fields in another table.
    for example:
    UPDATE table3
    SET
    TL3.name = TL2.name,
    TL3.status = TL2.status,
    TL3.date = TL2.date
    FROM table3 TL3 JOIN table2 TL2
    ON (TL3.unique_id = TL2.unique_id);
    any help will be appreciated.

    Hi,
    You can also use MERGE, like this:
    MERGE INTO  table3     dst
    USING   (
             SELECT  unique_id
             ,         name
             ,         status
             ,         dt          -- DATE is not a good column name
             FROM    table2
         )          src
    ON     (dst.unique_id     = src.unique_id)
    WHEN MATCHED THEN UPDATE
    SET     dst.name     = src.name
    ,     dst.status     = src.status
    ,     dst.dt          = src.dt
    ;Unlike UPDATE, this lets you avoid essentially doing the same sub-query twice: once in the SET clause and then again in the WHERE clause.
    Like UPDATE, you don't acutally join the table being changed (table3 in this case) to the other table(s); that is, the FROM clause of the suib-query does not include table3.
    Riedelme is right; you'll get better response to SQL questions like this in the SQL and PL/SQL forum:
    PL/SQL

  • How to re-write this big SELECT Query with INNER JOINs?

    Hi Experts
    I have a performance killer SELECT query with an inner join of 3 tables u2013 VBAP, VBAK and VBEP together, which populates records to an internal table INT_COLL_ORD. Based on these records selected, in another SELECT query, records are fetched from VBUK table to the internal table INT_VBUK.
    SELECT A~VBELN A~POSNR A~MATNR A~KWMENG A~KBMENG A~ERDAT A~ERZET A~PSTYV D~AUART E~ETTYP E~EDATU
    INTO TABLE INT_TAB_RES
    FROM VBAP AS A INNER JOIN VBAK AS D
    ON D~VBELN EQ A~VBELN AND D~MANDT EQ A~MANDT
    INNER JOIN VBEP AS E
    ON E~VBELN EQ A~VBELN AND E~POSNR EQ A~POSNR AND E~MANDT EQ A~MANDT
    WHERE  A~VBELN IN s_VBELN AND
           D~auart in s_auart AND
           D~vkorg in s_vkorg AND
           D~vbtyp eq 'C'     AND
           ( ( matnr LIKE c_prefix_sp AND zz_msposnr NE 0 AND kbmeng EQ 0 )
           OR ( matnr LIKE c_prefix_fp AND kwmeng NE A~kbmeng ) ) AND
           A~ABGRU EQ SPACE AND
           A~MTVFP IN R_MTVFP AND
           A~PRCTR IN R_PRCT AND
           E~ETENR EQ '1'.
    SORT INT_COLL_ORD BY VBELN POSNR ETTYP.
    DELETE ADJACENT DUPLICATES FROM INT_TAB_RES COMPARING VBELN POSNR.
    CHECK NOT INT_TAB_RES [] IS INITIAL.
    SELECT VBELN UVALL CMGST INTO TABLE INT_VBUK
    FROM VBUK FOR ALL ENTRIES IN INT_TAB_RES
    WHERE VBELN = INT_TAB_RES-VBELN AND UVALL NE 'A'.
    Now, the requirement is:
    I want to split this query. Like, first join VBAK and VBUK first. With this selection, go to the inner join of VBAP and VBEP (on key VBELN) to get the results. How can I re-write this Query?
    Please help.
    Thx n Rgds

    Hi Nagraj
    As of your suggestion, I have re-written the query as below:
    * Declarations
    TYPES: BEGIN OF TYP_COLL_ORD,
            VBELN  LIKE VBAK-VBELN,
            POSNR  LIKE VBUP-POSNR,
            MATNR  LIKE VBAP-MATNR,
            KWMENG LIKE VBAP-KWMENG,
            KBMENG LIKE VBAP-KBMENG,
            ERDAT  LIKE VBAK-ERDAT,
            ERZET  LIKE VBAK-ERZET,
            PSTYV  LIKE VBAP-PSTYV,
            AUART  LIKE VBAK-AUART, u201Calready exists in type
            ETTYP  LIKE VBEP-ETTYP,
            EDATU  LIKE VBEP-EDATU.
    TYPES: END OF TYP_COLL_ORD.
    DATA: INT_COLL_ORD TYPE TABLE OF TYP_COLL_ORD WITH HEADER LINE.
    TYPES: BEGIN OF TYP_VBUK,
            AUART  LIKE VBAK-AUART, u201Chave added this field
            VBELN  LIKE VBUK-VBELN,
            UVALL  LIKE VBUK-UVALL,
            CMGST  LIKE VBUK-CMGST.
    TYPES: END OF TYP_VBUK.
    DATA: INT_VBUK TYPE TABLE OF TYP_VBUK WITH HEADER LINE.
    *QUERY#1 u2013 for VBAK & VBUK Join
    SELECT A~AUART B~VBELN B~UVALL B~CMGST
    INTO TABLE INT_VBUK
    FROM VBAK AS A INNER JOIN VBUK AS B
    ON A~VBELN EQ B~VBELN
    WHERE A~VBELN IN s_VBELN AND
    A~auart in s_auart AND
    A~vkorg in s_vkorg AND
    A~vbtyp eq 'C' AND
    B~UVALL NE 'A'.
    IF NOT INT_VBUK[] IS INITIAL.
    SORT INT_VBUK BY VBELN.
    DELETE ADJACENT DUPLICATES FROM INT_VBUK COMPARING VBELN.
    *QUERY#2 u2013 for VBAP & VBEP Join
    SELECT A~VBELN A~POSNR A~MATNR A~KWMENG A~KBMENG A~ERDAT A~ERZET A~PSTYV B~ETTYP B~EDATU
    INTO TABLE INT_COLL_ORD
    FROM VBAP AS A INNER JOIN VBEP AS B
    ON B~VBELN EQ A~VBELN AND B~POSNR EQ A~POSNR AND B~MANDT EQ A~MANDT
    FOR ALL ENTRIES IN INT_VBUK
    WHERE A~VBELN = INT_VBUK-VBELN AND
    ( ( matnr LIKE c_prefix_sp AND zz_msposnr NE 0 AND kbmeng EQ 0 )
    OR ( matnr LIKE c_prefix_fp AND kwmeng NE A~kbmeng ) ) AND
    A~ABGRU EQ SPACE AND
    A~MTVFP IN R_MTVFP AND
    A~PRCTR IN R_PRCT AND
    B~ETENR EQ '1'.
    ENDIF.
      SORT INT_COLL_ORD BY  VBELN POSNR ETTYP.
      DELETE ADJACENT DUPLICATES FROM INT_COLL_ORD
        COMPARING VBELN POSNR.
      CHECK NOT INT_COLL_ORD[] IS INITIAL.
      LOOP AT INT_COLL_ORD.
        CLEAR: L_MTART,L_ATPPR,L_ETTYP.
        IF L_PREVIOUS_ETTYP NE INT_COLL_ORD-ETTYP OR
          L_PREVIOUS_AUART NE INT_COLL_ORD-AUART.
          READ TABLE INT_OVRCTL WITH KEY AUART = INT_COLL_ORD-AUART ETTYP = INT_COLL_ORD-ETTYP.
          CHECK SY-SUBRC NE 0.
    Now, the issue is:
    Please note that declaration for INT_COLL_ORD has a field AUART, which is used in further parts of program (see the statement just above)
    But, since neither VBAP nor VBEP contains AUART field, it cannot be fetched through the QUERY#2. So this value is not populated into INT_COLL_ORD through SELECT Query.
    Since this field is used in later part of program & that the internal table has no value for this field, it dumps!!
    How to include this value into the INT_COLL_ORD?
    Plz suggest....

  • ORA-00947 Error on straight SELECT with INNER JOINs

    I have a REAL bizarre situation. I have a SQL SELECT Statement that is joining a few tables. I actually have a WHERE clause where I am filtering by a coulmn within one of the joins. However, if I try to SELECT that coulmn, I am getting an Oracle error ORA-00947. I can even SELECT * and get ALL the columns back form ALL the tables I'm joing on, including the one that is not allowing me just to select it.
    Has anyone ever seen anything like this before???
    I appreciate your review and am hopeful for a reply.
    Thanks.
    PSULionRP

    Jez....Not sure if I need to worry about proprietary stuff here...Here's the SQL and the column I'm trying to select is CDM_SUPPLIER_UTILITY.SUPPLIER_CD.
    When I do that is when I get the ORA-00947 error. And our version is...
    Oracle9i Enterprise Edition Release 9.2.0.8.0 - 64bit Production
    SELECT CDM_CALENDAR.CALENDAR_DT,
    CDM_OFFER.SUPPLIER_NAME,
    CDM_SUPPLIER_UTILITY.SUPPLIER_CD,
    ABS(SUM(CDM_MONEY.TRANSACTION_AMT))
    FROM CDEDM.CDM_TRANSACTIONS CDM_TRANSACTIONS
    INNER JOIN CDEDM.CDM_MONEY CDM_MONEY
    ON CDM_MONEY.TRANSACTION_FK = CDM_TRANSACTIONS.TRANSACTION_GK_PK
    INNER JOIN CDEDM.CDM_OFFER CDM_OFFER
    ON CDM_OFFER.OFFER_GK_PK = CDM_MONEY.OFFER_FK
    INNER JOIN CDEDM.CDM_CALENDAR CDM_CALENDAR
    ON CDM_CALENDAR.CALENDAR_DT_PK = CDM_MONEY.TRANSACTION_DT_FK
    INNER JOIN CDEDM.CDM_BILL_ACCOUNTS CDM_BILL_ACCOUNTS
    ON CDM_BILL_ACCOUNTS.BILL_ACCT_GK_PK = CDM_MONEY.BILL_ACCOUNTS_FK
    INNER JOIN CDEDM.CDM_SUPPLIER_UTILITY CDM_SUPPLIER_UTILITY
    ON CDM_SUPPLIER_UTILITY.SUPPLIER_UTILITY_GK_PK = CDM_BILL_ACCOUNTS.SUPPLIER_FK
    WHERE CDM_SUPPLIER_UTILITY.SUPPLIER_CD = 'MC2'
    AND CDM_CALENDAR.CALENDAR_DT BETWEEN NEXT_DAY(trunc(SYSDATE-12),'Saturday')
    AND NEXT_DAY(trunc(SYSDATE-5),'Saturday')
    AND CDM_TRANSACTIONS.TRAN_DECODE IN
    'Debit/Bill Installment Billing',
    'Debit/Bill Electric Service',
    'Debit by Transfer of Payment TO Uncollec',
    'Debit Miscellaneous Electric',
    'Credit for Transfer TO Uncollectible',
    'Credit for Tranfer FROM Uncollectible',
    'Credit Miscellaneous Electric',
    'Credit Alteration',
    'Credit Allowance',
    'Bill Consumption On An Inactive Meter'
    AND CDM_MONEY.TRANSACTION_LEVEL_CD IN
    'A',
    GROUP BY CDM_CALENDAR.CALENDAR_DT,
    CDM_OFFER.SUPPLIER_NAME,
    CDM_SUPPLIER_UTILITY.SUPPLIER_CD

  • Query with INNER joins

    Hi
    How can we optimize instead of inner joins. or any other idea to improve it.
    Thanks in advance!
    Regards,
    LKRao

    What is 'it'?
    Read {message:id=9360002} and {message:id=9360003} , and adjust your post accordingly.
    Without a query, execution plan, database version, index information, etc. etc., I wouldn't know how to be of any help here...perhaps other volunteers have a crystal ball, but I forgot mine accidentally this morning...

  • Need help with inner join and distinct rows

    Hey Guys,
    i have
    1) BaseEnv Table 
    2) Link Table
    3) BaseData Table
    Link table has three columns Id,BaseEnvId,BaseDataId 
    the BaseEnvID is unique in the table where as BaseDataId can be repeated i.e multile rows of BaseEnv Table can point to same BaseData  table row
    Now i want to do  BaseEnvTable inner join Link Table inner join BaseData Table and select 5 columsn ; Name,SyncName,Version,PPO,DOM  from the BaseData table.. the problem is that after i do the inner join I get duplciate records..
    i want to eliminate the duplicate records , can any one help me here

    Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data should
    use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect. 
    This is minimal polite behavior on SQL forums. Now we have to guess and type, guess and type, etc. because of your bad manners. 
    CREATE TABLE Base_Env
    (base_env_id CHAR(10) NOT NULL PRIMARY KEY,
    Think about the name Base_Data; do you have lots of tables without data? Silly, unh? 
    CREATE TABLE Base_Data
    (base_data_id CHAR(10) NOT NULL PRIMARY KEY,
    Your Links table is wrong in concept and implementation. The term “link” refers to a pointer chain structure used in network databases and makes no sense in RDBMS. There is no generic, magic, universal “id” in RDBMS! People that do this are called “id-iots”
    in SQL slang. 
    We can model a particular relationship in a table by referencing the keys in other tables. But we need to know if the relationship is 1:1, 1:m, or n:m. This is the membership of the relationship. Your narrative implies this: 
    CREATE TABLE Links
    (base_env_id CHAR(10) NOT NULL UNIQUE
       REFERENCES Base_Env (base_env_id),
     base_data_id CHAR(10) NOT NULL
       REFERENCES Base_Data (base_data_id));
    >> The base_env_id is unique in the table where as base_data_id can be repeated I.e multiple rows of Base_Env Table can point [sic] to same Base_Data table row. <<
    Again, RDBMS has no pointers! We have referenced an referencing tables. This is a fundamental concept. 
    That narrative you posted has no ON clauses! And the narrative is also wrong. There is no generic “name”, etc. What tables were used in your non-query? Replace the ?? in this skeleton: 
    SELECT ??.something_name, ??.sync_name, ??.something_version, 
           ??.ppo, ??.dom
    FROM Base_Env AS E, Links AS L, Base_Data AS D
    WHERE ?????????;
    >> I want to eliminate the duplicate records [sic], can any one help me here?<<
    Where is the sample data? Where is the results? Please read a book on RDBMS so you can post correct SQL and try again. 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Rewrite the query with out joins and group by

    Hi,
    This was an interview question.
    Table Names: bookshelf_checkout
    bookshelf
    And the join condition between these two tables is title
    We need to rewrite below query without using join condition and group by clause ?
    SELECT b.title,max(bc.returned_date - bc.checkout_date) "Most Days Out"
               FROM bookshelf_checkout bc,bookshelf b
               WHERE bc.title(+)=b.title
               GROUP BY b.title;When I was in college, I read that most of the SELECT statements can be replaced by basic SQL operations (SET OPERATORS). Now I am trying to rewrite the query with SET operators but not able to get the exact result.
    Kindly help me on this.
    Thanks,
    Suri

    Something like this?
      1  WITH books AS (
      2  SELECT 'title 1' title FROM dual UNION ALL
      3  SELECT 'title 2' FROM dual UNION ALL
      4  SELECT 'title 3' FROM dual ),
      5  bookshelf AS (
      6  SELECT 'title 1' title, DATE '2012-05-01' checkout_date, DATE '2012-05-15' returned_date FROM dual UNION ALL
      7  SELECT 'title 1' title, DATE '2012-05-16' checkout_date, DATE '2012-05-20' returned_date FROM dual UNION ALL
      8  SELECT 'title 2' title, DATE '2012-04-01' checkout_date, DATE '2012-05-15' returned_date FROM dual )
      9  SELECT bs.title, MAX(bs.returned_date - bs.checkout_date) OVER (PARTITION BY title) FROM bookshelf bs
    10  UNION
    11  (SELECT b.title, NULL FROM books b
    12  MINUS
    13* SELECT bs.title, NULL FROM bookshelf bs)
    SQL> /
    TITLE   MAX(BS.RETURNED_DATE-BS.CHECKOUT_DATE)OVER(PARTITIONBYTITLE)
    title 1                                                           14
    title 2                                                           44
    title 3Lukasz

  • Case with select into and sub query

    hi im trying to use case and select with sebqueries, but my beginer like understanding of syntax fails me. can someone point out what im doing wrong in the case select below. im using select into, as i ultimatly need to load a ref cursor for use with crystal reports.
    thanks
    james
    ps if anyone is london based, and would like to spend a day or two teaching me how to be a bit better at PL/SQL (can aford to pay a little bit) please get in touch!!
    SELECT
    Case (select kind_code from event where                    
    event.event_id = event.container_event_id)     
    when 1094006
    then          promo_name     
    end
    into      result
    FROM promo,     promo_plan ,     event_promotion
    WHERE      promo.promo_id = promo_plan.promo_id
    AND     promo_plan.promo_plan_id = event_promotion.promo_plan_id
    AND     event_promotion.detail_id = '33532282'
    when blah then 'blah';

    Hello
    AH i see what you are driveing at, yes i am just using case slect to determin which >routine to run, as the name is stored in a diferent location depending on the event kind >code. are are you saying i need multiple selects within the case statment? one for each >type of kind code?Well it depends really. If the select
    select kind_code from event where
    event.event_id = event.container_event_idIs going to return more than one row for any given run, you're going to need to take a bit of a different approach. Is it the case that this query will return more than one row which would mean that you want value X and value Y for each row?
    Using the test data and everything from before:
    SQL> CREATE OR REPLACE PROCEDURE p_GetStuff(ac_Result   OUT sys_refcursor)
      2  IS
      3
      4  BEGIN
      5     /*
      6             This uses a cartesian product i.e. repeat every row in
      7             dt_test_data against every row in dt_test_event
      8     */
      9     OPEN Ac_Result FOR
    10     SELECT
    11             CASE dt_test_event.kind_code
    12             WHEN 1 THEN
    13                     dt_test_data.object_name
    14             WHEN 2 THEN
    15                     dt_test_data.object_type
    16             END
    17     FROM
    18             dt_test_data,
    19             dt_test_event;
    20
    21  END;
    22  /
    Procedure created.
    SQL> var x refcursor
    SQL> exec p_getstuff(:x)
    PL/SQL procedure successfully completed.
    SQL> print x
    CASEDT_TEST_EVENT.KIND_CODEWHEN1THENDT_TEST_DATA.OBJECT_NAMEWHEN2THENDT_TEST_DAT
    ABC
    ABC4
    AD1
    AD2
    ADHOC_CONTACT_LOG
    AK_CD_CLAIM_VALIDATION_SOURCE
    AK_CD_CLAIM_VALIDATION_TYPE
    AK_CLAIM_ACTION_ROWSOURCE
    APPROVAL_LIST_MEM_IE
    APPROVE_GRP_HIST_IE
    10 rows selected.
    SQL> insert into dt_test_event values(2);
    1 row created.
    SQL> exec p_getstuff(:x)
    PL/SQL procedure successfully completed.
    SQL> print x
    CASEDT_TEST_EVENT.KIND_CODEWHEN1THENDT_TEST_DATA.OBJECT_NAMEWHEN2THENDT_TEST_DAT
    ABC
    ABC4
    AD1
    AD2
    ADHOC_CONTACT_LOG
    AK_CD_CLAIM_VALIDATION_SOURCE
    AK_CD_CLAIM_VALIDATION_TYPE
    AK_CLAIM_ACTION_ROWSOURCE
    APPROVAL_LIST_MEM_IE
    APPROVE_GRP_HIST_IE
    TABLE
    CASEDT_TEST_EVENT.KIND_CODEWHEN1THENDT_TEST_DATA.OBJECT_NAMEWHEN2THENDT_TEST_DAT
    TABLE
    TABLE
    TABLE
    TABLE
    INDEX
    INDEX
    INDEX
    INDEX
    INDEX
    20 rows selected.Or an alternative to that would be, if you have a fixed number of event ids and they relate to a fixed number of attributes you could use something like:
    CREATE OR REPLACE PROCEDURE p_GetStuff3(ac_Result     OUT sys_refcursor)
    IS
    BEGIN
              The SUBSTR
              is just there to make sure the data fit on screen, my SQL*Plus
              is a bit weird!
         OPEN Ac_Result FOR
         SELECT
              SUBSTR(MAX(DECODE(dt_test_event.kind_code,1,dt_test_data.object_name,NULL)),1,30) attribute_1,
              SUBSTR(MAX(DECODE(dt_test_event.kind_code,2,dt_test_data.object_type,NULL)),1,30) attribute_2
         FROM
              dt_test_data,
              dt_test_event
         GROUP BY
              object_name;
    END;
    SQL> delete from dt_test_event where kind_code=2;
    1 row deleted.
    SQL> exec p_getstuff3(:x)
    PL/SQL procedure successfully completed.
    SQL> print x
    ATTRIBUTE_1                    ATTRIBUTE_2
    ABC
    ABC4
    AD1
    AD2
    ADHOC_CONTACT_LOG
    AK_CD_CLAIM_VALIDATION_SOURCE
    AK_CD_CLAIM_VALIDATION_TYPE
    AK_CLAIM_ACTION_ROWSOURCE
    APPROVAL_LIST_MEM_IE
    APPROVE_GRP_HIST_IE
    10 rows selected.
    SQL> insert into dt_test_event values(2);
    1 row created.
    SQL> exec p_getstuff3(:x)
    PL/SQL procedure successfully completed.
    SQL> print x
    ATTRIBUTE_1                    ATTRIBUTE_2
    ABC                            TABLE
    ABC4                           TABLE
    AD1                            TABLE
    AD2                            TABLE
    ADHOC_CONTACT_LOG              TABLE
    AK_CD_CLAIM_VALIDATION_SOURCE  INDEX
    AK_CD_CLAIM_VALIDATION_TYPE    INDEX
    AK_CLAIM_ACTION_ROWSOURCE      INDEX
    APPROVAL_LIST_MEM_IE           INDEX
    APPROVE_GRP_HIST_IE            INDEX
    10 rows selected.Message was edited by:
    david_tyler
    Oops, copy + pasted the wrong comments for the 2nd proc.

  • Why can't i use "INNER JOIN" in a query for SQL Server with JDBC??????

    Hi,
    I'm trying to execute some SQL queries and I just don't understand what's wrong.
    I�m using Tomcat and SQL Server in order to do this, but when I�m try to execute a query with a INNER JOIN statements Tomcat raise a SQL exception... at the very first time I thought there was a problem with database connection but I realize that a simple query to a table works pretty well. then I found out some problems with JDBC:ODBC.... so I install JDBC for SQL Server 2000 and test with the same simple query and works..... so, I come to a conclusion.... INNER JOIN or JOIN statements can't be used in JDBC..... please... somebody tell I�m wrong and give me a hand...
    I'm using TOMCAT 4 and JDK 1.4 SQL Server 2000
    Error occurs when executeQuery() is called.... not prepareStatement().... ??????
    Driver DriverRecResult = (Driver)Class.forName(driver).newInstance();
    Connection ConnRecResult = DriverManager.getConnection(DSN,user,password);
    PreparedStatement StatementRecResult = ConnRecResult.prepareStatement(query);
    ResultSet RecResult = StatementRecResult.executeQuery(); <---- Exception raise here
    So much tahnks in advance,

    That's exactly what I think, driver it's raising the exception, but I don't know why.... i test the same query with INNER JOIN directly from SQL Query Analyser and it's works perfectly, my problem ain't SQL, but JSP and JDBC 'cause i'm a newbie about these issues.
    Common sense tell me possible problems lie in SQLServer drivers 'cause i run the same pages on JRUN through jdbc:odbc and do works well, but by now i just depend on Tomcat.....
    I've installed SQL Server drivers for JDBC but i just find it doesn't work fully... could be the version of JDK i've installed? what version do i need?
    ( I'm running Tomcat 4 with JDK 1.4 & SQL Server 2000 W2K )
    thanks for reply.

Maybe you are looking for