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.

Similar Messages

  • 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

  • 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

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

  • How to use SELECT statement  to extract KNA1-NAME1 and KNB1-ZSABE

    In building table I_KNA1 in  form f_extract_data, an additional select statement is needed to select and  append datafrom (KNA1 and KNB1) to existing I_KNA1
    In form f_extract_data table i_kna1 is populated with data from zd_kna101.(where ZD_KNA101 is a view of KNA1, KNB1 and KNBK.  It's a joint of these three tables.)  This will take care of all customers with KNBK-BANKL and KNBK-BANLN populated.  But this does not include new customers created in SAP CRM (no KNBK records).  Therefore a separate SELECT statement is needed to extract KNA1-NAME1 and KNB1-ZSABE for customers created in SAP CRM(the customers who do do not have BANKL and BANKN). These selected records are then need to be appended to I_KNA1.  It's possible that new selection statement might extract records that are already in existing I_KNA1 table.  IF this is the case, right after the append, sort I_KNA1 and remove duplicate records.
    form f_extract_data.
    select kunnr                         " Customer Number
             name1                         " Name
             zsabe                         " Business Unit
             bankl                         " Legacy Bank Key
             bankn                         " Legacy Bank Account
        from zd_kna101                     " View of KNA1, KNB1, and KNBK
        into table i_kna1
        for all entries in i_doc_by_ref
       where kunnr = i_doc_by_ref-kunnr
        and zsabe in s_zsabe.           
      if sy-subrc <> 0.
        message a116 with 'customer'.  " Customer Table is empty.  HALT!!!
      else.                                                    
        sort i_kna1 by kunnr.                                  
      endif.
    will I have to use the join statement(for KNA1-NAME1 and KNB1-ZSABE using the key as KUNNR) here or give two seperate select statements for extracting data from KNA1 and KNB1 using the key as KUNNR.
    THANKS FOR THE HELP.

    I would suggest using the join on KUNNR.  Maybe something like this.
    data: begin of itab occurs 0,
          kunnr type kna1-kunnr,
          name1 type kna1-name1,
          ZSABE type knb1-ZSABE,
          end of itab.
        select kna1~kunnr kna1~name1 knb1~zsabe
               into table itab
                    from kna1
                       inner join knb1
                            on kna1~kunnr = knb1~kunnr
                                   where ........
    Regards,
    Rich Heilman

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

  • How to coerce data types to strings in a SELECT statement?

    ABAPers,
    I need to coerce column outputs to strings in a SELECT statement. Here is a pseudo example:
    select ConvertToString(count(*)) from MARA
    On help.sap.com, I could not find enough information on the functions that are supported within SELECT statement. I would appreciate it if someone can enlighten me on how to achive this.
    Note that my real problem is that I do not know the return type of the specified columns. The columns are passed as a user-specified parameter. As I do not know the column types, I am mandating that customers specify columns that return only string type data.
    Thank you in advance for your help.
    Pradeep

    Hi Pradeep,
    Convert to string wont be possible in the SELECT statement.
    What you can do is use Field Symbols. This allows to assign data types dynamically.
    Field-Symbols
    Best regards,
    Prashant
    Pls. mark points for helpful answers

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

  • Put prepended "WITH" into Select statement possible?

    Assume I have a SQL statement like:
    with t1 as (select ......),
    t2 as (select ......)
    Select .... From t1, t2 Where ....;
    Can I merge somehow the prepended "with" term into the actual select statement?
    As far as I remember there is an equivalent statement syntax like:
    Select .... from t1 as (select ....), t2 as (select ....) where ....;
    but this does not work.
    Peter

    It will be like
    Select ....
    From ( select .. From ...) t1
    ,( select .. From ...) t2
    WHERE ...
    Regards
    Arun

  • Is it Possible to join 4 or more tables in a Select Statement?

    Hello guys,
    Can I do Inner Join 4 or 5 tables in a select statement?

    U HAVE  TO SERCH  FOR  KEY FIELD  FOR THAT . MEANS   HOW  TABELS  ARE RELATED EACH OTHE  FOR THIS  U  ALSO USE SQ02
    FOR  EXAMPLE
    SELECT        bkpf~belnr
                    bkpf~gjahr
                    bkpf~bukrs
                    bkpf~blart
                    bkpf~bldat
                    bkpf~budat
                    bkpf~usnam
                    bkpf~tcode
                    bkpf~xblnr
                    bsik~lifnr
                    bsik~bupla
                    bsik~secco
              INTO  CORRESPONDING FIELDS OF TABLE itab_pur
              FROM bkpf INNER JOIN bsik
              ON   bkpfbelnr = bsikbelnr
               and  bkpfbukrs = bsikbukrs
               WHERE    bkpf~bukrs  IN co_code
               AND      bkpf~budat  IN pos_dt
               AND      bkpf~tcode  IN t_code
               AND      bsik~secco  IN se_code.
      U CAN  ALSO ADD   MORE TABLE BASED  ON CONDITION

Maybe you are looking for

  • HT204306 How to unlock my IPad

    how to unlock my iPad

  • Assign Access Manager roles to end users?

    Hello, I am looking for information on how to assign an AM role to an end-user that is provisioned from IDM 7 to AM 7.1 using the AM resource adapter. We are modeling our IDM to AM provisioning based on this BigAdmin guide: http://www.sun.com/bigadmi

  • Caught exception in Spry.Data.Region.

    Hi there every one... I getting this error and i cant get around it can anyone help me, thanks in advanced..... code: <div spry:region="pvprefix" class="SpryHiddenRegion"> <a href="javascript:pvprefix.previousPage();" spry:if="{ds_PageNumber} != '1'"

  • Automatic batch Determination:Batch determination is not possible

    Dear Guru's, I have ticked the automatic batch determination in the item categories. Defined the records for the batch determiantion: in VCH1. i have assigned the Batch Determination --> in the Logistics General. But in the Order Screen : when I go t

  • How do I transfer all my pics from my computer to the TC

    I want to transfer all my pics wirelessly from my laptop to the external-hardrive(Time Capsule) so it will free up the space on my laptop. I need step by step instructions if you can. Thanks