Limit no of rows in complex query

Hi,
I have below cursor query for which I need to limit no of rows retrieved to a certain value say 5000.
I'm getting full table scan on table ltc_iss_rec if I do not specify a range
for ltc_iss_rec.
Thq query purpose get ref nos whose lc expiry date is less than or equal to
sysdate -15.
The max query below is also giving higher cost .
Question si how to limit rows in cursor without using a range for ltc_iss_rec_id.
The primary key in ltc_iss_rec is (ltc_iss_rec_id,psd_serial_num)
Index in ltc_iss_rec is (ltc_iss_rec_id,lc_expr_dt)
The primary key in psd is (psd_id,psd_serial_no)
primary key in psd_link is (psd_id,psd_serial_no,link_psd_id,link_psd_ser_no)
Index in psd_link is (link_psd_id,link_psd_ser_no)
Index on psd_lcs is (update_serial_no)
primary key on (psd_lcs) is (psd_id,psd_serial_no,other columns)
SELECT MIN(ltc_iss_rec_id)
INTO l_min_ltc_iss_rec_id
FROM ltc_iss_rec
WHERE lc_expr_dt <= ADD_MONTHS(SYSDATE,-15);
SELECT MAX(ltc_iss_rec_id)
INTO l_max_ltc_iss_rec_id
FROM
SELECT ltc_iss_rec_id
FROM ltc_iss_rec
WHERE ltc_iss_rec_id >= l_min_ltc_iss_rec_id
ORDER BY ltc_iss_rec_id
WHERE ROWNUM < l_iwh_arch_cnt;
OPEN txn_ref_cur FOR
SELECT b.ltc_iss_rec_id,b.psd_serial_num,a.sys_id,a.cosmos_ref_no,
a.src_sys_asgn_ref_no,a.bank_id,b.lc_expr_dt
FROM psd a,ltc_iss_rec b
WHERE b.ltc_iss_rec_id >= l_min_ltc_iss_rec_id
AND b.ltc_iss_rec_id <= l_max_ltc_iss_rec_id
-- and b.lc_expr_dt <= add_months(sysdate,-15)
AND a.psd_id = b.ltc_iss_rec_id
AND a.psd_serial_no = b.psd_serial_num
AND a.psd_typ_cod = 'ISS'
AND a.psd_serial_no =
SELECT NVL(MAX(link_psd_ser_no),'000') FROM psd_link c,psd_lcs d
WHERE c.psd_id = d.psd_id
AND c.psd_serial_no = d.psd_serial_num
AND c.link_psd_id = a.psd_id
AND c.link_psd_id BETWEEN l_min_ltc_iss_rec_id AND l_max_ltc_iss_rec_id
AND d.update_serial_num = (
SELECT MAX(f.update_serial_num) FROM psd_link e, psd_lcs f
WHERE e.psd_id = f.psd_id
AND e.psd_serial_no = f.psd_serial_num
AND e.link_psd_id = a.psd_id
ORDER BY b.ltc_iss_rec_id;

Try using Analytic function row_number().
Regards
RK

Similar Messages

  • Limit nbr of rows in a query

    Dears,
    I found 2 solutions to limit the number of rows a query can return:
    - the first one is making use of a condition in the query itself based on RCOUNT
    - a second one is setting the parameter ResultRowLimit in the instanceconfig file.
    Now I was wondering how this works. Suppose that I want to limit my result set to the first 100 rows before retrieving the whole report.
    Making use of the condition it's clear...an extra where-clause is added that will limit the number of rows retrieve.
    But what with the ResultRowLimit parameter. Is the query retrieving all rows and only shows the first 100? Or is the execution of the query really restricted to the first 100 rows?
    Can anyone explain me once?
    Txs!!
    PS if someone knows another solution to limit the query result, just let me know ;-)
    Edited by: ADB on 6-jul-2009 8:07

    Try using Analytic function row_number().
    Regards
    RK

  • Limit Number for Rows in BW Query Result

    Hello Experts,
        I am creating a query to be consumed by a web service. Therefore, I want to restrict the number of rows the query can display. Does anyone know a way to limit the result set to display only say FIRST 100 rows of data?
        I have looked at 'safety belt' solution, i.e. limiting number of cells to for example, 5000 cells. However, when the limit is exceeded the query just shows an error message not the first 5000 cells.
    thanks,
    Kartik

    Hi,
    You can do some things like..........
    Do not display the data in a detailed level.
    Use Always Suppress option in the result set.
    Also it depends on your Query definition. If your rows contains Branch wise or Region Wise, then your report will be fit in your first level of output. You need not to drilldown further.
    Why do you want to consider only first 1000 rows if you are planning to use it by Web service?
    I don't know whether it is feasible or not. I have one more alternative for you. You can try to achieve by APD by the Query. Insert a ABAP routine which should consider first 1000 result rows for your Web service. Just throw a light on this idea..............
    Regards,
    Suman

  • How do you limit the number of rows return from query?

    How do you limit the number of rows return from query? Do all databases support this kind of feature?

    i think the standard is limit
    to get the top 30
    select * from mytable LIMIT 30;returns the first 30 rows
    also if you want a range
    select * from mytable LIMIT 10,30;returns 30 rows starting from 10
    this last one is useful for displaying ranges... something similar happens in these forums when viewing topics and messages

  • How to create an explain plan with rowsource statistics for a complex query that include multiple table joins ?

    1. How to create an explain plan with rowsource statistics for a complex query that include multiple table joins ?
    When multiple tables are involved , and the actual number of rows returned is more than what the explain plan tells. How can I find out what change is needed  in the stat plan  ?
    2. Does rowsource statistics gives some kind of  understanding of Extended stats ?

    You can get Row Source Statistics only *after* the SQL has been executed.  An Explain Plan midway cannot give you row source statistics.
    To get row source statistics either set STATISTICS_LEVEL='ALL'  in the session that executes theSQL OR use the Hint "gather_plan_statistics"  in the SQL being executed.
    Then use dbms_xplan.display_cursor
    Hemant K Chitale

  • Limit number of rows from wildcard expansion- DRG-51030

    We use CONTEXT iindex in 11g to search on a text DB column, "Name".
    This is used in a UI to show autosuggest list of 25 matching names.
    When the end user types an 'a' we want to show a list of the first 25 names that contain an 'a'.
    We hit the issue of too many matches in the wildcard expansion query:
    DRG-51030: wildcard query expansion resulted in too many terms
    This is a frequent use case when the user types just 1 character ('a' will easily match over 50K names in our case).
    Is there a way to make the wildcard expansion query only return the first 25 rows?
    We never show more than 25 names in our UI - so we would like the expansion query to also return max of 25 rows.
    Our query is:
    SELECT ResEO.DISPLAY_NAME,
    ResEO.RESOURCE_ID,
    ResEO.EMAIL
    FROM RESOURCE_VL ResEO
    WHERE CONTAINS (ResEO.DISPLAY_NAME , '%' || :BindName || '%' )>0
    Also,
    Is there a way to use CTXCAT type of index and achieve this (expansion query limit of 25)?
    We are considering switching to CTXCAT index based on documentation that recommends this type of an index for better performance.

    Your best bet may be to look up the words directly in the $I token table.
    If your index is called NAME_INDEX you could do:
    select /* FIRST_ROWS(25) */ token_text from
      (  select token_text
         from dr$name_index$i  
         where token_text like 'A%' )
    where rownum < 26;That should be pretty quick.
    However, if you really want to do %A% - any word which has an A in it - it's not going to be so good, because this will prevent the index being used on the $I table - so it's going to do a full table scan. In this case you really need to think a bit harder about what you're trying to achieve and why. Does it really make any sense to return 25 names which happen to have an A in them? Why not wait until the user has typed a few more characters - 3 perhaps? Or use my technique for one or two letters, then switch over to yours at three characters (or more).
    A couple of notes:
    - Officially, accessing the $I table is not supported, in that it could change in some future version, though it's pretty unlikely.
    - I trust you're using the SUBSTRING_INDEX option if you're doing double truncated searches - a wild card at the beginning and end. If not, your performance is going to be pretty poor.

  • Creating a complex query in CR designer

    I'm running Crystal Reports XI Release 2 on Windows NT. I have a very complex query and cannot figure out how to make it work in CR. Basically, I've got a table A with fields containing reference codes that may or may not be present. I created a SQL query that imbeds select statements in the select fields (the field names between SELECT and FROM). So, it would read something like SELECT field1, field2, (select Code_Name from REF_Table where REF_Table.code=TableA.code and TableA.code is not null) FROM TableA. That works great in SQL Developer.
    In CR, I tried a command field but that produces a cartesian set where I get a line for every record that has the field for each and every record in TableA.  No good. I just want the name for the value in the TableA record translated to the name if it is present.  Is there a way to do this in CR? I used to be able to edit the SQL directly in CR but now it won't let me do that. Anyone know a better way to solve this kind of problem?

    I'm not an Oracle guy so I don't know what you can or can't do in PL SQL.
    I'm surprised that you are getting different results between SQL Developer and the CR Command. CR should pass the query, exactly as it's written back to the server, same as SQL Dev.
    IN T-SQL...If  you want to make sure that the sub-query is returning only 1 row, try placing "TOP 1" behind the SELECT.
    (select top 1 loc.location_name
    from ref_location loc
    where loc.location_num=obd.location_num and odb.location_num is not null)
    I'm thinking that Oracle doesn't have the the TOP N option but it does have a rownum feature. So maybe...
    (SELECT x.location_name
    FROM (
        select loc.location_name
        from ref_location loc
        where loc.location_num=obd.location_num and odb.location_num is not null) x
    WHERE rownum = 1
    ORDER BY rownum)
    This is assuming that Oracle allows you to use ORDER BY in a sub-query. T-SQL only allows it if it's used in conjunction with TOP N...
    Just a thought,
    Jason

  • Working with a complex query and trying to get rid of duplicates

    I'm working with the following complex query, and I need to
    select vin, number, year, make, model, and state from
    2007 vehicles in certain models, vin types
    2006 vehicles in certain models, vin types
    Is there a more efficient way to write this than how I've been writing it?:
    select distinct vehicle.vin VIN, unit.STATION_ID STID, unit.EMBEDDED_AREA_CODE||unit.EMBEDDED_PREFIX||lpad(unit.EMBEDDED_RON,4,0)
    MIN, unit.AUTHENTICATION_ID AUTHCODE, vehicle.user_veh_desc, veh_model.VEH_MODEL_DESC MODEL, veh_model.VEH_MANUF_YEAR YEAR, acct_veh.STATE STATE
    from vehicle
    inner join veh_unit on vehicle.vehicle_sak=veh_unit.vehicle_sak
    inner join unit on veh_unit.unit_sak=unit.unit_sak
    inner join vdu_profile on vdu_profile.vehicle_sak=vehicle.vehicle_sak
    inner join vdu_profile_program on vdu_profile_program.VDU_PROFILE_SAK=vdu_profile.VDU_PROFILE_SAK
    inner join veh_model on vehicle.VEH_MODEL = veh_model.VEH_MODEL
    inner join acct_veh on acct_veh.VEHICLE_SAK = vehicle.VEHICLE_SAK
    and vehicle.user_veh_desc like ('%2007%')
    AND unit.unit_gen_id >= 36
    AND vdu_profile_program.VDU_PROGRAM_SAK = 3
    and vdu_profile_program.PREFERENCE_VALUE = 'Y'
    and acct_veh.STATE in ('MN','ND','IA')
    AND (veh_model.VEH_MODEL_DESC like ('%Vehicle2%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle3%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle5%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle6%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle7%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle8%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle9%'))
    and ACCT_VEH.ACCT_VEH_STATUS_ID = 'A'
    and (vehicle.vin like ('_______3_________')
    or vehicle.vin like ('_______W_________')
    or vehicle.vin like ('_______K_________')
    or vehicle.vin like ('_______0_________'))
    UNION
    select distinct vehicle.vin VIN, unit.STATION_ID STID, unit.EMBEDDED_AREA_CODE||unit.EMBEDDED_PREFIX||lpad(unit.EMBEDDED_RON,4,0)
    MIN, unit.AUTHENTICATION_ID AUTHCODE, vehicle.user_veh_desc, veh_model.VEH_MODEL_DESC MODEL, veh_model.VEH_MANUF_YEAR YEAR, acct_veh.STATE STATE
    from vehicle
    inner join veh_unit on vehicle.vehicle_sak=veh_unit.vehicle_sak
    inner join unit on veh_unit.unit_sak=unit.unit_sak
    inner join vdu_profile on vdu_profile.vehicle_sak=vehicle.vehicle_sak
    inner join vdu_profile_program on vdu_profile_program.VDU_PROFILE_SAK=vdu_profile.VDU_PROFILE_SAK
    inner join veh_model on vehicle.VEH_MODEL = veh_model.VEH_MODEL
    inner join acct_veh on acct_veh.VEHICLE_SAK = vehicle.VEHICLE_SAK
    and vehicle.user_veh_desc like ('%2006%')
    AND unit.unit_gen_id >= 36
    AND vdu_profile_program.VDU_PROGRAM_SAK = 3
    and vdu_profile_program.PREFERENCE_VALUE = 'Y'
    and acct_veh.STATE in ('MN','ND','IA')
    AND (veh_model.VEH_MODEL_DESC like ('%Vehicle1%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle2%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle3%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle4%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle5%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle6%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle7%'))
    and ACCT_VEH.ACCT_VEH_STATUS_ID = 'A'
    and (vehicle.vin like ('_______Z_________')
    or vehicle.vin like ('_______K_________'))

    I am not sure how many rows you have in the tables but I am assuming that there would be performance benefits in performing the query only once. You can combine similar coding and use an OR condition for the parts that are different. I left the 'K' vin comparison in both years for readability.
    I was not able to fully test my code but I believe that it will work as is. I hope it helps. If you are happier with the UNION you may want to investigate the WITH clause as you can query a subset of data twice, rather than the full data set.
    -- Common code 
    SELECT DISTINCT
       vehicle.vin,
       unit.station_id stid,
       unit.embedded_area_code || unit.embedded_prefix || LPAD (unit.embedded_ron, 4, 0) MIN,
       unit.authentication_id authcode,
       vehicle.user_veh_desc,
       veh_model.veh_model_desc model,
       veh_model.veh_manuf_year YEAR,
       acct_veh.state
    FROM vehicle
    INNER JOIN veh_unit           
       ON vehicle.vehicle_sak = veh_unit.vehicle_sak
    INNER JOIN unit               
       ON veh_unit.unit_sak = unit.unit_sak
    INNER JOIN vdu_profile        
       ON vdu_profile.vehicle_sak = vehicle.vehicle_sak
    INNER JOIN vdu_profile_program
       ON vdu_profile_program.vdu_profile_sak = vdu_profile.vdu_profile_sak
    INNER JOIN veh_model          
       ON vehicle.veh_model = veh_model.veh_model
    INNER JOIN acct_veh           
       ON acct_veh.vehicle_sak = vehicle.vehicle_sak     
    AND unit.unit_gen_id >= 36
    AND vdu_profile_program.vdu_program_sak = 3
    AND vdu_profile_program.preference_value = 'Y'
    AND acct_veh.state IN ('MN', 'ND', 'IA')
    AND acct_veh.acct_veh_status_id = 'A'
    AND
    -- Annual code
          (   -- 2006 conditions 
          AND vehicle.user_veh_desc LIKE ('%2007%')
          AND regexp_like(veh_model.veh_model_desc, 'Vehicle[2356789]')
          AND regexp_like(vehicle.vin, '_{7}[3WK0]_{9}')           
       OR
          (   -- 2007 conditions 
          AND vehicle.user_veh_desc LIKE ('%2006%')
          AND regexp_like(veh_model.veh_model_desc, 'Vehicle[1234567]')
          AND regexp_like(vehicle.vin, '_{7}[ZK]_{9}')
       ).

  • Possible to execute complex query in ExecuteSQL method in DI Server??

    Hi All,
    Is it Possible to execute complex query in ExecuteSQL Method in DI Server?
    Regards,
    G.Suresh

    Hello Guru,
    It is possible. Mostly if it can be done in DI, it will also can be done in DI Server except metadata operaiton, transation management etc.
    I try the following complex query (join, nexted):
    The SOAP Request
    <?xml version="1.0" encoding="UTF-16"?>
    <env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
    <env:Header>
      <SessionID>4FFCFAA3-5493-456A-BC89-410B35AF096C</SessionID>
    </env:Header>
    <env:Body>
      <dis:ExecuteSQL xmlns:dis="http://www.sap.com/SBO/DIS">
       <DoQuery>SELECT OCRD.CardCode, OCRD.CardName, OCPR.Name FROM OCRD JOIN OCPR ON OCRD.CardCode = OCPR.CardCode WHERE OCRD.CardCode IN
    (SELECT DISTINCT ORDN.CardCode FROM ORDN)</DoQuery>
      </dis:ExecuteSQL>
    </env:Body>
    </env:Envelope>
    The SOAP Response:
    <?xml version="1.0"?><env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
    <env:Body><ExecuteSQLResponse xmlns="http://www.sap.com/SBO/DIS">
    <BOM><BO><AdmInfo><Object>oRecordset</Object></AdmInfo><OCRD><row><CardCode>C002</CardCode><CardName>SAP</CardName>
    <Name>2</Name></row><row><CardCode>C002</CardCode><CardName>SAP</CardName><Name>l</Name></row><row><CardCode>C002</CardCode>
    <CardName>SAP</CardName><Name>Z</Name></row></OCRD></BO></BOM></ExecuteSQLResponse></env:Body></env:Envelope>
    I think you can easily parse the result...
    Kind Regards
    -Yatseas

  • Working with multiple results of a complex query

    Hi all!
    As I "advance" in learning PL/SQL with oracle, I now get stuck in handling multiple results of a complex query. As far as I know, I cannot use a cursor here, as there is no table where the cursor could point to.
    Here is the concept of what I want to do (pseudocode):
    foreach result in SELECT * FROM table_1, table_n WHERE key_1 = foreign_key_in_n;
        -- do someting with the resultHere is my attemt, that freezes the browser gui and throws an internal database error:
    declare
        type t_stock is record(
                baggage_id  baggage.baggage_id%type,
                section_id  sections.section_id%type,
                shelf_id    shelves.shelf_id%type
        v_stock t_stock;
        rcnt number(2);
    begin
    dbms_output.put_line(TO_CHAR(rcnt));
    loop
         SELECT COUNT(*) INTO rcnt FROM (
                   SELECT baggage.baggage_id, sections.section_id, shelves.shelf_id
                   FROM baggage, sections, shelves
                   WHERE baggage.baggage_id = sections.contained_baggage_id
                        AND shelves.is_connex_to_section_id = sections.section_id);
         IF rcnt <= 0 THEN
              exit;
         END IF;
         SELECT baggage.baggage_id, sections.section_id, shelves.shelf_id INTO v_stock
         FROM baggage, sections, shelves
         WHERE baggage.baggage_id = sections.contained_baggage_id
              AND shelves.is_connex_to_section_id = sections.section_id
              AND ROWNUM < 2;
         UPDATE sections SET contained_baggage_id = NULL WHERE section_id = v_stock.baggage_id;
         commit; -- do I need that?
    end loop;
    END;
    /So, is there a way to traverse a list of results from a complex query? Maybe without creating a temporary table (or is that the better way?).
    regards, Alex
    I reformatted the code
    pktm

    Ok, here are the details:
    The tables are used to model kind of a transport system. There are terminals connected with sections that may contain 1 piece of baggage. The baggage is moved by a procedure through a transport system. After each of these "moving steps", I check if the baggage is in front of the shelf it should be in.
    [To be honest, the give statement doesn't contain the info, in which shelf the baggage wil bee inserted. That was spared out because of the lack of a working piece of code :)]
    But: if we consider the fact, that a baggage is in front of such a shelf in the way, that it should be put in this shelf, then all this makes some sense.
    - move baggae through a transport system
    - see if you can put baggage into a shelf
    In order to "put baggage in a shelf", I need to remove it from the transport section. As the transport system is not normalized, I need to update the section where the baggage was in.
    Uhm... yes it's a task that doesn't make too much sense. It seems to be some kind of general spirit in university homework :)
    But: the FOR r IN (Statement) lloks good. I'll use that.
    And, the ROWNUM < 2 is used to limit the size of the result to 1, there is no need to have a specific ordering. It's just because - afaik - oracle doesn't have a limit clause. I would appreciate your help if you know a better way to do limit resultsets.
    best regards, Alex

  • How can i imrove peroformance of complex Query

    How can i improve performance of complex Query
    which used CASE WHEN , GROUP By Rollup
    for example
    SELECT CASE WHEN null then a
    ELSE b END
    FROM (
    SELECT a,b,c,..........
    FROM table1
    UNION ALL
    SELECT a,b,c,..........
    FROM table2
    GROUP BY ROLLUP a,b,c ,............
    this query take 18 min to return 180000 record
    is there is any way to improve the performance of this query

    Hello
    Have you considered using
    ALTER SYSTEM SET _fast=TRUE;-)
    Alternatively you could provide some more information such as an execution plan for your query:
    Oracle9i Enterprise Edition Release 9.2.0.4.0 - Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.4.0 - Production
    SQL> set linesize 200
    SQL> set pages 50000
    SQL> EXPLAIN PLAN FOR
      2  select * from dual;
    Explained.
    SQL> select * from table(dbms_xplan.display);
    PLAN_TABLE_OUTPUT
    | Id  | Operation            |  Name       | Rows  | Bytes | Cost  |
    |   0 | SELECT STATEMENT     |             |       |       |       |
    |   1 |  TABLE ACCESS FULL   | DUAL        |       |       |       |
    Note: rule based optimization
    9 rows selected.If you want general info on tuning, I suggest you read the Perfomance tuning guide and the Data Warehousing guide. These are the best place to find information about concepts and techniques. The forums are better suited to specific questions.
    HTH
    David

  • Complex query design suggestions

    Hi, I should first of all point out I'm new to pl/sql and struggling a bit so any help you can provide is really appreciated.
    I have the requirements for a complex query the conditions of which are as follows
    Four tables involved
    ProductGroups, Products, Stock, StockMovements
    Query requirements psudeocode (broken into bits to make things easier)
    /* CODE */
    Select distinct products
    where productgroup.group between 'a' and 'z'
    And stock.location = 'x'
    And stock.qty > 0
    For each product
         _myDate = currentdate - 1 year
         stkMvt= Select * from StockMovements where product = product
         If(select count(*) from stkMvt where code = 'A' and type = 'A' and source = 'A' and stkMvt.date > _myDate) > 0)
              -- exclude row / move next product
         End If
         If (select count(*) from stkMvt where code = 'B' and type = 'B' and source = 'B' and stkMvt.date> _myDate) > 0)
              -- exclude row / move next product
         End If
         If (select count(*) from stkMvt where code = 'C' and type = 'C' and source = 'C' and Qty > 0 and stkMvt.date> _myDate) > 0)
              -- exclude row / move next product
         End If
         If (select max(stkMvt.date) from stkMvt where code = 'D' and type = 'D' and source = 'D' < _myDate)
              If ( select max(stkMvt.date) from stkMvt where ((code = 'E' and type = 'E' and source 'E')
                   Or (code = 'F' and type = 'F' and source = 'F')
                   Or (code = 'G' and type = 'G' and source = 'G')) > _myDate )
                   -- exclude row / move next product
              End If
         End If
         -- Get the fields to return
         Qty1 = Select coalesce(sum(qty),0) from stkMvt where code = 'H' and type = 'H' and source = 'H'
         Qty2 = Select coalesce(sum(qty),0) from stkMvt where code = 'I' and type = 'I' and source = 'I'
         Qty3 = Select coalesce(sum(qty),0) from stkMvt where code = 'J' and type = 'J' and source = 'J' and stkMvt.date between :fromDate and :toDate
         LastDate = Select max(stkMvt.Date) from stkMvt
         StkQty = Select Qty from Stock where product = product
         AllQty = Select AllQty from Stock where product = product
         FreeQty = StkQty - AllQty
         Value = Select value from Stock
         Select group, product , Qty1, Qty2, Qty3, LastDate, StkQty, AllQty, FreeQty, Value INTO table/cursor
    Loop
    Return table / cursor
    /* CODE END */
    Any guidance about the best way to achieve the above in an SP or Package would be massively helpful,
    Thanks in advance
    Scott.

    Agreed, it is a mess and I was looking the other way when it was dumped into my lap to deal with unfortunately. Any pointers in the right direction would really be helping me out.
    ok first the table structures, I'll include only the relevant fields to make things a bit easier.
    CREATE TABLE "TEST"."CMGROUP"
    (     "CMGRP_GROUP" CHAR(4 BYTE),
         "CMGRP_DESC" CHAR(30 BYTE)
    CREATE TABLE "TEST"."CMPROD"
    (     "CMP_PRODUCT" CHAR(20 BYTE),
         "CMP_DESC" CHAR(50 BYTE),
         "CMP_GROUP" CHAR(4 BYTE),
         "CMP_SPECIAL" CHAR(1 BYTE)
    CREATE TABLE "TEST"."STOCK"
         "STK_PRODUCT" CHAR(20 BYTE),
         "STK_LOC" CHAR(5 BYTE),
         "STK_STKQTY" NUMBER,
         "STK_VALUE" NUMBER,
         "STK_ALLSTK" NUMBER
    CREATE TABLE "TEST"."STMOVE"
         "STMOV_LOC" CHAR(5 BYTE),
         "STMOV_PRODUCT" CHAR(20 BYTE),
         "STMOV_DATE" DATE,
         "STMOV_TYPE" CHAR(1 BYTE),
         "STMOV_SOURCE" CHAR(1 BYTE),
         "STMOV_CODE" CHAR(1 BYTE),
         "STMOV_QTY" NUMBER,
         "STMOV_YEAR" NUMBER(5,0),
         "STMOV_PERIOD" NUMBER(5,0)
    Relationships are as follows
    CMGROUP.CMGRP = CMPROD.CMP_GROUP (One to Many)
    CMPROD.CMP_PRODUCT = STOCK.STK_PRODUCT (One to Many)
    STOCK.STK_LOC = STMOVE.STMOV_LOC (Many to Many)
    STOCK.STK_PRODUCT = STMOVE.STMOV_PRODUCT (Many to Many)
    As for the requirements well they aren't straightforward but the gist of it is to return a ref cursor to a crystal report from an oracle package. The ref cursor is to contain the following
    select products that are
    1) In stock
    2) For a specific location
    3) In a range of product groups
    4) That either have a manual stock receipt movement within the last 12 months
    5) Or do not have the following stock movement within the last 12 months
         a. PO Receipt
         b. WO Receipt
         c. Stock Acquisition Receipt
    Of the results I need to
         1) Display the group
         2) Display the product
         3) Sum the Qty of WO Receipts from the 1st of the month (13 Months Ago) until today
         4) Sum the Qty of PO Receipts from the 1st of the month (13 Months Ago) until today
         5) Sum the Qty of Stock Transfers from the 1st of the month (13 Months Ago) until today
         6) Display the most recent stock movement date
         7) Display the current stock quantity
         8) Display the allocated stock quantity
         9) Display the available stock quantity
         10) Display the stock value
    Movement code definitions as follows     
    Manual Stock Receipt
    Stmov_type: O
    Stmov_source: J
    Stmov_code: G
    Purchase Order Goods Receipt
    Stmov_type: O
    Stmov_source: R
    Stmov_code: S
    Stock Requisition Receipt (Positive stmov_qty value)
    Stmov_type: G
    Stmov_source: J
    Stmov_code: L
    Stock Requisition Issue (Negative stmov_qty value)
    Stmov_type: G
    Stmov_source: J
    Stmov_code: L
    Manual Stock Issue to GL Account (Issue to workshop)
    Stmov_type: F
    Stmov_source: J
    Stmov_code: G
    Works order issue
    Stmov_type: F
    Stmov_source: W
    Stmov_code: G
    Works order receipt
    Stmov_type: 1
    Stmov_source: W
    Stmov_code: G
    There are a few other conditions and requirements but I think that covers the basics. If there is anything I've left out let me know and I do my best to provide.
    Thanks in advance
    Scott.

  • How can I do for a row of a query be data provider for a variable?

    Hi friends, I have a problem !
    How can I do for a row of a query be data provider for a variable?
    I need that a value of variable be stored when the user select a row in a query. At the BPS we can do this configuring the variable selector in WIB, and in a WAB how I can do this ?
    Best regards,
    Gustavo Liberado

    In this case when I press the key to call other forms I need to wait for the response in the secondary form and then process the result.That is exactly what a "modal JDialog" (or JOptionPane) are used for.
    Try it. Create a short demo program. All you need is a JFrame with a single button to show the modal dialog. All you modal dialog needs is a single button to close the dialog. After you show the modal dialog add a System.out.println(...) statement in your code and you will see that it is not executed until the dialog is closed.
    Then once you understand the basics you add the code to your real program.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.

  • Can I use SYSDATE in the WHERE clause to limit the date range of a query

    Hi,
    Basicaly the subject title(Can I use SYSDATE in the WHERE clause to limit the date range of a query) is my question.
    Is this possible and if it is how can I use it. Do I need to join the table to DUAL?
    Thanks in advance.
    Stelios

    As previous poster said, no data is null value, no value. If you want something, you have nvl function to replace null value by an other more significative value in your query.<br>
    <br>
    Nicolas.

  • Complex query

    I am novice in PL/Sql. I need some help in writing a complex query.
    I imagine the following table structure.
    Type(string) Date(date) count(int)
    Given a date range
    The query needs to group the records on type and return the record (type and count) which has the max date (its just date, no time is involved) for each group (which is based on type) . If there are more than one records which have the max date then the average count should be returned for that type
    i would be glad if someone could give any ideas as to how to go about this query. Thanking you in advance.
    regards.

    Heres the query ... Forget the period .... wht this query is supposed to do is group on assigned ki for a given date range. then it has to get the value which is for the last record for that Ki in the date range. If there are 2 records which have max date then it should give an average.
    e.g
    assignedKI / date / value
    a 1st may 2008 10
    b 2nd may 2008 12
    c 1st may 2008 13
    a 30 - apr-2008 16
    b 4th may 2008 17
    a 1st may 2008 20
    The query should return
    a 1st may 2008 15 (which is the average as there are 2 values for the max date for a)
    b 4th may 2008 17
    c 1st may 2008 13
    the following query doesnot work ....
    SELECT
    kiv2.assigned_k_i,
    kiv2.ki_name,
    kiv.period,
    max( kiv2.ki_value_date) ,
    avg(kiv2.ki_value)
    FROM
    SELECT
    assigned_k_i,
    period p1,
    TO_CHAR(ki_value_date, period) period,
    MAX(ki_value_date) ki_value_date
    FROM
    v_ki_value,
    (select ? period from dual)
         WHERE
         (status = 'APPROVED' OR status = 'AUTOAPPROVED')
    AND ( trunc(to_date(to_char(ki_value_date, 'DD/MM/YYYY'), 'DD/MM/YYYY')) >= ?)
    AND ( trunc(to_date(to_char(ki_value_date, 'DD/MM/YYYY'), 'DD/MM/YYYY')) &lt;= ?)
    AND (INSTR(?, TO_CHAR(assigned_k_i)) > 0)
    GROUP BY
    assigned_k_i,
    TO_CHAR(ki_value_date, period)
    ) kiv,
    v_ki_value kiv2
    WHERE
    kiv.assigned_k_i = kiv2.assigned_k_i
    AND to_char(kiv.ki_value_date, kiv.p1) = to_char(kiv2.ki_value_date, kiv.p1)
    GROUP BY
    kiv2.assigned_k_i,
    kiv2.ki_name,
    kiv.period,
    kiv2.ki_value
    ORDER BY
    kiv2.assigned_k_i

Maybe you are looking for

  • Java.awt availability in CDC Toolkit ?

    Hi guys and girls, I've just tried out the Sun Java Toolkit for CDC 1.0 .. I tried making a simple app which uses awt components, such as Frame, Label, Button .. but the Label and Button just wont compile. I always thought that CDC has all the lib fo

  • Moving site to iweb

    Is iweb used only to build a site, or is it possible to move an existing site over to it?

  • MBA fails to wake (Platform Failure) after entering Low Power Sleep state

    2011 MacBook Air 13” model number A1369 The issue: every time the battery drains empty and the device automatically shuts off, it will not properly power-on after being charged.  The display backlight is active (and apple logo on the rear is illumina

  • Nokia C7 contact default phone number

    I have a Nokia C7-00 and are using Nokia Ovi Suite 3.0.0.290. As soon as I have edited a contact with several phone numbers, one of the numbers is marked as default number. After synchronizing, there is only the default number visible for voice call.

  • Poor Performance using Videos on Networked Attached Drive (NAS)

    Finally I got tired of trying to keep all 5 of our home computers syncronized together. The NAS box solves many of the problems. Two issues have arrived. First the playback of my videos from the NAS seems to robbed my CPU performance. Song files perf