Problem with SELECT INTO Query

Why am I always getting 0 for returnvalue in the following query?
create or replace
PACKAGE BODY MyPKG AS
PROCEDURE SelectCount
   returnvalue       OUT      INTEGER
AS
  BEGIN
select COUNT(*) from MyTable into returnvalue;
IF( SQL%ROWCOUNT >= 1 )
  THEN
    returnvalue := 1;
  ELSE
    returnvalue := 0;
  END IF; 
dbms_output.put_line('returnvalue: ' || returnvalue);
END SelectCount;
END MyPKG ;

Hi,
When you use an aggregate function, such as COUNT, without a GROUP BY clause, then the query is guaranteed to return exactly 1 row, regadless of whether there are any rows in the table or not.
Perhaps you meant:
create or replace
PACKAGE BODY MyPKG AS
PROCEDURE SelectCount
   returnvalue       OUT      INTEGER
AS
  BEGIN
      select COUNT(*) from MyTable into returnvalue;
      dbms_output.put_line('returnvalue: ' || returnvalue);
  END SelectCount;
END MyPKG ;
that is, simply lose the IF block.

Similar Messages

  • OnChanger="get_ajax_select_xml(this);" with  select list (query named LOV)

    Hello,
    i used Vikas'example Re: cascading lov for tabular form
    i have a problem with Select list (query based LOV)
    when run tabular form i have the following error:
    report error:
    ORA-06502: PL/SQL: numeric or value error: character string buffer too small
    the number of rows of the Lov are 900
    the display variable is 70 char
    is there any limit?
    Thank in advance
    Costanti

    Leo,
    Thanks for the response, but I don't think you quite understand my problem. If I go to the Column Attributes screen for the group_id field, I have the "Display As" drop down set to "Select List (query based LOV)", not "Select List (named LOV)". This requires that the sql query be written in the "List of values definition" text area below. Within that text area I have the following query:
    SELECT DISPLAY_NAME, GROUP_ID
    FROM APPLICATION_GROUPS
    WHERE APP_ID = ?????
    ORDER BY 1
    The APP_ID that I need to reference is for the current row of data that is being processed. Therefore, I can't use a :PNNN_APP_ID variable, because that field does not exist on the page.
    Hopefully this explains it a little better.
    Thanks,
    Kris

  • Problem with "SELECT...FOR UPDATE OF..." and "POST command" combination

    Problem with "SELECT...FOR UPDATE OF..." and "POST command" combination
    Problem in committing transactions in Multiple Forms (Oracle Forms) with POST built-in command:
    Consider that the following statements are written in WHEN-WINDOW-CLOSED trigger of a called form.
    Statements in called form (Form name: FORM_CHILD):
    go_block('display_block') ;
    do_key('execute_query') ;
    -- Data from table_b will be populated in this block, based on the value of COLUMN_1 obtained
    -- from TABLE_A.
    -- Example: If the value of COLUMN_1 is 10, then all the matching records from TABLE_B, which
    -- are inserted with value 10 in TABLE_B.COLUMN_1 will be fetched and shown here.
    if user_choice = 'YES' then
    commit ;
    else
    rollback ;
    end if ;
    Statements in calling forms:
    There are two calling forms having following statements and it is going to call the above said called form.
    CALLING FORM 1
    Statements in KEY-COMMIT trigger:
    post;
    call_form(form_child, no_activate) ;
    Statements in ON-INSERT trigger:
    select column_1
    from table_a
    for update of column_1
    where column_2 = 'X' ;
    update table_a
    set column_1 = column_1 + 1
    where column_2 = 'X' ;
    insert into table_b ...;
    insert into table_b ...; Statements in KEY-COMMIT trigger:
    post;
    call_form(form_child, no_activate) ;
    CALLING FORM 2:
    Statements in ON-INSERT trigger:
    select column_1
    from table_a
    for update of column_1
    where column_2 = 'X' ;
    update table_a
    set column_1 = column_1 + 1
    where column_2 = 'X' ;
    insert into table_b ...;
    insert into table_b ...;
    insert into table_b ...;
    Our understanding:
    Assume that both the forms are running from two different machines/instances, issuing commit at the same time. In this case, forms will start executing the statements written in ON-INSERT trigger, the moment POST command is executed. Though the commit is issued at the same time, according to oracle, only one of the request will be taken for processing first. Assume that calling form 1 is getting processed first.
    So, it fetches the value available in COLUMN_1 of TABLE_A and locks the row from further select, update, etc. as SELECT...FOR UPDATE command is used (note that NOWAIT is not given, hence the lock will be released only when COMMIT or ROLLBACK happens) and proceed executing further INSERT statements. Because of the lock provided by the SELECT...FOR UPDATE command, the statements in calling form 2 will wait for the resource.
    After executing the INSERT statements, the FORM_CHILD is called. The rows inserted in to TABLE_A will be queried and shown. The database changes will be committed when user closes the window (as COMMIT is issued in its WHEN-WINDOW-CLOSED trigger). Then the SELECT...FOR UPDATE lock will be released and calling form 2's statements will be executed.
    Actual happenings or Mis-behavior:
    Calling form 2 starts executing INSERT statements instead of waiting for SELECT...FOR UPDATE lock. Also, the value selected from TABLE_A.COLUMN_1 is same in both the calling forms, which is wrong.
    The rows inserted into TABLE_B are having similar COLUMN_1 values in calling form 2 and they are fetched and shown in the called form FORM_CHILD.
    Note that in calling form 2 also POST only is issued, but the changes posted there are accessible in calling form 1 also, which is wrong.
    Kindly suggest us as to how to fix above problem. It will be much use, if you can send us the information regarding the behavior of Oracle Forms POST built-in also.
    Our mail ID: [email protected]
    Thanks a lot in advance.

    You have several problems:
    1. On-Insert will ONLY run if you have created a new record in a base-table block. If you haven't done that, then the POST command will not cause it to run.
    2. Select for update without a "no wait" will lock records for the first form, but when the second form tries this, it will hit the ORA-00054 exception, and will NOT wait. The only way you could make it wait is to issue an UPDATE sql command, which is not such a good way to go.
    All POST does is issues SQL insert or update commands for any changes the user has made to records in a form's base-table blocks, without following with a Commit command.
    Also understand that Commit is the same as Commit_Form, and Rollback is the same as Clear_Form. You should read up on these in the Forms help topics.

  • Dynamic Pivot with Select Into

    I have this Dynamic Pivot which works fine.
    DECLARE @query VARCHAR(4000)
    DECLARE @years VARCHAR(2000)
    SELECT @years = STUFF(( SELECT DISTINCT'],[' + [factor_label]
    FROM [TEMP_lacp_factors]
    ORDER BY '],[' + [factor_label]
    FOR XML PATH('')
    ), 1, 2, '') + ']'
    SET @query =
    'SELECT * FROM
    SELECT [date_],[issue_id],[cusip],[Factor_value],[factor_label]
    FROM [TEMP_lacp_factors]
    )t
    PIVOT (MAX([factor_value]) FOR [factor_label]
    IN ('+@years+')) AS pvt'
    EXECUTE (@query)
    I'm trying to take the results of that and do a SELECT INTO, so I can move the results to another table.  Is this possible?  I didn't find a whole lot online.
    The error that I'm getting is this.
    Caused by: Column name or number of supplied values does not match table definition.
    How can I do this?  Is it even possible?
    Knowledge is the only thing that I can give you, and still retain, and we are both better off for it.

    Sure, you can create a table with SELECT INTO, but it cannot be a #temptable. Well, it can be a #temptable, but it will disappear as soon as you exit the scope it was created it, that is the dynamic SQL.
    The question is only, what would you do with this table later? Since you don't know the column names, about all work will have to be done through dynamic SQL.
    A dynamic pivot is a non-relational operation. A SELECT statement produces a table, and a table describes a distinct entity, of which the column are distinct and well-defined attributes. Something which your dynamic pivot does not adhere to.
    There is only one thing you can do with your dynamic pivot: returning the data to the client. I don't know what you want to do with that table, but probably you should do that manipulation before the dynamic pivot, because as I said: that is always your
    last step.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Problem with selecting text in Adobe Reader XI

    Hi all, I am encountering a problem with Adobe Reader XI and it is very strange I could not find an alike issue on the internet so I guess I have to submit a question with it.
    So here it is, I am using Adobe Reader XI Version 11.0.2, operating system: Windows 7. I do not know it starts from when but it has the problem with selecting text - to be copied in pdf documents. I ensure that the documents are not scanned documents but word-based documents (or whatever you call it, sorry I cannot think of a proper name for it).
    Normally, you will select the text/paragraph you want to copy and the text/paragraph will be highlighted, but the problem in this case that I cannot select the text/paragraph, the blinking pointer (| <-- blinking pointer) will just stays at the same location so I cannot select/highlight anything to be copied. It happens oftenly, not all the time but 90%.
    This is very annoying as my work involves very much with copying text from pdf documents, I have to close the pdf file and then open it again so I can select the text but then after the first copying or second (if I am lucky), the problem happens again. For a few text I have to type it myself, for a paragraph I have to close all opening pdf documents and open again so I could select the paragraph to copy. I ran out of my patience for this, it causes trouble and extra time for me just to copying those texts from pdf documents. Does this problem happen to anyone and do you have a solution for this? I would much appreciate if you could help me out, thank you!

    Yeah,  I totally agree, this is very strange. I have always been using Adobe Reader but this problem only occurred ~three months ago. It must be that some software newly installed I think. But I have no idea.
    About your additional question, after selecting the texts and Ctrl + C, the texts are copied and nothing strange happens. It's just that right after I managed to copy the texts, it takes me a while to be able to select the texts again. For your information, I just tested to select the texts and then pressed Ctrl, the problem happened. And then I tried pressing C and then others letters, it all led to the problem.
    I guess I have to stick with left-clicked + Copy until I/someone figure the source of this problem. Thanks a lot for your help!

  • Problem with:  select 'c' as X from dual

    Problem with 'select 'c' as X from dual'
    I get 2 different results when I execute the above with SQLPlus (or java) depending on the instance I am connected to. For one instance the result is a single character and for the other the character is padded with blanks to 32 chars in the SQLPlus window (and java). Does anyone know what database setting causes this to happen? Is it a version issue ?
    Test #1: Oracle 9.2.0.6 - SQLPlus result is padded with blanks
    SQL*Plus: Release 9.2.0.1.0 - Production on Mon Dec 10 09:27:58 2007
    Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.
    Connected to:
    Oracle9i Enterprise Edition Release 9.2.0.6.0 - 64bit Production
    With the Partitioning option
    JServer Release 9.2.0.6.0 - Production
    SQL> select 'c' as X from dual;
    X
    c
    SQL>
    Test #2 Oracle 9.2.0.1 SQLPlus result is a single character.
    SQL*Plus: Release 9.2.0.1.0 - Production on Mon Dec 10 09:29:27 2007
    Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.
    Connected to:
    Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.1.0 - Production
    SQL> select 'c' as X from dual;
    X
    c
    SQL>

    Using 9.2.0.6 On AIX 5.2 I get the single byte result:
    UT1 > select 'c' as X from dual;
    X
    c
    If the databases are on different Oracle Homes you may want to check the sqlplus global logon files for any set commands.
    If you executed the two sql statements from different OS directories you may also want to check your sqlpath for sqlplus .logon files.
    Try issueing clear columns and repeating the statement. Are the results the same?
    HTH -- Mark D Powell --

  • Problems with Input Ready Query

    Hello All,
    I'm facing problems with input ready query for BI IP.
    I've created the input query on aggregation level and maintianed all the planning settings.  It is not allowing me to edit, when i'm attaching in the web template.
    I also attached a button copy function, and i'm able to execute it and save it, but it not allowing me to change manually.
    I also enabled the 3rd option for keyfigures...data can be changed with planning functions and user input.
    Please help me in this regard.
    We have just started the development of BI-IP, please suggest me if there are any notes to be applied.
    Regards
    Kumar

    Hello Johannes,
    Yes I've set to the finest granularity...even if it is Only one characteristic and one key figure without any restrictions...
    I've checked even planning tab page under properties...it is also fine..
    But still it is not allaowing me to go to edit mode...this is a fresh instalation and the query i'm working is the first one...
    Please suggest me if there are any notes to be applied, we are on Support Pack 10.
    Regards
    Jeevan Kumar

  • Problem with select query in search

    Hi,
    Here i am using MYSQL database and when i am insertind date to database it is saving like  '2009-11-10 00:00:00'  and when i used to dispaly this in dateformat as '11/10/2009' .
    here is the problem occurs , when i write a search query as
    select recruitername,interviewdate ,skillset
                 from details
                  where interviewdate = #form.interviewdate#
    i am getting problem with date . would u please help me how to solve this issue .

    Try to use DateFormat
    select recruitername,interviewdate ,skillset
                 from details
                  where interviewdate = #DateFormat(form.interviewdate, "yyyy-dd-mm")#

  • Problem with select query inside a function.

    Hi,
    i have created a function as
    create or replace function "NEW"
    (emp in number,
    s_date in DATE,
    e_date in DATE)
    return number
    is
    v_alo number default 0;
    v_alo2 number default 0;
    v_date date;
    begin
    select sum(allocation_percent) into v_alo from employeeproject where start_date < s_date and end_date > e_date and pid != 'BPDE-KER12' and employee_id = emp;
    select allocation_percent into v_alo2 from employeeproject where start_date < s_date and end_date > e_date and pid = 'BPDE-KER12' and employee_id = emp;
    select max(end_date) into v_date from employeeproject where employee_id=emp having max(end_date) <= S_DATE;
    if v_alo < 100 then
    return 1;
    else if v_alo2 = 100 then
    return 2;
    else if v_date < s_date then
    return 3;
    else
    return 4;
    end if;
    end if;
    end if;
    exception
    when NO_DATA_FOUND then
    return 5;
    end;it is compiled correctly.
    when executing the function with
    select abc.a,new(a,'03-jan-2011','04-jan-2011') "status" from abc where new(a,'03-jan-2011','04-jan-2011') in (1,2,3,4);it is returning
    A status
    1 5
    2 5
    3 5
    instead of
    A status
    1 1
    2 2
    3 3
    and when i comment any two select statements then some part of my ans is correct.
    unable to understand the behaviour.
    can any pls help me understand it.
    Thanks,
    hari

    Hi,
    thanks for the reply, and sorry for my ugly code.
    i am using Oracle database 10g express edition.
    Case could be a option to use but i need to figure why my query is not returning any value when used together.
    my requirement is to find
    the employees who are have allocation percent sum < 100 for a defined period(excluding pid=BPDE-KER12) and
    employee who is mapped to pid=BPDE-KER12 not in my first requirement in that period and
    the employees whose latest end date is less than the new start date.
    i have tried the new modified code as you said but this time it returns null, not even exceptions running.
    i divide my requirement into three functions which will return value.
    1.  create or replace function "NEW4"
    (emp in number,
    s_date in DATE,
    e_date in DATE)
    return number
    is
    v_alo number default 0;
    v_alo2 number default 0;
    v_date date;
    begin
    --to check if the employee total percentage is <100 then return 1 else return 4
    select sum(allocation_percent) into v_alo from pm_employee_project
    where
    start_date < s_date and end_date > e_date and pid !='BPDE-KER12' and employee_id = emp;
    if v_alo < 100 then
    return 1;
    elsif v_alo2 = 100 then
    return 2;
    elsif v_date < s_date then
    return 3;
    else
    return 4;
    end if;
    exception
    when NO_DATA_FOUND then
    return 5;
    end;
    then,
    select abc.a,NEW4(a,'03-jan-2011','30-jan-2011') "STATUS" from abc
    result,
    A STATUS
    1 *1*
    2 4
    3 4 2.create or replace function "NEW5"
    (emp in number,
    s_date in DATE,
    e_date in DATE)
    return number
    is
    v_alo number default 0;
    v_alo2 number default 0;
    v_date date;
    begin
    --To select employee who are in a specific pid.
    select allocation_percent into v_alo2 from pm_employee_project where
    start_date < s_date and end_date > e_date and pid = 'BPDE-KER12' and
    employee_id = emp;
    if v_alo2 = 100 then
    return 2;
    elsif v_alo < 100 then
    return 1;
    elsif v_date < s_date then
    return 3;
    else
    return 4;
    end if;
    exception
    when NO_DATA_FOUND then
    return 5;
    end;
    then,
    select abc.a,NEW5(a,'03-jan-2011','30-jan-2011') "STATUS" from abc
    Result,
    A STATUS
    1 5
    2 *2*
    3 5 3.   create or replace function "NEW6"
    (emp in number,
    s_date in DATE,
    e_date in DATE)
    return number
    is
    v_alo number default 0;
    v_alo2 number default 0;
    v_date date;
    begin
    --to select the employee whose project end date is less thann the new date.
    select max(end_date) into v_date from pm_employee_project where
    employee_id=emp having max(end_date) <= S_DATE;
    if v_alo2 = 100 then
    return 2;
    elsif v_alo = 100 then
    return 1;
    elsif v_date < s_date then
    return 3;
    else
    return 4;
    end if;
    exception
    when NO_DATA_FOUND then
    return 5;
    end;
    then,
    select abc.a,NEW6(a,'03-jan-2011','30-jan-2011') "STATUS" from abc
    Result,
    A STATUS
    1 5
    2 5
    3 *3* so my function works properly individually, but i want all the three conditions in a single function with same order as above 1 then 2 and then 3.
    and when i try to do it that way i am not getting my result as
    A STATUS
    1 *1*
    2 *2*
    3 *3*
    so how can i proceed.
    my input table values,
    select * from abc
    A B C
    1 2 2
    2 1 3
    3 1 2
    select * from pm_employee_project
    varchar2 varchar2 date date date varchar2
    EMPLOYEE_ID PID START_DATE END_DATE ALLOCATION_PERCENT SUPERVISOR_ID
    1 10 02-JAN-11 31-JAN-11 89 -
    1 20 05-JAN-11 20-JAN-11 9 -
    1 BPDE-KER12 21-JAN-11 31-JAN-11 11 -
    2 BPDE-KER12 01-JAN-11 31-JAN-11 100 -
    3 30 01-JAN-10 01-JAN-11 100

  • Case with select into and sub query

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

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

  • Performance problem with selecting records from BSEG and KONV

    Hi,
    I am having performance problem while  selecting records from BSEG and KONV table. As these two tables have large amount of data , they are taking lot of time . Can anyone help me in improving the performance . Thanks in advance .
    Regards,
    Prashant

    Hi,
    Some steps to improve performance
    SOME STEPS USED TO IMPROVE UR PERFORMANCE:
    1. Avoid using SELECT...ENDSELECT... construct and use SELECT ... INTO TABLE.
    2. Use WHERE clause in your SELECT statement to restrict the volume of data retrieved.
    3. Design your Query to Use as much index fields as possible from left to right in your WHERE statement
    4. Use FOR ALL ENTRIES in your SELECT statement to retrieve the matching records at one shot.
    5. Avoid using nested SELECT statement SELECT within LOOPs.
    6. Avoid using INTO CORRESPONDING FIELDS OF TABLE. Instead use INTO TABLE.
    7. Avoid using SELECT * and Select only the required fields from the table.
    8. Avoid nested loops when working with large internal tables.
    9. Use assign instead of into in LOOPs for table types with large work areas
    10. When in doubt call transaction SE30 and use the examples and check your code
    11. Whenever using READ TABLE use BINARY SEARCH addition to speed up the search. Be sure to sort the internal table before binary search. This is a general thumb rule but typically if you are sure that the data in internal table is less than 200 entries you need not do SORT and use BINARY SEARCH since this is an overhead in performance.
    12. Use "CHECK" instead of IF/ENDIF whenever possible.
    13. Use "CASE" instead of IF/ENDIF whenever possible.
    14. Use "MOVE" with individual variable/field moves instead of "MOVE-
    CORRESPONDING" creates more coding but is more effcient.

  • Problem with SELECT WHERE IN

    I'm having a problem with a SELECT clause...
    the variables...
    <cfset MyString=#getProducts.matches_with#>
    <cfset myArrayList = ListToArray(MyString)>
    the query...
    SELECT *
    FROM pricelist
    WHERE supplier_code IN ('#myArrayList[1]#' , '#myArrayList[2]#')
    The problem is, the select clause is only ever retrieving one row, despite their being several matches
    The clause works fine when I change the WHERE line to
    WHERE supplier_code IN ('E1775' , 'R1771')
    What am I doing wrong here ?

    Just wanted to say thanks all for the advice - I'm back on track now.
    As you know I had a field 'matches_with' in the merchandise table which contains a comma separated list, which I now accept is bad design.
    I wrote the following code to take each field and put it into a new table called matches_with, which contains two fields
    product_code , matches_with_product_code. All done.
    <cfloop query="getData">
        <!--- create an array based on the csv list of items in matches_with field --->
        <cfset myArray = ListToArray(#getData.matches_with#)>
         <!--- skip if no items in array --->   
        <cfif #ArrayLen(myArray)# gt 0>
            <!--- loop through item in the array --->
            <cfloop from="1" to="#ArrayLen(myArray)#" index="i">
                <cfquery name="insert" datasource="foo">
                    <!--- insert each array item into SQL table --->
                    INSERT INTO 00_matches_with (product_code, matches_with_product_code)
                    VALUES ('#getData.product_code#' , '#myArray[i]#')
                </cfquery>
            </cfloop>
        </cfif>
    </cfloop>

  • Problem with timestamp in query

    I have problem with timestamp in JPA query.
    I wonna select all data from database where difference between two timestamps is more than 3 month.
    Database:
    ID timestamp1 timestamp2
    1 20008-11-19 15:02000 20008-08-19 15:02000
    2 20008-11-19 15:02000 20008-11-14 15:02000
    @Column(name = "timestamp1", nullable = false)
    @Temporal(TemporalType.TIMESTAMP)
    public Date timestamp1;
    @Column(name = "timestamp2", nullable = false)
    @Temporal(TemporalType.TIMESTAMP)
    public Date timestamp2;
    sql query works:
    select id from table where
    MONTH( DATE(timestamp1) - DATE(timestamp2) ) > 3
    but how I can write in Java?
    I't doesnt wrk:
    Query query = em.createQuery("SELECT f.id FROM Foo f WHERE MONTH( DATE(f.timestamp1) - DATE(f.timestamp2) ) > 3 ")
    error:
    ExceptionUtil E CNTR0020E: EJB threw an unexpected (non-declared) exception during invocation of method .
    Exception data: <openjpa-1.0.2-r420667:627158 nonfatal user error> org.apache.openjpa.persistence.ArgumentException: An error occurred while parsing the query filter 'SELECT f.id FROM Foo f WHERE MONTH( DATE(f.timestamp1) - DATE(f.timestamp2) ) > 3'.
    Error message: <openjpa-1.0.2-r420667:627158 nonfatal user error> org.apache.openjpa.kernel.jpql.ParseException: Encountered "MONTH (" at character 438, but expected: ["(", "+", "-", ".", ":", "", "=", "?", "ABS", "ALL", "AND", "ANY", "AS", "ASC", "AVG", "BETWEEN", "BOTH", "BY", "CONCAT", "COUNT", "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "DELETE", "DESC", "DISTINCT", "EMPTY", "ESCAPE", "EXISTS", "FETCH", "FROM", "GROUP", "HAVING", "IN", "INNER", "IS", "JOIN", "LEADING", "LEFT", "LENGTH", "LIKE", "LOCATE", "LOWER", "MAX", "MEMBER", "MIN", "MOD", "NEW", "NOT", "NULL", "OBJECT", "OF", "OR", "ORDER", "OUTER", "SELECT", "SET", "SIZE", "SOME", "SQRT", "SUBSTRING", "SUM", "TRAILING", "TRIM", "UPDATE", "UPPER", "WHERE", <BOOLEAN_LITERAL>, <DECIMAL_LITERAL>, <IDENTIFIER>, <INTEGER_LITERAL>, <STRING_LITERAL>].
    at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder$ParsedJPQL.parse(JPQLExpressionBuilder.java:1665)
    at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder$ParsedJPQL.<init>(JPQLExpressionBuilder.java:1645)

    The error is indocating improper formatting of your JPQL string. MONTH is not understood. I would recommend using your SQL string in a createNativeQuery(...) call instead.
    Doug

  • Problem with unit in Query

    Hallo Experts,
    We encounter a problem with unit in our Query.
    Szenario:
    We use the Unit like PC, SET in Query.
    In Table T006 those Units have value 0 in the field ANDEC, so they will be rounded up and rounded down in Query.
    Our Problem is some Queries need the rounding up and down but others don't need this function.
    Where and how should we change to solve the problem.
    thanks & Best regards

    hi,
    if you want to control the rounding off while unit conversion you can do it from SPRO
    In the BW system, goto SPRO -> SAP NetWeaver -> General Settings -> Check Units of Measurement -> Units of Measurement -> Choose the unit corresponding to 'KM' -> Click on 'Details' button in the toolbar.
    Look the field 'Decimal Pl rounding'. Change this to 3 or whatever value you choose and see if it works.
    in above link i have taken example of KM, you need need to select the required unit.
    let us know if this is solves your problem. I am not sure if this can be done for individual queries but this is controlled by UOM wise as mentioned above.
    Regards,
    Rk.

  • Performance Problem While Selecting a Query....

    Hi Users
    I have problem with performance with appliction
    where are using D2K frent end and backend oracle 9i
    we have a validaion buttion that is taking lot of time to check the date like 500 records
    i want some links about performance issue process pls help.
    Here some of the query taking more than 1sec to more
    1)
    SELECT      
    /*+(INDEX(KBS_CHKSHTCARDTB(IND1_CHKSHTCARD))*/
    COUNT(DISTINCT A.KBCK_CHKSHEET_NO)
    FROM     
    KBS_CHKSHTCARDTB A ,KBS_CHKSHTHDRTB B                              WHERE A.KBCK_CHKSHEET_NO=B.KBCH_CHKSHEET_NO          
    AND KBCK_E_DATE =TRUNC(SYSDATE)
    AND KBCH_PRINT_STATUS='P'     
    OutPut: 206
    Time : 1sec
    2)
    UPDATE KBS_CARDMASTERTB
    SET KBCM_LOCK_FROM = KBCM_LOCK_FROM_CONTROL,
    KBCM_LOCK_STATUS= NULL
         WHERE KBCM_LOCK_FROM_CONTROL is not null
         and KBCM_LOCK_FROM IS NULL
         and KBCM_LOCK_FROM_CONTROL <=trunc(sysdate)      
         AND KBCM_LOCK_STATUS = 'Y'
    and KBCM_UNIQUE_IDNO IN(SELECT DISTINCT KBSA_UNIQUE_IDNO
    FROM KBS_SCANTB WHERE TRUNC(KBSA_E_DATE)      = TRUNC(:KANBAN_CTRL_BLK.DAT)
    AND KBSA_TRUCK_SQ_NO           = :Kanban_ctrl_blk.cycl
    AND KBSA_ERROR_CODE      IS NULL)
    AND (KBCM_VENDOR_NO,KBCM_PLANT_CODE)in (SELECT DISTINCT kbsa_vendor_no,KBSA_PLANT_CODE
    FROM KBS_SCANTB      WHERE TRUNC(KBSA_E_DATE)      = TRUNC(:KANBAN_CTRL_BLK.DAT)           AND KBSA_TRUCK_SQ_NO = :Kanban_ctrl_blk.cycl AND KBSA_ERROR_CODE      IS NULL)
    AND KBCM_PROCESS_CODE IN (SELECT DISTINCT KBSA_PROCESS_CODE
    FROM KBS_SCANTB                                              WHERE TRUNC(KBSA_E_DATE)      = TRUNC(:KANBAN_CTRL_BLK.DAT) AND KBSA_TRUCK_SQ_NO = :Kanban_ctrl_blk.cycl
    AND KBSA_ERROR_CODE      IS NULL);
    OutPut: Totatl Number of Table:29288
    Time : more than     5sec
    3)
    CURSOR GET_TEMP_CARDS_SWIPED_CUR IS
         SELECT KBCM_VENDOR_NO
                        ,KBCM_PLANT_CODE
                        ,KBCM_FAMILY --ADDED BY SUJITH.C TO SUPPORT PSMS2
                        ,KBCM_BACK_NO
                        ,KBCM_UNIQUE_IDNO
                        ,KBCM_KANBAN_TYPE
         FROM KBS_CARDMASTERTB
         WHERE KBCM_KANBAN_TYPE IN ('T','B')
         AND KBCM_UNIQUE_IDNO IN
    (SELECT KBSA_UNIQUE_IDNO
    FROM          KBS_SCANTB
    WHERE KBSA_E_DATE                = :DAT
    AND          KBSA_TRUCK_SQ_NO      = :CYCL
    AND KBSA_ERROR_CODE      IS NULL
    AND KBSA_TYPE IS NULL);
    Thanks Advance ........

    [When your query takes too long...|http://forums.oracle.com/forums/thread.jspa?messageID=1812597#1812597]
    [How to post a SQL statement tuning request|http://forums.oracle.com/forums/thread.jspa?threadID=863295&tstart=0]

Maybe you are looking for

  • How to back up my iTunes library when it's on an external HD?

    I just purchased a MacBook Air and am busy transferring all of my data to the new computer.  It appears I will not have room to keep my iMovie Library and my iTunes library on the Air itself..so I've gotten an external HD to use for that purpose.  I

  • Aborted due to lack of required utility

    When attempting to execute any jobs from DB13, we are getting an error message indicating "Aborted due to lack of required utility". This is a new system which was copied from another system where DB13 jobs execute successfully. Has anyone encountere

  • Change name of publishedcollection when creating or editing

    I need to change the name of the publishcollection when the collection is created or edited. This is to make sure the collection name matchs the name of the one on the remote server. I have tried the following code and it executes ok, but in the end

  • How to eliminate unwanted popup email address suggestions?

    I have a overage of suggested addresses when sending email  How can I eliminate one or more?

  • MM and BOM

    Hi, I have a doubt in MM and BOM, If I have a material A and this one is sometimes In House and sometimes is in Subcontract, can I have 2 BOM´s and choose in some field in MM. Material A= C+ B Material A: MM->F/SM->BOM 1->IR Material A:MM -> E(In hou