Cursors & procedures - - Help in simple query!

hi all...
i am having difficulties trying to implement a simple
PL/SQL program, in fact...
i got it working, but i believe it could be implemented
in a more procedural manner!!!
here is my working code:
CREATE VIEW Todays_Rank AS
Select ISBN, RANK()OVER (Order by Total_Sold ASC)Sales_Rank
FROM
(SELECT bk.ISBN, sum(cc.Quantity) Total_Sold
FROM Book bk, Cart_Contains cc, Shopping_Cart sc
WHERE bk.ISBN = cc.ISBN
AND cc.Cartid = sc.Cartid
AND ((sc.State='checked-out') Or (sc.State='fulfilled '))
Group by bk.ISBN
Order by sum(cc.Quantity) ASC);
SET serveroutput ON
BEGIN
DECLARE
CURSOR rank_cursor IS
SELECT ISBN, sales_rank FROM todays_rank;
IndRec rank_cursor%ROWTYPE;
BEGIN
OPEN rank_cursor;
LOOP
FETCH rank_cursor INTO IndRec;
EXIT WHEN rank_cursor%NOTFOUND;
UPDATE book bk
SET bk.sales_rank=IndRec.sales_rank
WHERE bk.isbn=IndRec.ISBN;
COMMIT;
END LOOP;
CLOSE rank_cursor;
END;
END;
as i understood from cursors so far, is that they do the same job as views, which made me think that there must be
a better implementation for the code above!!!
*note that the query above is meant to update the book
table directly, and after it is done, it deletes any
temporary values, i.e. the created views!!!
the part to deal with deleting the views is not
implemented yet though!!
i hope you have some hints for me...!!!
thanking your kind attention & cooperation in advance!!

hi all once again..
in relation to the same db schema brought up earlier,
a simple prog. has been implemented to run on daily basis,
checks all the books that has been ordered by the customers, and that applies on books that are in status
checked out, and compares the quantity of each ordered
book to the one held in stock!!
finally it generates a report of the ordered quantity by customers - quantity in stock * 5
the query is perfectly working as follow:
-- Retreival of quantity of books sold today
CREATE or replace VIEW sold_today AS
SELECT cc.ISBN, sum(cc.Quantity) AS total_sold
FROM Cart_Contains cc, Shopping_Cart shc
WHERE cc.Cartid = shc.Cartid
GROUP BY cc.ISBN
ORDER BY Sum(cc.quantity) DESC;
-- Retreival of the quantity in stock of each book
CREATE or replace VIEW stock_quantity AS
SELECT s.ISBN, sum(s.Quantity) AS total_stock
FROM stocks s
GROUP BY s.ISBN
ORDER BY Sum(s.quantity) DESC;
set serveroutput on
BEGIN
DECLARE
reOrder Number(4);
todaysDate SHOPPING_CART.ORDER_DATE%TYPE;
UnknownSoldType exception;
-- Combining outcome from the two views in a single cursor
cursor sold_cursor is
SELECT bk.ISBN, bk.Title, bk.Publisher_Name, st.total_sold, sq.total_stock, shc.Order_date
FROM sold_today st, stock_quantity sq, shopping_cart shc, cart_contains cc, book bk
WHERE bk.ISBN = st.ISBN
AND st.ISBN = sq.ISBN
AND sq.ISBN = cc.ISBN
AND cc.Cartid = shc.Cartid
AND (shc.State='checked-out');
IndRec sold_cursor%ROWTYPE;
BEGIN
-- Todays date
select distinct sysdate INTO todaysDate from dual;
-- Printing reoprt's headder
dbms_output.put_line('====================================='||'=========================================');
dbms_output.put_line('|| ISBN | Title | Publisher | QUANTIY | QUANTITY ||');
dbms_output.put_line('|| | | | ORDERS | PURCHASE ||');
OPEN sold_cursor;
LOOP
FETCH sold_cursor INTO IndRec;
EXIT WHEN sold_cursor%NOTFOUND;
-- Date checking vs. stock quantity
               IF to_char(IndRec.order_date, 'ddmmyyyy') = to_char(todaysDate, 'ddmmyyyy') THEN
                    IF IndRec.total_sold > IndRec.total_stock THEN
                    -- Printing orders' report content!
dbms_output.put_line('====================================='||'=========================================');
reOrder := (IndRec.total_sold - IndRec.total_stock)*5;
dbms_output.put_line(' || ' || Lpad(IndRec.ISBN,10,10) || ' | ' ||Lpad(IndRec.Title,20,20) || ' | ' || Lpad(IndRec.Publisher_Name,10,10 )||' | ' ||to_Char(IndRec.total_sold, '9999') || ' | ' || to_Char(reOrder, '9999')|| ' ||');
                    END IF;
               END IF;
          END LOOP;
          CLOSE sold_cursor;
     dbms_output.put_line('====================================='||'=========================================');
          EXCEPTION
          when UnknownSoldType then
               dbms_output.put_line('=======================');
               dbms_output.put_line('ERROR: Aborting program.');
               dbms_output.put_line('Unknown Pay Type for Name');
          when others then
               dbms_output.put_line('ERROR During Processing. See the DBA.');
END;
END;
but this raises up my previous question: what is the
alternative for views, if there is a better one!
another question, if views is the best alternative in this case, is it possible to delete the temporary
tables created by views in each case???
thanking and apprecuiating your help & attention...
cheers..
k.s.

Similar Messages

  • HELP on simple query

    I am trying to run kodo under Tomcat. In order for the user to login I do a simple query:
    PersistenceManager pm = pmf.getPersistenceManager ();
    KodoQuery q = (KodoQuery) pm.newQuery (UserInfo.class, "username == u_name && password == p_word");
    q.setUnique(true);
    q.declareParameters("String u_name, String p_word");
    UserInfo u = (UserInfo) q.execute(u_name, p_word);
    pm.close ();
    if (u == null)
    return (0);
    else
    return (1);
    I get the following exception:
    Unable to execute a query on type "class com.login.UserInfo". This class or interface is not persistent, and does not have any persistent implementors.
    I can run a JDOQL query using the same class from the kodoworkbench and it works fine. What am I missing?

    I am trying to run kodo under Tomcat. In order for the user to login I do a simple query:
    PersistenceManager pm = pmf.getPersistenceManager ();
    KodoQuery q = (KodoQuery) pm.newQuery (UserInfo.class, "username == u_name && password == p_word");
    q.setUnique(true);
    q.declareParameters("String u_name, String p_word");
    UserInfo u = (UserInfo) q.execute(u_name, p_word);
    pm.close ();
    if (u == null)
    return (0);
    else
    return (1);
    I get the following exception:
    Unable to execute a query on type "class com.login.UserInfo". This class or interface is not persistent, and does not have any persistent implementors.
    I can run a JDOQL query using the same class from the kodoworkbench and it works fine. What am I missing?

  • Help understanding simple query trace with 35,000 "query subcube" events

    No matter WHAT query I issue against my cube, I'm finding thousands of query subcube events against an unexpected , I assume it's a partition.
    Even for the simplest possible query SELECT FROM <CUBE>, which for this cube would return the measure [MRN Distinct Count], a trace reveals 35,000 query subcube events against a partition (?) called "<server>.Medical Home.MedHome.Lab Orders
    With Results" which is NOT the partition that holds that [MRN Distinct Count] measure.
    I can't figure out why this object is being queried so many times for queries completely unrelated to it.  I believe this performance degradation is somewhat new...so I have been trying to think of what may have been added to the cube recently.
    I recently added KPIs and calculated sets & members that DO draw from that Lab Orders With Results object...would calculated members or KPI's cause this kind of problem? I thought that they were all pre-calculated @ processing?
    Thanks for any insight you can provide
    Here's a summary of the profiler trace on the query SELECT FROM <CUBE>
    Event Desc
    # of Events
    ObjectPath
    Duration
    Query Begin
    1
    NULL
    0
    Query Cube Begin
    1
    <server>.Medical Home.MedHome
    0
    Query Subcube Verbose
    11
    <server>.Medical Home.MedHome.Fact Dx 2
    189
    Query Dimension
    7
    <server>.Medical Home.Dim Person
    0
    Query Subcube Verbose
    35650
    <server>.Medical Home.MedHome.Lab Orders With Results
    13856
    Serialize Results Begin
    1
    <server>.Medical Home.MedHome
    0
    Serialize Results Current
    4
    <server>.Medical Home.MedHome
    0
    Query Subcube Verbose
    5
    <server>.Medical Home.MedHome.Dim Person
    0
    Serialize Results Current
    1
    <server>.Medical Home.MedHome
    0
    Serialize Results End
    1
    <server>.Medical Home.MedHome
    0
    Query Cube End
    1
    <server>.Medical Home.MedHome
    40919
    Query End
    1
    NULL
    41059
    Paul

    RedBirdRising - my cube had several dynamic calculated sets in it.  As I recall several of those sets included slices on that one particular dimension that was being queried so many times. For me it was sets that compiled populations of people
    with particular lab result values, so that lab result partition was queried thousands of times for ANY query, even simple ones like SELECT FROM [CUBE].  
    To be precise, I actually had calculated sets interacting with calculated measures - for example, one of the offending calculated sets was really this series of calculations:
    -CALC SET 1: define calculated set of diabetic patients
    -CALC MEASURE 1: define calculated measure for most recent lab test result of a particular lab test - which included a slice on the dimension I found being queried thousands of times.
    -DYNAMIC calculated set: FILTER(CALC SET1, CALC MEASURE 1 <= x)
    So as soon as I switched that dynamic set to a STATIC set my queries began executing in a reasonable amount of time and those query subcube events were no longer issued in the thousands.  I feel like i've heard that FILTER performs poorly but didn't
    know of any alternatives to achieve what we needed.
    hope this helps...I can't say I know for sure what unforseen impact(s) switching to static sets has had yet.  Dynamic seemed like the way to go but the performance hit was just too drastic.  
    Paul

  • Help with simple Query.

    I have 2 tables.  Table A and Table B
    Table A
    Client_ID
    Client_Name
    Table B
    Document_ID
    Client_ID
    Document_Name
    I need a SQL query that can return all Client Names and all of the Document Names that each client is missing.
    I have seen lots examples all over the web about returning Client Names from Table A that are missing from Table B, but nothing about returning the Document Names from Table B as well.
    RobA29

    >> Clients and Documents <<
    Why do you think that those are good table names? Why did you fail to write DDL? This is minimal Netiquette for 30+ years of SQL forums. 
    Each entity gets table: 
    CREATE TABLE Clients
    (client_id CHAR(10) NOT NULL PRIMARY KEY,
     client_name VARCHAR(35) NOT NULL);
    CREATE TABLE Documents
    (document_id CHAR(10) NOT NULL PRIMARY KEY,
     document_name VARCHAR(35) NOT NULL);
    Here is one guess (based on nothing you bothered to tell us) at the relationship: 
    CREATE TABLE Document_Assignments
    (client_id CHAR(10) NOT NULL
      REFERENCES Clients (client_id),
     document_id CHAR(10) NOT NULL
     REFERENCES Documents (document_id),
     PRIMARY KEY (document_id, client_id));
    This is n:m, but put in some UNIQUE constraints and you can get 1:n or m:1 or 1:1; do you know what those terms mean? Why don't you read any book on RDBMS over the holidays before you try to write SQL again? It will help a lot. 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Need Help with Simple Query

    Select deptno,sum(sal) from emp group by deptno order by deptno;
    This gives the below output
    Deptno Sum(Sal)
    10 8750
    20 10875
    30 9400
    But i need the Below Output
    10 20 30
    8750 10875 9400
    Help needed

    i tried with a example go around a glance and try it with yours
    CREATE TABLE CHIPTRUCK_SALES
    (LOCATION VARCHAR(20),
    DATE DATE,
    HOTDOGS_SOLD INT);
    INSERT INTO CHIPTRUCK_SALES VALUES
    ('Claremont', '1/1/2001', 10),
    ('Brougham', '1/1/2001', 20),
    ('Greenwood', '1/1/2001', 8),
    ('Whitevale', '1/1/2001', 5),
    ('Claremont', '1/2/2001', 11),
    ('Brougham', '1/2/2001', 22),
    ('Greenwood', '1/2/2001', 15),
    ('Whitevale', '1/2/2001', 17),
    ('Claremont', '1/3/2001', 8),
    ('Brougham', '1/3/2001', 19),
    ('Greenwood', '1/3/2001', 12),
    ('Whitevale', '1/3/2001', 7);
    SELECT
    LOCATION,
    MAX(CASE WHEN date = '1/1/2001' THEN hotdogs_sold END) AS "1/1/2001",
    MAX(CASE WHEN date = '1/2/2001' THEN hotdogs_sold END) AS "1/2/2001",
    MAX(CASE WHEN date = '1/3/2001' THEN hotdogs_sold END) AS "1/3/2001"
    FROM CHIPTRUCK_SALES GROUP BY LOCATION ORDER BY LOCATION;
    =>
    LOCATION 1/1/2001 1/2/2001 1/3/2001
    Brougham 20 22 19
    Claremont 10 11 8
    Greenwood 8 15 12
    Whitevale 5 17 7
    4 record(s) selected.

  • Help with a simple query

    Hi ,
    I'm running the following simple query in sql*plus on ORACLE9i. But this query stopped running after 30minutes, and the sql*plus die at the same time .I have no idea about this. Could somebody tell me how I can solve this problem. Thank you very much for your help.
    Select Distinct PERSADDRUSE. ADDRUSECD as "Application", PERS.PERSNBR as "Account",
    (PERS.FIRSTNAME || ' '|| PERS.MDLINIT ||' ' || PERS.LASTNAME ) as "Name1",' 'as "Name2",' 'as "Name3",
    AL1.TEXT as "Address1",AL2.TEXT as "Address2",AL3.TEXT as "Address3",
    (ADDR.CITYNAME ||' ' || ' '||ADDR.STATECD ||' '||ADDR.ZIPCD||' '|| ADDR.ZIPSUF) as "CityStateZip"
    From PERSADDRUSE
    Join PERS
    ON PERS.PERSNBR = PERSADDRUSE.PERSNBR
    --AND  PERS.ADDDATE = '12-JAN-2005'
    AND PERSADDRUSE.ADDRUSECD = 'PRI'
    join ADDR
    ON PERSADDRUSE.ADDRNBR = ADDR.ADDRNBR
    left JOIN ADDRLINE AL1
    ON ADDR.ADDRNBR = AL1.ADDRNBR
    AND AL1.LINENBR = 1
    left JOIN ADDRLINE AL2
    ON ADDR.ADDRNBR = AL2.ADDRNBR
    AND AL2.LINENBR = 2
    left JOIN ADDRLINE AL3
    ON ADDR.ADDRNBR = AL3.ADDRNBR
    AND AL3.LINENBR = 3;

    Thanks for reply. I have some other query running for 45m and it seems fine. The following are the explain plan I print out. I'm new to PL/SQL.Could you guys give me some other ideas?
    BMS_XPLAN.DISPLAY()(PLAN_TABLE_OUTPUT)
    PERSADDRUSE | 5726 | 68712 | 183 |'), DBMS_XPLAN_TYPE('| 8 | TABLE ACCESS FULL| PERS | 161K| 2839K| 431 |'), DBMS_XPLAN_TYPE('| 9 | TABLE ACCESS FULL | ADDR | 239K| 5145K| 298 |'), DBMS_XPLAN_TYPE('| 10 | TABLE ACCESS FULL | ADDRLINE | 82087 | 1683K| 240 |'), DBMS_XPLAN_TYPE('| 11 | TABLE ACCESS FULL | ADDRLINE | 82087 | 1683K| 240 |'), DBMS_XPLAN_TYPE('| 12 | TABLE ACCESS FULL | ADDRLINE | 82087 | 1683K| 240 |'), DBMS_XPLAN_TYPE('------------------------------------------------------------------------'), DBMS_XPLAN_TYPE(' '), DBMS_XPLAN_TYPE('Note: cpu costing is off, PLAN_TABLE'' is old version'))

  • [Help] statement.executeQuery(query) opens MULTIPLE cursors

    Hey everyone,
    I'm having a real hard time finding anything about this on the net so I've turned here. When we call:
    resultSet = statement.executeQuery(query)
    from a servlet for some reason that one executeQuery opens anywhere from 9-12 cursors in our oracle DB. All the executeQuery documentation I could find just said it should open 1 cursor for that particular ResultSet. query is a fairly simple SQL statement, it searches multiple tables but that doesn't explain why it should open so many cursors.
    On a side note the resultSet and statement are global to the method and are closed in the finally block, no SQLExceptions are thrown further adding to my confusion.
    If anyone has seen something like this where executing 1 query opens multiple cursors please let me know any information you might have.
    Thanks in advance
    -Dave

    Hi Dave
    I had a similar problem using the Oracle 8i, but my query was a more complicated than yours and opened a lot of cursors.
    The answer is to close every ResultSet and the Statement:
    while (xxResult.next()){ ... }
    xxResult.close();
    xxResult.getStatement().close();
    This worked for me,
    Good luck,
    Daniel.

  • Help! no response when doing SIMPLE query!

    I meet a strange problem when I do a SIMPLE query on a table in Oracle 8.1.7, just like:
    SELECT id FROM person WHERE id='12345';
    Most of id values are ok to the query, except some values.
    Whether I use these values in sqlplus or JDBC, mostly, no response is returned!! And I find the session in Oracle always keeps the status 'Active'. But in few scenario I can get the result quickly.
    I don't know the reason. Help me please!
    Thanks a lot!
    Meyor

    I'm not sure if the 'id' column contains something else.
    When I shutdown and restart the database, the problem seems to be "solved". If the problem reoccurs again, I will try to use xTRIM functions.
    Thanks!
    Meyor

  • Simple Query in Oracle Linked Table in MS Access causes full table scan.

    I am running a very simple query in MS ACCESS to a linked Oracle table as follows:
    Select *
    From EXPRESS_SERVICE_EVENTS --(the linked table name refers to EXPRESS.SERVICE_EVENTS)
    Where performed > MyDate()
    or
    Select *
    From EXPRESS_SERVICE_EVENTS --(the linked table name refers to EXPRESS.SERVICE_EVENTS)
    Where performed > [Forms]![MyForm]![Date1]
    We have over 50 machines and this query runs fine on over half of these, using an Oracle Index on the "performed" field. Running exactly the same thing on the other machines causes a full table scan, therefore ignoring the Index (all machines access the same Access DB).
    Strangely, if we write the query as follows:
    Select *
    From EXPRESS_SERVICE_EVENTS
    Where performed > #09/04/2009 08:00#
    it works fast everywhere!
    Any help on this 'phenominon' would be appreciated.
    Things we've done:
    Checked regional settings, ODBC driver settings, MS Access settings (as in Tools->Options), we have the latest XP and Office service packs, and re-linked all Access Tables on both the slow and fast machines independantly).

    Primarily, thanks gdarling for your reply. This solved our problem.
    Just a small note to those who may be using this thread.
    Although this might not be the reason, my PC had Oracle 9iR2 installed with Administratiev Tools, where user machines had the same thing installed but using Runtime Installation. For some reason, my PC did not have 'bind date' etc. as an option in the workarounds, but user machines did have this workaround option. Strangely, although I did not have the option, my (ODBC) query was running as expected, but user queries were not.
    When we set the workaround checkbox accordingly, the queries then run as expected (fast).
    Once again,
    Thanks

  • How to Use the Procedures in a Sql Query

    Hi Friends,
    Can anyone help me out whether can we use the procedure in the sql query..
    if yes help me out with an example
    my requirement is
    i have one sql query .. in which i need to use the procedure which returns multiple values... how can i overcome it,can anyone help me out for this..
    for your reference i am pasting the sql query
    SELECT paf.person_id
    FROM per_all_assignments_f paf START WITH paf.person_id = p_person_id
    AND paf.primary_flag = 'Y'
    AND paf.assignment_type IN('E', 'C')
    AND l_effective_date BETWEEN paf.effective_start_date
    AND paf.effective_end_date
    CONNECT BY PRIOR paf.supervisor_id = paf.person_id
    AND paf.primary_flag = 'Y'
    AND paf.assignment_type IN('E', 'C')
    AND l_effective_date BETWEEN paf.effective_start_date
    AND paf.effective_end_date
    and paf.person_id not in (>>>I HAVE TO USE THE PROCEDURE HERE<<<<);
    Thanks in advance

    We never saw your procedure, but maybe you could wrap it in a function
    SQL> create or replace procedure get_members(in_something IN number, out_members OUT sys_refcursor)
    is
    begin
      open out_members for
        'select level member_id from dual connect by level <= :num' using in_something;
    end get_members;
    Procedure created.
    SQL> create or replace type numbers as table of number;
    Type created.
    SQL> create or replace function members(in_something IN number)
    return numbers
    as
      member_cur sys_refcursor;
      members numbers;
    begin
      get_members(in_something, member_cur);
      fetch member_cur bulk collect into members;
      close member_cur;
      return members;
    end;
    Function created.
    SQL> select * from  table(members(4));
    COLUMN_VALUE
               1
               2
               3
               4
    4 rows selected.Variant on same using piplined function
    SQL> create or replace function members_piped(in_something IN number)
    return numbers pipelined
    as
      member_cur sys_refcursor;
      rec number;
    begin
      get_members(in_something, member_cur);
      loop
         fetch member_cur into rec;
         exit when member_cur%notfound;
         pipe row(rec);
      end loop;
      close member_cur;
      return;
    end;
    Function created.
    SQL> select * from  table(members_piped(4));
    COLUMN_VALUE
               1
               2
               3
               4
    4 rows selected.
    SQL> drop function members_piped;
    Function dropped.
    SQL> drop function members;
    Function dropped.
    SQL> drop type numbers;
    Type dropped.
    SQL> drop procedure get_members;
    Procedure droppedEdit:
    Sorry Blu, had not seen you already posted similar thing
    Edited by: Peter on Jan 27, 2011 5:38 AM

  • Error in the simple Query

    Dear Experts,
    Not able to Execute this simple query :
    Select T1.JobID , T1.BudgetValue,T1.ActualValue FROM [dbo].[Enprise_JobCost_ActualBudgetView] T1 WHERE T1.TransType = '[%0]'
    Regards

    Hello,
    View - A View in simple terms is a subset of a 'virtual table. It can be used to retrieve data from the tables, Insert, Update or Delete from the tables. The Results of using View are not permanently  stored in the database.
    Stored Procedure -  A stored procedure is a group of SQL statements which can be stored into the database and can be shared over the netwrok with different users.
    http://www.geekinterview.com/question_details/65914
    Better make a UDT for your requirement.
    Thanks
    Manvendra Singh Niranjan

  • A simple query to show sales versus last year on daily basis/

    Hi guys,
    I want to build a simple query with day (1,2,3,4,5,6) on the rows and "sales current year" and "sales last year"
    on the columns.
    I have only 0CALDAY in my cube.
    How can I have on the rows the day in stead of the full date?
    I would like to see in the sames row sales current year and sales last year.
    Thanks
    Shlomi

    HI Shlomi
    Create a virtual characteristic in your infoprovider that can calculate the day from calendar Day. In ZXRSRZZZ while adding code for this virtual characteristic use the function module DATE_COMPUTE_DAY to compute the day for every calendar day.
    For calculating Sales Current year, create a restricted ky figure with Sales as the key figure. Add 0CalDay to this RKF and create a variable for this infoobject(Eg: ZCURYEAR) that will receive input from the user for the range of dates eg: 08/16/2009 - 08/22/2009.
    For Sales Prior year, create another restricted key figure with Sales. Add 0CalDay to this RKF and add a customer exit variable. In the Customer exit code use the ZCURYEAR variable and offset it to prior year in both the upper and lower limits. This should work.
    I hope this helps.
    Thanks.

  • A simple  query

    a simple query
    on plsql block
    if i don't define the size of a variable of number type what will be the default size ?
    declare
    a number ;
    begin
    null
    end;
    and in a procedure if i don't mention in or out in the parameters what will oracle take it by default ?
    create or replace procedure(a number,b number)
    is
    begin
    null
    end;
    PLs note that both the pl/sql blocks are just for giving an idea .
    regards
    SHUBH

    You can get such information from the documents.
    [imp]The absence of precision and scale designators specifies the maximum range and precision for an Oracle number.[imp]
    Cheers
    Sarma.

  • Simple query takes time to run

    Hi,
    I have a simple query whcih takes about 20 mins to run.. here is the TKPROF forit:
      SELECT
        SY2.QBAC0,
        sum(decode(SALES_ORDER.SDCRCD,'USD', SALES_ORDER.SDAEXP,'CAD', SALES_ORDER.SDAEXP /1.0452))
      FROM
        JDE.F5542SY2  SY2,
        JDE.F42119  SALES_ORDER,
        JDE.F0116  SHIP_TO,
        JDE.F5542SY1  SY1,
       JDE.F4101  PRODUCT_INFO
    WHERE
        ( SHIP_TO.ALAN8=SALES_ORDER.SDSHAN  )
        AND  ( SY1.QANRAC=SY2.QBNRAC and SY1.QAOTCD=SY2.QBOTCD  )
        AND  ( PRODUCT_INFO.IMITM=SALES_ORDER.SDITM  )
        AND  ( SY2.QBSHAN=SALES_ORDER.SDSHAN  )
        AND  ( SALES_ORDER.SDLNTY NOT IN ('H ','HC','I ')  )
        AND  ( PRODUCT_INFO.IMSRP1 Not In ('   ','000','689')  )
        AND  ( SALES_ORDER.SDDCTO IN  ('CO','CR','SA','SF','SG','SP','SM','SO','SL','SR')  )
        AND  (
        ( SY1.QACTR=SHIP_TO.ALCTR  )
        AND  ( PRODUCT_INFO.IMSRP1=SY1.QASRP1  )
      GROUP BY
      SY2.QBAC0
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        1      0.07       0.07          0          0          0           0
    Execute      1      0.00       0.00          0          0          0           0
    Fetch       10     92.40     929.16     798689     838484          0         131
    total       12     92.48     929.24     798689     838484          0         131
    Misses in library cache during parse: 1
    Optimizer goal: CHOOSE
    Parsing user id: 62 
    Rows     Row Source Operation
        131  SORT GROUP BY
    3535506   HASH JOIN 
    4026100    HASH JOIN 
        922     TABLE ACCESS FULL OBJ#(187309)
    3454198     HASH JOIN 
      80065      INDEX FAST FULL SCAN OBJ#(30492) (object id 30492)
    3489670      HASH JOIN 
      65192       INDEX FAST FULL SCAN OBJ#(30457) (object id 30457)
    3489936       PARTITION RANGE ALL PARTITION: 1 9
    3489936        TABLE ACCESS FULL OBJ#(30530) PARTITION: 1 9
      97152    TABLE ACCESS FULL OBJ#(187308)
    OVERALL TOTALS FOR ALL NON-RECURSIVE STATEMENTS
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        1      0.07       0.07          0          0          0           0
    Execute      2      0.00       0.00          0          0          0           0
    Fetch       10     92.40     929.16     798689     838484          0         131
    total       13     92.48     929.24     798689     838484          0         131
    Misses in library cache during parse: 1kindly suggest how to resolve this...
    OS is windows and its 9i DB...
    Thanks

    > ... you want to get rid of the IN statements.
    They prevent Oracle from usering the index.
    SQL> create table mytable (id,num,description)
      2  as
      3   select level
      4        , case level
      5          when 0 then 0
      6          when 1 then 1
      7          else 2
      8          end
      9        , 'description ' || to_char(level)
    10     from dual
    11  connect by level <= 10000
    12  /
    Table created.
    SQL> create index i1 on mytable(num)
      2  /
    Index created.
    SQL> exec dbms_stats.gather_table_stats(user,'mytable')
    PL/SQL procedure successfully completed.
    SQL> set autotrace on explain
    SQL> select id
      2       , num
      3       , description
      4    from mytable
      5   where num in (0,1)
      6  /
                                        ID                                    NUM DESCRIPTION
                                         1                                      1 description 1
    1 row selected.
    Execution Plan
    Plan hash value: 2172953059
    | Id  | Operation                    | Name    | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT             |         |  5001 |   112K|     2   (0)| 00:00:01 |
    |   1 |  INLIST ITERATOR             |         |       |       |            |          |
    |   2 |   TABLE ACCESS BY INDEX ROWID| MYTABLE |  5001 |   112K|     2   (0)| 00:00:01 |
    |*  3 |    INDEX RANGE SCAN | I1      |  5001 |       |     1   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       3 - access("NUM"=0 OR "NUM"=1)Regards,
    Rob.

  • Best design for Boolean function from simple query

    Hello,
    what is the most efficient, shorter, readable, simple way to make a boolean function that simply return true or false from a simple query that return 0 or 1 to n records?
    Is this solution using a cursor's the best (working...):
       FUNCTION is_date_present (p_date IN DATE)
          RETURN BOOLEAN
       IS
          CURSOR chk_cursor
          IS
             SELECT COUNT (*)
               FROM target_dates
              WHERE target_date = p_date;
          nb   NUMBER := 0;
       BEGIN
          OPEN chk_cursor;
          FETCH chk_cursor
           INTO nb;
          CLOSE chk_cursor;
          IF nb >= 1
          THEN
             RETURN TRUE;
          ELSE
             RETURN FALSE;
          END IF;
       END;Performance, clarity and simplicity are important...
    Thanks

    Well, I prefer (not tested):
    FUNCTION is_date_present (p_date IN DATE)
    RETURN BOOLEAN
    IS
    nb NUMBER := 0;
    BEGIN
    SELECT COUNT (*)
    INTO nb
    FROM target_dates
    WHERE target_date = p_date;
    IF nb >= 1 THEN
    RETURN TRUE;
    LSE
    RETURN FALSE;
    IF;
    END;Regards,
    MiguelWhy count multiple records when you only care if you get at least 1 occurrence? Just wasted cycles.
    FUNCTION is_date_present (p_date IN DATE)
    RETURN BOOLEAN
    IS
    nb NUMBER := 0;
    BEGIN
      SELECT COUNT (*)
      INTO nb
      FROM DUAL
      WHERE EXISTS
          SELECT NULL 
          FROM target_dates
          WHERE target_date = p_date
      IF nb >= 1 THEN
         RETURN TRUE;
      ELSE
         RETURN FALSE;
      END IF;
    END;Or you could just add a ROWNUM = 1 on to yours, either way.

Maybe you are looking for