Nested select statements.

Hi, I am writing a piece of code in which i use nested select statements for 4 tables to retrieve one column's data (ie: POSNR). But when i execute it, it takes way too long to get the data. I'm quite new to ABAP so very in need of your help. Thanks
REPORT  z_impos_test.
TABLES: coss,       "CO Object: Cost Totals for Internal Postings
        afvc,       "Operation within an order
        prps,       "WBS (Work Breakdown Structure) Element Master Data
        imzo.       "Table: CO Object - Capital Investment Prog.Pos.
TYPES: BEGIN OF st_impos,
  objnr       TYPE coss-objnr,
  gjahr       TYPE coss-gjahr,
  kstar       type coss-kstar,
  projn       type afvc-projn,
  pspnr       type prps-pspnr,
  posnr       type imzo-posnr,
END OF st_impos.
data: year TYPE coss-gjahr value '2007'.
DATA: t_output  TYPE STANDARD TABLE OF st_impos WITH HEADER LINE,
      st_output TYPE st_impos,
      t_output2 TYPE STANDARD TABLE OF st_impos WITH HEADER LINE,
      st_output2 TYPE st_impos.
SELECT objnr gjahr kstar FROM coss
INTO CORRESPONDING FIELDS OF st_output
WHERE ( objnr LIKE 'NV%' OR
      objnr LIKE 'PR%' ) AND
       gjahr = year.
   SELECT SINGLE projn from afvc into CORRESPONDING FIELDS OF st_output
       WHERE objnr = st_output-objnr.
APPEND st_output to t_output.
ENDSELECT.
SORT t_output BY objnr.
DELETE ADJACENT DUPLICATES FROM t_output.
LOOP AT t_output into st_output.
SELECT objnr pspnr
       INTO CORRESPONDING FIELDS OF st_output2
       FROM prps
       WHERE objnr = st_output-objnr
       AND   pspnr = st_output-pspnr.
  SELECT SINGLE posnr from imzo into CORRESPONDING FIELDS OF st_output2
       WHERE objnr = st_output2-objnr.
APPEND st_output2 to t_output2.
ENDSELECT.
ENDLOOP.
LOOP AT t_output2 to st_output2.
WRITE:   st_output2-posnr.
ENDLOOP.
Edited by: Jacie Johns on Apr 23, 2009 11:26 PM

HI John,
Try to avoid INTO CORRESPONDING FIELDS in SELECT statement.
As you are not using PSPNR and POSNR fields in the first SELECT statement. If you remove these fields, in structure, INTO CORRESPONDING FIELDS can be avoided. Create a separate structure with the fields that are required for T_OUTPUT table (i.e. create another structure with only first 4 fields, as T_OUTPUT1.
And as mentioned in your code,
  WHERE objnr = st_output-objnr
       AND   pspnr = st_output-pspnr
in select statement, ST_OUTPUT-PSPNR value is not fetched in the previous select statements.
Create Another structure with fields OBJNR, PSPNR, POSNR for table T_OUTPUT2 to store the data from tables, PRPS and IMZO.
Use JOINS and FOR ALL ENTRIES to fetch the desired data.
The sample code is as follows:
===
TYPES: BEGIN OF ty_output1,
  objnr       TYPE coss-objnr,
  gjahr       TYPE coss-gjahr,
  kstar       type coss-kstar,
  projn       type afvc-projn,
END OF ty_output1,
BEGIN OF ty_output2,
  objnr       TYPE coss-objnr,
  pspnr       type prps-pspnr,
  posnr       type imzo-posnr,
END OF ty_output2,
BEGIN OF ty_output3,
  objnr       TYPE coss-objnr,
  gjahr       TYPE coss-gjahr,
  kstar       type coss-kstar,
  projn       type afvc-projn,
  pspnr       type prps-pspnr,
  posnr       type imzo-posnr,
END OF ty_output3.
data: year TYPE coss-gjahr value '2007'.
DATA:
       wa_output1 TYPE ty_output1,   
       wa_output2 TYPE ty_output2,
       wa_output3 TYPE ty_output3,
       t_output1  TYPE STANDARD TABLE OF ty_output1 ,
       t_output2 TYPE STANDARD TABLE OF ty_output2 ,
       t_output3 TYPE STANDARD TABLE OF ty_output3..
SELECT cobjnr cgjahr ckstar aprojn FROM coss as c
     INNER JOIN afvc as A on aobjnr = cobjnr
  INTO table t_output1
  WHERE ( c~objnr like 'NV%'   or
          c~objnr like 'PR%' ) and
        c~gjahr = year.
SELECT pobjnr ppspnr i~posnr FROM prps as P
     INNER JOIN imzo AS I on pobjnr = iobjnr
     INTO TABLE t_output2
     for all entries in table T_OUTPUT1
     WHERE      p~objnr = t_output1-objnr.
SORT : t_output1 BY objnr,
            t_output2 BY objnr.
DELETE ADJACENT DUPLICATES FROM : t_output1 COMPARING objnr,
                                                                 t_output2 COMPARING objnr.
LOOP AT t_output1 INTO wa_output1
READ TABLE t_output2 INTO wa_output2 WITH KEY objnr - wa_output1-objnr BINARY SEARCH.
if sy-subrc = 0.
  MOVE <wa_output1 fiels> and <wa_output2 fields> to WA_OUTPUT3.
  append wa_output3 to T_OUTPUT3.
endif.
ENDLOOP.
Hope this will solve your problem.
Regards,
Sai Prasad

Similar Messages

  • Is it possible to nest SELECT statements?

    Greetings community,
    Another newbie’s question it is. Looking tutorials and some posts here I’ve been advised not to pull entire table through the local network, and torture client machines’ processors and memory. It’s been said that better solution is to
    pull just one part of the table.
    So, imagine this: you want to make a part of your app that would allow your user to view list of orders. So you put one data grid view on the form, pull last 20 headers from the table into it and leave to user to choose one to be opened
    in another form. If user doesn’t find header they want, they press page up for example and previous 20 headers are loaded into data grid view. Of course, user could filter headers list by customer, or by distribution lane (having all customers residing in
    one part of the town), or whatever more, but let’s not complicate things at this moment, because I’m practically in the beginning.
    I’m trying to make a stored procedure that would load penultimate 20 headers when user presses page up. So, not knowing any better, I created table variable that has the same structure as Orders table with one difference: OrderID column,
    which is identity (auto incremented) in Orders table, here is simply defined as bigint not null. Community member Visakh16 warned me few months ago it’s the bad practice to put self-incrementing columns in table variables.
    At this moment there’s a query on my screen, which waits to become store procedure. After boring part with table variable definition, it goes like this:
    INSERT INTO @OrdersTemp SELECT TOP 40 * FROM dbo.Orders ORDER BY OrderID DESC
    SELECT TOP 20 * FROM @OrdersTemp ORDER BY OrderID ASC
    To put that simply, I pull last 40 headers into table variable, and then pull first 20 from there. This thing works, and I just have to replace 40 with parameter, for every page up or down.
    Now I have few questions.
    -Is there some better way (considering performance) to achieve that? Here is the place where I wanted to ask the question from the title of the post. I don’t know much about T-SQL, and I’m not sure about the proper syntax to nest SELECT
    statements, if something like that is even possible
    -Is there any better way (some built-in function) to find about the count of the rows in one table than
    SELECT COUNT(OrdersID) FROM dbo.Orders
    Thanks for any suggestions.

    Hi Erland,
    Sorry for the very late reply, but I said that I would start another thread when I find more free time to dedicate it to this, so I didn’t really expected you to reply anymore. I didn’t really check here for more than a week, and I glanced
    at mail accidentally.
    As for the negative result I got, its measurement unit is microsecond, so it doesn’t go out of margins you had experienced.
    As for the number of cores, you got me surprised there. I use express edition of SQL server. Last time I checked was SQL server 2012 express, and in specifications it said that express edition is limited to 1 processor core, 1GB of RAM
    and creates up to 10GB database file. I don’t believe they changed any of those specifications. It was generous enough when they doubled size of DB file few editions ago. Still, it appears that “one processor core for express edition” statement has some gray
    areas in it.
    However, at this moment I’m just learning, and I just wanted some way to test how efficient my queries are. I don’t have a real biz problem to solve. I don’t expect that any real performance problem should rise in years of everyday work
    of populating database. What I expect is performance impact when it comes to creating reports, but after all, I don’t think that my boss would create reports by himself. I believe that creating reports would be my task, and I will be doing it after hours,
    being the only user at the moment. Or maybe I could make de-normalized copy of database that would be populated after hours to make it possible for my boss to get his reports faster by himself, as I’ve heard that was the way of making BI in older non-express
    editions.
    So, I do suggest that we finally close this thread for sake of other readers. I’ll start another one with this subject when I find the time to do it.
    Again, thanks for being with me along this journey.

  • Prompting for user input in nested select statements

    I recently rewrote a query to use a nested select statement instead of specifying every SELECT field on the GROUP BY line.  Here's the query which works perfectly with hard-coded values of '030', '01/01/11', and '12/31/11'.
    SELECT T0.[CardName] AS Customer, T0.[CardCode] as 'Cust ID', T0.[Phone1] as Phone, T0.[CntctPrsn] as 'Contact Person', T0.[Address], T0.[City], T0.[State1] as State, T0.[ZipCode] as 'Zip Code', T0.[Country],  T1.[TotalSales]
    FROM OCRD T0 
    INNER JOIN
       (SELECT I.[CardCode] AS CardCode, SUM(I.[DocTotal]) AS TotalSales
        FROM OINV I
        WHERE left (I.[CardCode], 3) = '030' AND (I.[DocDate] >= '01/01/11' AND I.[DocDate] <= '12/31/11')
        GROUP BY I.[CardCode]) T1
    ON T0.[CardCode] = T1.[CardCode]
    ORDER BY T0.[CardName]
    When I try to prompt for the left 3 characters of the CardCode (or the dates), ie.
        WHERE left (I.[CardCode], 3) = [%0] AND (I.[DocDate] >= '01/01/11' AND I.[DocDate] <= '12/31/11')
    I get an error "Column 'OCRD.CardName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause".
    It's like putting a user variable in the inner SELECT made it part of the outer SELECT which is exactly what I was trying to avoid by re-writing this query with the inner SELECT.
    Can anyone explain what SQL Server is doing here and how to fix it?

    Thanks Gordon.  That's how I originally wrote the query and it works fine.  But I was disturbed that I had to GROUP BY every field in my SELECT statement when I really only wanted to group by CardCode.  So I did some research and came up with this where the inner select still groups by only CardCode and still takes user input.  I don't really understand why you need the commented SELECT statements in the SET lines, but you do.  Something about using real table fields for variables.
    DECLARE @startDate datetime
    DECLARE @endDate datetime
    DECLARE @rep varchar(10)
    SET @rep /* SELECT T0.[CardCode] FROM ORDR T0 WHERE T0.[CardCode] */ = '[%0]'
    SET @startDate /* SELECT T0.[DocDate] FROM OINV T0 WHERE T0.[DocDate] */ = '[%1]'
    SET @endDate /* SELECT T0.[DocDate] FROM OINV T0 WHERE T0.[DocDate] */ = '[%2]'
    SELECT T0.[CardName] AS Customer, T0.[CardCode] as 'Cust ID', T0.[Phone1] as Phone, T0.[CntctPrsn] as 'Contact Person', T0.[Address], T0.[City], T0.[State1] as State, T0.[ZipCode] as 'Zip Code', T0.[Country],  T1.[TotalSales]
    FROM OCRD T0 
    INNER JOIN
       (SELECT I.[CardCode] AS CardCode, SUM(I.[DocTotal]) AS TotalSales
        FROM OINV I
        WHERE left (I.[CardCode], 3) = @rep AND (I.[DocDate] >= @startDate AND I.[DocDate] <= @endDate)
        GROUP BY I.[CardCode]) T1
    ON T0.[CardCode] = T1.[CardCode]
    ORDER BY T0.[CardName]
    FOR BROWSE

  • How to avoid the below nested select statement

    Please any one help me how this select statemet is working and      how to avoid the nesetd select statement .
    if we avoid below nested , does it improve performace ?
    select field1 field2                                  
               into table w_feeds                                 
               from ZTable as t                         
               where field2 in r_feedf1                       
               and  POSITION_POSTDT =                           
               ( SELECT MAX( position_postdt ) FROM zTable 
                      where position_postdt le r_pdate-high    
                      and   field1 = t~field1 ).
    Thanks in Advace.

    Hi,
    Instead of nested query go for two separate queries. I see you are querying on the same table...so better go by this approach
    select field1 field2 POSITION_POSTDT
    into table w_feeds
    from ZTable
    where field2 in r_feedf1.
    Remove the where condition on POSITION_POSTDT
    Sort the table w_feeds by POSITION_POSTDT  Descending; So you will get data pertaining to Max Position_Postdt.
    Finally delete the other entries which are not Max.
    This will enhance the performance over the nested query.
    Regards
    Shiva
    Edited by: Shiva Kumar Tirumalasetty on Apr 27, 2010 7:00 PM
    Edited by: Shiva Kumar Tirumalasetty on Apr 27, 2010 7:00 PM

  • Alias of a table is not recognized in the nested select statement

    Hi,
    I have to migrate a query in DB2 to Oracle. The query in DB2 uses Fetch First Row, this is being replaced by Rownum as follow.
    DB2 Query
    SELECT S.ID AS ID, (SELECT VALUE_N FROM ARCHIVE.PACKAGE_PARAMETERS WHERE PACKAGE_ID = S.ID AND ROWNUM < 2) AS HUB_UNIT_ID FROM ARCHIVE.SHIPMENTS S WHERE S.ARCHIVE_ID < 900
    This is working fine
    Oracle Query
    SELECT S.ID AS ID, ( SELECT VALUE_N FROM (SELECT VALUE_N FROM ARCHIVE.PACKAGE_PARAMETERS WHERE PACKAGE_ID = S.ID ) tempTable where ROWNUM < 2) AS HUB_UNIT_ID FROM ARCHIVE.SHIPMENTS S WHERE S.ARCHIVE_ID < 900
    This is throwing error
    Error: ORA-00904: "S"."ID": invalid identifier
    Table Script
    CREATE TABLE "ARCHIVE"."PACKAGE_PARAMETERS" (
    "ID" NUMBER(19,0) NOT NULL ,
    "PACKAGE_ID" NUMBER(19,0) ,
    "DESCRIPTION" VARCHAR(128) ,
    "VALUE_N" VARCHAR(128) ,
    "NOTES" VARCHAR(512) )
    CREATE TABLE "ARCHIVE"."SHIPMENTS" (
    "ID" NUMBER(19,0) NOT NULL ,
    "CREATED" DATE DEFAULT SYSDATE NOT NULL ,
    "CI_INSURANCE_CHARGE" FLOAT DEFAULT 0 NOT NULL ,
    "ARCHIVE_ID" NUMBER(19,0) ,
    Please suggest me some alternative.
    Let me know if you need more information.
    Regards,
    Anil Sinha

    SELECT S.ID AS ID, ( SELECT VALUE_N FROM (SELECT VALUE_N FROM >>ARCHIVE.PACKAGE_PARAMETERS WHERE PACKAGE_ID = S.ID ) >>tempTable where ROWNUM < 2) AS HUB_UNIT_ID FROM >>ARCHIVE.SHIPMENTS S WHERE S.ARCHIVE_ID < 900
    This is throwing error
    Error: ORA-00904: "S"."ID": invalid identifierBecause S.ID is out of scope of correlated subquery. See:
    http://download-uk.oracle.com/docs/cd/B10501_01/server.920/a96540/queries8.htm#2054088
    Has to be formally:
    SELECT S.ID AS ID,
    (SELECT VALUE_N FROM ARCHIVE.PACKAGE_PARAMETERS WHERE PACKAGE_ID = S.ID AND ROWNUM < 2) AS HUB_UNIT_ID
    FROM ARCHIVE.SHIPMENTS S WHERE S.ARCHIVE_ID < 900
    But to be honest it's doubtful logic to use arbitrary row from multi-row subquery as the source for column value...
    Rgds.

  • ABAP Select statement performance (with nested NOT IN selects)

    Hi Folks,
    I'm working on the ST module and am working with the document flow table VBFA. The query takes a large amount of time, and is timing out in production. I am hoping that someone would be able to give me a few tips to make this run faster. In our test environment, this query take 12+ minutes to process.
        SELECT vbfa~vbeln
               vbfa~vbelv
               Sub~vbelv
               Material~matnr
               Material~zzactshpdt
               Material~werks
               Customer~name1
               Customer~sortl
          FROM vbfa JOIN vbrk AS Parent ON ( Parentvbeln = vbfavbeln )
                 JOIN vbfa AS Sub ON ( Subvbeln = vbfavbeln )
                 JOIN vbap AS Material ON ( Materialvbeln = Subvbelv )
                 JOIN vbak AS Header ON ( Headervbeln = Subvbelv )
                 JOIN vbpa AS Partner ON ( Partnervbeln = Subvbelv )
                 JOIN kna1 AS Customer ON ( Customerkunnr = Partnerkunnr )
          INTO (WA_Transfers-vbeln,
                WA_Transfers-vbelv,
                WA_Transfers-order,
                WA_Transfers-MATNR,
                WA_Transfers-sdate,
                WA_Transfers-sfwerks,
                WA_Transfers-name1,
                WA_Transfers-stwerks)
          WHERE vbfa~vbtyp_n = 'M'       "Invoice
          AND vbfa~fktyp = 'L'           "Delivery Related Billing Doc
          AND vbfa~vbtyp_v = 'J'         "Delivery Doc
          AND vbfa~vbelv IN S_VBELV
          AND Sub~vbtyp_n = 'M'          "Invoice Document Type
          AND Sub~vbtyp_v = 'C'          "Order Document Type
          AND Partner~parvw = 'WE'       "Ship To Party(actual desc. is SH)
          AND Material~zzactshpdt IN S_SDATE
          AND ( Parentfkart = 'ZTRA' OR Parentfkart = 'ZTER' )
          AND vbfa~vbelv NOT IN
             ( SELECT subvbfa~vbelv
               FROM vbfa AS subvbfa
               WHERE subvbfavbelv = vbfavbelv
               AND   subvbfa~vbtyp_n = 'V' )           "Purchase Order
          AND vbfa~vbelv NOT IN
             ( SELECT DelList~vbeln
               FROM vbfa AS DelList
               WHERE DelListvbeln = vbfavbelv
               AND   DelList~vbtyp_v = 'C'             "Order Document Type
               AND   DelList~vbelv IN                  "Delivery Doc
                  ( SELECT OrderList~vbelv
                    FROM vbfa AS OrderList
                    WHERE OrderList~vbtyp_n = 'H' )    "Return Ord
          APPEND WA_Transfers TO ITAB_Transfers.
        ENDSELECT.
    Cheers,
    Chris

    I am sending u some of the performance isuues that are to be kept in mind while coding.
    1.Donot use Select *...... instead use Select <required list>......
    2.Donot fetch data from CLUSTER tables.
    3.Donot use Nested Select statements as. U have used nested select which reduces performance to a greater extent.
      Instead  use  views/join .
    Also keep in mind that not use join condition for more for more than three tables unless otherwise required.
    So split select statements into three or four and use Select ......for all entries....
    4.Extract  the data from the database  atonce consolidated upfront into table.
      i.e. use INTO TABLE <ITAB> clause instead of using
    Select----
    End Select.
    5.Never use order by clause in Select ..... statement. instead use SORT<itab>.
    6.When  ever u need to calculate max,min,avg,sum,count use AGGREGATE FUNCTIONS and GROUP BY clause insted of calculating by userself..
    7.Donot use the same table once for Validation and another time for data extraction.select data  only once.
    8.When the intention is for validation use Select single ....../Select.......up to one rows ......statements.
    9.If possible always use array operations to update the database tables.
    10.Order of the fields in the where clause select statement  must be in the same order in the index of table.
    11.Never release the object unless throughly checked by st05/se30/slin.
    12.Avoid using identical select statements.

  • LEFT(MVKE~PRODH,5) IN SELECT STATEMENT

    Hello ABAP-ers!
    In my SELECT STATEMENT i must JOIN table MVKE (MVKEPRODH - material hierarchy), with custom table where i have 1st level of hierarchy (ZTABLEHIER1). These two fields have sort of similar data - PRODH is second level of hierarchy for material, while HIER1 field has 1st level of hierarchy, so i have to trim down PRODH field to first 5 chars in my SELECT statement.
    Example:
    MVKE~PRODH = 0010000001
    ZTABLE~HIER1= 00100
    So, i need to take only first 5 characters from PRODH field and compare it with ZTABLE~HIER1 field.
    I thought to use ...JOIN ZTABLE ON left(mvkeprodh, 5) = ztablehier1 but i knew it wouldn't work, and as i don't know of any way to do it so i must ask here.
    Do you have any suggestion on how to do this?
    Thanks,
    Mihailo

    Hi Clemens,
    thank you for your reply, i just have one more question.
    How do i use this in a where clause?
    - field in my ZTABLE - HIJE1 = '00100%' - I use % in the end because that's where i need a wildcard in LIKE clause
    - filed PRODH = '0010000001'  second level material hierarchy
    Ok, i've used it and seems like i'm near the solution... the problem is like on the pic:
    http://s7.postimage.org/mqj2kq5qj/a1234.jpg
    I have the '00100%' in ZHIJERARHIJA but it doesn't let me use it in LIKE clause it asks for v_zhijerarhija (i'm inserting that value in).
    Please help!
    Ok, I solved it with nested select statements between which i used left(prodh,5) which gave me the first level of hierarchy.
    Thanks.
    Edited by: mihailosundic on Feb 18, 2012 10:52 PM

  • Select statement (new to ABAP)

    Hi, I just get to know ABAP and have been studying about it. I'm practising an exercise in which i use select statement to retrieve data from many tables with the same field. The tables i use are COSS, AFVC, PRPS and IMZO with the same field OBJNR. The data i need to retrieve is POSNR from table IMZO. This is the code that i've just written. Howvever, when i execute it, it said 'Unable to interpret t_imobj-posnr'. I think the code is not right somehow. Very appreciate any guides.
    REPORT  Z_IMPOS_TEST.
    TABLES: coss,       "CO Object: Cost Totals for Internal Postings
            afvc,       "Operation within an order
            prps,       "WBS (Work Breakdown Structure) Element Master Data
            imzo.       "Table: CO Object - Capital Investment Prog.Pos.
    TYPES: BEGIN OF st_impos,
      objnr       TYPE coss-objnr,
      gjahr       TYPE coss-gjahr,
      pspnr       TYPE prps-pspnr,
      posnr       TYPE imzo-posnr,
    END OF st_impos.
    DATA : st_imobj    TYPE st_impos,
           t_imobj     TYPE STANDARD TABLE OF st_impos.
    *PARAMETERS: p_year TYPE coss-gjahr OBLIGATORY.
    SELECT objnr gjahr
          INTO CORRESPONDING FIELDS OF st_imobj
          FROM  coss
          WHERE objnr = st_imobj-objnr
          AND  gjahr = '2007'.
       SELECT objnr
          INTO st_imobj-objnr
          FROM afvc
          WHERE projn = st_imobj-pspnr.
             SELECT objnr
             INTO st_imobj-objnr
             FROM imzo
             WHERE posnr = st_imobj-posnr.
             st_imobj-posnr = st_imobj-posnr.
             st_imobj-gjahr = '2007'.
             APPEND st_imobj TO t_imobj.
             ENDSELECT.
        ENDSELECT.
      ENDSELECT.
      WRITE: 'InvProgPosition is : '  t_imobj-posnr.

    thank you everyone. I fixed most of the lines in the code. The syntac is correct now, but since i used nested select statements, it takes like FOREVER to give the output when i execute it!. Are there any other ways to make the code more effecient?
    REPORT  z_impos_test.
    TABLES: coss,       "CO Object: Cost Totals for Internal Postings
            afvc,       "Operation within an order
            prps,       "WBS (Work Breakdown Structure) Element Master Data
            imzo.       "Table: CO Object - Capital Investment Prog.Pos.
    TYPES: BEGIN OF st_impos,
      objnr       TYPE coss-objnr,
      gjahr       TYPE coss-gjahr,
      kstar       type coss-kstar,
      projn       type afvc-projn,
      pspnr       type prps-pspnr,
      posnr       type imzo-posnr,
    END OF st_impos.
    data: year TYPE coss-gjahr value '2007'.
    DATA: t_output  TYPE STANDARD TABLE OF st_impos WITH HEADER LINE,
          st_output TYPE st_impos,
          t_output2 TYPE STANDARD TABLE OF st_impos WITH HEADER LINE,
          st_output2 TYPE st_impos.
    SELECT objnr gjahr kstar FROM coss
    INTO CORRESPONDING FIELDS OF st_output
    WHERE ( objnr LIKE 'NV%' OR
          objnr LIKE 'PR%' ) AND
           gjahr = year.
       SELECT SINGLE projn from afvc into CORRESPONDING FIELDS OF st_output
           WHERE objnr = st_output-objnr.
    APPEND st_output to t_output.
    ENDSELECT.
    SORT t_output BY objnr.
    DELETE ADJACENT DUPLICATES FROM t_output.
    LOOP AT t_output into st_output.
    SELECT objnr pspnr
           INTO CORRESPONDING FIELDS OF st_output2
           FROM prps
           WHERE objnr = st_output-objnr
           AND   pspnr = st_output-pspnr.
      SELECT SINGLE posnr from imzo into CORRESPONDING FIELDS OF st_output2
           WHERE objnr = st_output2-objnr.
    APPEND st_output2 to t_output2.
    ENDSELECT.
    ENDLOOP.
    LOOP AT t_output2 to st_output2.
    WRITE:   st_output2-posnr.
    ENDLOOP.

  • Sql Query Error (9i) nested select with OleDB

    I have the following query which works fine when used with Sqlplus, but fails when called from within crytal reports (using an OleDB connection). I saw an open Oracle bug number 3025605 on some website, but haven't been able to look up any additional information on the error. The query fails with Ora-00972.
    SELECT "CLIENTS"."CLTFIRSTNAME",
    "CLIENTS"."CLTLASTNAME",
    "CLIENTS"."CLTMIDDLENAME",
    "SCHEDULE"."SCSESSIONDATE",
    (SELECT r.REMPFIRSTNAME||' '||r.REMPLASTNAME
    FROM REFAGENCYEMPLOYEES R WHERE "R"."REMPLOYEEID" = "SCHEDULE"."SCREFPERSON1ID") REFAGENT1,
    (SELECT r.REMPFIRSTNAME||' '||r.REMPLASTNAME
    FROM REFAGENCYEMPLOYEES R WHERE "R"."REMPLOYEEID" = "SCHEDULE"."SCREFPERSON2ID") REFAGENT2,
    "CODELOOKUP"."CODELISTNAME"
    FROM "POBJS"."CLIENTS" "CLIENTS",
    "POBJS"."SCHEDULE" "SCHEDULE",
    "POBJS"."CODELOOKUP" "CODELOOKUP"
    WHERE ("CLIENTS"."CLIENTID"="SCHEDULE"."SCCLIENTID")
    AND ("SCHEDULE"."SCEXAMTYPE"="CODELOOKUP"."CODEVALUE")
    AND "CODELOOKUP"."CODELISTNAME"='EXAM TYPES'
    Thanks for any help.

    Thanks for the information. I worked around the problem by calling a function that basically runs the nested select statement and returns a value.
    pobjs.getrname("SCHEDULE"."SCREFPERSON1ID") AS AGENT1,
    "CODELOOKUP"."CODELISTNAME"
    FROM "POBJS"."CLIENTS" "CLIENTS", ........

  • Using Nested Table in Select Statement

    Hi all ,
    Can i use the PL/SQL nested table or Varray
    in the select statement as a normal table joined with other database tables.
    i.e.
    I have a nested table NT_1 in PL/SQL proc
    i have to use this NT_1 in the select statement as
    select xxx from
    tab_1,
    tab_2,
    NT_1
    where
    < some conditional joins >.
    Please help me in this regard.
    regds
    Dhananjaya.H

    you can not use a varray as part of a SQL Statement in order to build joins.
    Can you explain better what do you want to do ?
    Joel P�rez

  • Update statement with nested selects and alias usage

    Hello, we are trying to build an update statement like this...
    update table1 t1
    set attr1 = ( select someattr
    from (nested select 1) as aux1
    (nested select 2 (nested select 2.1 + nested select 2.2)) ) as aux2
    where some_join_clauses
    where t1.attr2 = 123
    and t1.attr3 = 'abc'
    Alias t1 shound be known at the level of nested select 1,2 and 2.1, 2.2? We are receiving an error message saying that t1.someattr is an invalid identifier. Can you help? Thanks!

    mauramos wrote:
    Hello, we are trying to build an update statement like this...
    update table1 t1
    set attr1 = ( select someattr
    from (nested select 1) as aux1
    (nested select 2 (nested select 2.1 + nested select 2.2)) ) as aux2
    where some_join_clauses
    where t1.attr2 = 123
    and t1.attr3 = 'abc'
    Alias t1 shound be known at the level of nested select 1,2 and 2.1, 2.2? We are receiving an error message saying that t1.someattr is an invalid identifier. Can you help? Thanks!You can only reference elements nested 1 level deeper in a correlated update statement.
    I'd suggest you try with the MERGE statement, or alternatively, post some sample data (insert statements) and table DDL (create statements), with an 'expected output' description and we can try to help you build a suitable statement.

  • Bug report select statement nested select in FROM Clause on Oracle 10g

    The SELECT statement below does not return the appropriate result; it used to work on Oracle 8, but it does not on 10g (10.2).
    Here is the table
    create table T (
    A numeric(4),
    B numeric(4)
    Some data
    insert into T (A,B) VALUES (1,null);
    insert into T (A,B) VALUES (2,1);
    insert into T (A,B) VALUES (3,1);
    insert into T (A,B) VALUES (3,2);
    The select statement returning the worng result
    select totals.A, totals.totalBbyA
    from (
    select t1.A, sum(t1.B) totalBbyA
    from T t1
    group by A
    ) totals
    where
    totals.totalBbyA >= all
    select sum(nvl(t2.b,0)) from T t2 group by t2.a
    it returns "no rows selected"
    An equivalent select that does return the good result
    select t1.A, sum(t1.B) totalBbyA
    from T t1
    group by A
    having
    sum(t1.B) >= all
    select sum(nvl(t2.b,0)) from T t2 group by t2.a
    It returns
    A TOTALBBYA
    3 3
    Best regards

    910893 wrote:
    but it does not on 10g (10.2).Works fine in:
    SQL> select  *
      2    from  v$version
      3  /
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - Prod
    PL/SQL Release 10.2.0.4.0 - Production
    CORE    10.2.0.4.0      Production
    TNS for 32-bit Windows: Version 10.2.0.4.0 - Production
    NLSRTL Version 10.2.0.4.0 - Production
    SQL> select  *
      2    from  t
      3  /
             A          B
             1
             2          1
             3          1
             3          2
    SQL> select totals.A, totals.totalBbyA
      2  from (
      3  select t1.A, sum(t1.B) totalBbyA
      4  from T t1
      5  group by A
      6  ) totals
      7  where
      8  totals.totalBbyA >= all
      9  (
    10  select sum(nvl(t2.b,0)) from T t2 group by t2.a
    11  )
    12  ;
             A  TOTALBBYA
             3          3
    SQL> SY.

  • HOW CAN I  USE MULTIPLE INNERJOINS IN A SINGLE SELECT STATEMENT?

    HI,
    I AM SHABEER AHMED,
    I AM GETTING AN ERROR WHILE I ATTEMPT TO EXECUTE A SELECT STATEMENT WITH MULTIPLE INNER JOINS . BECOZ I WANT TO FETCH ITEM DATA, PARTNER DATA  BASED ON HEADER DATA .
    THEN OF COURSE I HAVE FETCH DATA FROM VBAK VBAP VBKD SO LZ SEND ME THE SOLUTION.
    BYE

    Hi,
    1.Just see this:
    SELECT * INTO CORRESPONDING FIELD OF TABLE itab
    FROM t1 INNER JOIN t2 ON t1f4 EQ t2f4
    INNER JOIN t3 ON t2f5 EQ t3f5 AND
    t2f6 EQ t3f6 AND
    t2f7 EQ t3f7.
    2.But better to use for all entries.It increases the performance.
    FOR ALL ENTRIES
    Tabular Conditions
    The WHERE clause of the SELECT statement has a special variant that allows you to derive conditions from the lines and columns of an internal table:
    SELECT ... FOR ALL ENTRIES IN <itab> WHERE <cond> ...
    <cond> may be formulated as described above. If you specify a field of the internal table <itab> as an operand in a condition, you address all lines of the internal table. The comparison is then performed for each line of the internal table. For each line, the system selects the lines from the database table that satisfy the condition. The result set of the SELECT statement is the union of the individual selections for each line of the internal table. Duplicate lines are automatically eliminated from the result set. If <itab> is empty, the addition FOR ALL ENTRIES is disregarded, and all entries are read.
    The internal table <itab> must have a structured line type, and each field that occurs in the condition <cond> must be compatible with the column of the database with which it is compared. Do not use the operators LIKE, BETWEEN, and IN in comparisons using internal table fields. You may not use the ORDER BY clause in the same SELECT statement.
    You can use the option FOR ALL ENTRIES to replace nested select loops by operations on internal tables. This can significantly improve the performance for large sets of selected data.
    Example for ALL ENTRIES
    DATA: TAB_SPFLI TYPE TABLE OF SPFLI,
    TAB_SFLIGHT TYPE SORTED TABLE OF SFLIGHT
    WITH UNIQUE KEY TABLE LINE,
    WA LIKE LINE OF TAB_SFLIGHT.
    SELECT CARRID CONNID
    INTO CORRESPONDING FIELDS OF TABLE TAB_SPFLI
    FROM SPFLI
    WHERE CITYFROM = 'NEW YORK'.
    SELECT CARRID CONNID FLDATE
    INTO CORRESPONDING FIELDS OF TABLE TAB_SFLIGHT
    FROM SFLIGHT
    FOR ALL ENTRIES IN TAB_SPFLI
    WHERE CARRID = TAB_SPFLI-CARRID AND
    CONNID = TAB_SPFLI-CONNID.
    LOOP AT TAB_SFLIGHT INTO WA.
    AT NEW CONNID.
    WRITE: / WA-CARRID, WA-CONNID.
    ENDAT.
    WRITE: / WA-FLDATE.
    ENDLOOP.
    INNER JOINS
    In a relational database, you normally need to read data simultaneously from more than one database table into an application program. You can read from more than one table in a single SELECT statement, such that the data in the tables all has to meet the same conditions, using the following join expression:
    SELECT...
    FROM <tab> INNER JOIN <dbtab> AS <alias> ON <cond> <options>
    where <dbtab> is a single database table and <tab> is either a table or another join expression. The database tables can be specified statically or dynamically as described above. You may also use aliases. You can enclose each join expression in parentheses. The INNER addition is optional.
    A join expression links each line of <tab> with the lines in <dbtab> that meet the condition <cond>. This means that there is always one or more lines from the right-hand table that is linked to each line from the left-hand table by the join. If <dbtab> does not contain any lines that meet the condition <cond>, the line from <tab> is not included in the selection.
    The syntax of the <cond> condition is like that of the WHERE clause, although individual comparisons can only be linked using AND. Furthermore, each comparison must contain a column from the right-hand table <dbtab>. It does not matter on which side of the comparison it occurs. For the column names in the comparison, you can use the same names that occur in the SELECT clause, to differentiate columns from different database tables that have the same names.
    The comparisons in the condition <cond> can appear in the WHERE clause instead of the ON clause, since both clauses are applied equally to the temporary table containing all of the lines resulting from the join. However, each join must contain at least one comparison in the condition <cond>.
    Example for INNER JOINS
    REPORT demo_select_inner_join.
    DATA: BEGIN OF wa,
    carrid TYPE spfli-carrid,
    connid TYPE spfli-connid,
    fldate TYPE sflight-fldate,
    bookid TYPE sbook-bookid,
    END OF wa,
    itab LIKE SORTED TABLE OF wa
    WITH UNIQUE KEY carrid connid fldate bookid.
    SELECT pcarrid pconnid ffldate bbookid
    INTO CORRESPONDING FIELDS OF TABLE itab
    FROM ( ( spfli AS p
    INNER JOIN sflight AS f ON pcarrid = fcarrid AND
    pconnid = fconnid )
    INNER JOIN sbook AS b ON bcarrid = fcarrid AND
    bconnid = fconnid AND
    bfldate = ffldate )
    WHERE p~cityfrom = 'FRANKFURT' AND
    p~cityto = 'NEW YORK' AND
    fseatsmax > fseatsocc.
    LOOP AT itab INTO wa.
    AT NEW fldate.
    WRITE: / wa-carrid, wa-connid, wa-fldate.
    ENDAT.
    WRITE / wa-bookid.
    ENDLOOP.
    Regards,
    Shiva Kumar(Reward if helpful).

  • Nested SQL statements for complex, detailed queries.

    Is it  possible to write nested SQL statements for complex, detailed queries. A nested query
    has a WHERE clause that includes a SELECT statement ? Is it true or false ?

    Hi wahid,
    Here are pretty good examples: 
    http://www.databasejournal.com/features/mssql/article.php/3464481/Using-a-Subquery-in-a-T-SQL-Statement.htm
    http://technet.microsoft.com/en-us/library/aa213252(v=sql.80).aspx
    Regards Harsh

  • Plsql procedure containing select statement to fill page items

    I would like to fill items :P200_A and :P200_B and so on
    with the result of a SELECT which depends on the different values of many select lists.
    E.G. :P200_list_alpha with the list of values
    STATIC:less than 10;less,equal than 10;equal,above 10;above,indifferent;indiff
    :P200_list_beta with the list of values
    STATIC:active;active,passiv;passiv,excluded;excluded
    How do I write the select statement ? I think it has to be executed in an anonymous PLSQL Procedure (after submit).
    What is a convenient way to write the select statement ?
    I could imagine to use lots of IF , ELSIF, ELSE statements and in each branch (here 12 ) the whole/complet SELECT statement is written.
    How to solve this problem in an elegant way ?
    In my opinion the CASE statement could be helpful, but how to use it in the WHERE clause with this nested conditions ?

    I think I got it:
    SELECT col1, col2, col3, ...
    INTO :P200_A , :P200_B , ....
    FROM mytable_1, mytable_2
    WHERE mytable_1.col1 = mytable_2.col1
    AND (
    CASE
    WHEN :P200_LIST_ALPHA = 'less' AND NVL(TO_COL_WITH_ALPHA, 0) < 10 THEN 1
    WHEN :P200_LIST_ALPHA = 'equal' AND NVL(TO_COL_WITH_ALPHA, 0) = 10 THEN 1
    WHEN :P200_LIST_ALPHA = 'above' AND NVL(TO_COL_WITH_ALPHA, 0) > 10 THEN 1
    WHEN :P200_LIST_ALPHA = 'indiff' THEN 1
    ELSE 0
    END = 1 )
    AND
    ( CASE
    WHEN :P200_LIST_BETA = 'active' AND TO_COL_WITH_BETA IN ( 'a', 'A', 'akt', 'AKT' ) THEN 1
    WHEN :P200_LIST_BETA = 'passive' AND TO_COL_WITH_BETA IN ( 'p', 'P' ) THEN 1
    WHEN :P200_LIST_BETA = 'excluded' AND TO_COL_WITH_BETA = 'X' THEN 1
    ELSE 0
    END = 1 )
    ;Edited by: wucis on Oct 24, 2011 4:09 PM

Maybe you are looking for

  • Error 5 when installing Indesign CS5

    trying to install my adobe suite 5 indesign and it keeps giving me a error 5 and will not open. help.

  • Agent is Unreachable (REASON = Connection refused) but the host is UP

    Folks, Can I pick your brains, I keep recieving the smtp alert from Grid control which says; Agent is Unreachable (REASON = Connection refused) but the host is UP upto 5 minutes later the smtp mail is received Agent is Unreachable clear : <SERVER> -

  • Date Extract Issue

    Hi, I have developed a sql based report in which the date fields are in the format to_char( 'DD-MON-YYYY'). The tester wants to pull the data in the excel. When they did so, the date displayed as '01-May-2009' became '01-May-09'. I have informed the

  • Do you see problems with text size when importing from Photoshop?

    Hi all - We're working on improving some things in the Photoshop-to-Reflow workflow, and right now specifically investigating trouble with imported text. Aside from the desire to have support for local fonts, are there any problems you run into when

  • Query to find SQL with changed plans

    I am trying to find out which SQL statements have changed plans since they were first executed. I'm trying to run this on all databases from 9i upwards and I am assuming that I have no licensed access to the AWR. However, Statspack is installed on al