A somewhat more complex use of EXECUTE_QUERY with a Where clause...

Basically, what I need to be able to do is when the form receives a certain parameter upon opening; it must immediately run a certain query and populate the data blocks.
I do understand the concept of setting the DEFAULT_WHERE in the PRE_QUERY trigger for the block; but I don't think this will work in my situation.
The reason being is that each data block must run 2 separate queries; and BOTH resulting queries must be populated to each data block, and not overwrite eachother...
Not only that, but the query being executed requires me to reference 2 separate tables (the data coming from one, however its comparing results from 2 separate tables, so I don't think simply modifying the where clause for the data block will even be possible to achieve the results I am looking for.
Maybe further explanation of my queries may help the situation. Basically, each data block is linked to a table for the current logged in user, and then there is a production table as well. When ANYTHING is modified, added, or deleted on the current user's table, they are suppose to "publish" the record to the production table. The EXECUTE_QUERY statement will be responsible for running the query that will populate ALL the records that have yet to be published to the production table. So basically, its running a query that will use an ID and compare each individual field by that ID for any changes from the production table. Then, it runs another query to find records that are in either the production table or user table, and not the other; to flag a new record or deleted record.
I've been thinking about possible ways to do this, but have had no luck unfortunately;
ANY guidance will be greatly appreciated it. I do understand that my description of the problem may be hard to comprehend, so if you need further clarification please ask.
Jason
Message was edited by:
user558647

It would be helpful to give an example of the sort of data in each table and what you want to show in each block. I probably didn't understand most of what you wrote but I think the following may be analogous to your situation and requirements (but you'll have more columns of course):
SQL> CREATE TABLE t_user AS
  2    SELECT
  3      ROWNUM id,
  4      object_name col1,
  5      object_type col2
  6    FROM all_objects
  7    WHERE ROWNUM < 10;
Table created.
SQL>
SQL> DELETE FROM t_user WHERE id = 1;
1 row deleted.
SQL>
SQL> CREATE TABLE t_published AS
  2    SELECT
  3      ROWNUM id,
  4      CASE Mod(ROWNUM,2)
  5        WHEN 0 THEN SubStr(object_name,1,2)
  6        ELSE object_name
  7        END AS col1,
  8      object_type col2
  9    FROM all_objects
10    WHERE ROWNUM < 9;
Table created.
SQL>
SQL>
SQL> SELECT * FROM t_user;
        ID COL1                           COL2
         2 I_USER1                        INDEX
         3 CON$                           TABLE
         4 UNDO$                          TABLE
         5 C_COBJ#                        CLUSTER
         6 I_OBJ#                         INDEX
         7 PROXY_ROLE_DATA$               TABLE
         8 I_IND1                         INDEX
         9 I_CDEF2                        INDEX
8 rows selected.
SQL> SELECT * FROM t_published;
        ID COL1                           COL2
         1 ICOL$                          TABLE
         2 I_                             INDEX
         3 CON$                           TABLE
         4 UN                             TABLE
         5 C_COBJ#                        CLUSTER
         6 I_                             INDEX
         7 PROXY_ROLE_DATA$               TABLE
         8 I_                             INDEX
8 rows selected.
SQL>
SQL> -- yet to be published to the production table
SQL> -- includes records previously published and then updated, but not new
SQL> -- records which have never been published (these are in the other query)
SQL> SELECT u.id, u.col1, u.col2
  2  FROM t_user u, t_published p
  3  WHERE u.id = p.id
  4  AND (
  5    u.col1 != p.col1
  6    OR u.col2 != p.col2
  7    )
  8  ;
        ID COL1                           COL2
         2 I_USER1                        INDEX
         4 UNDO$                          TABLE
         6 I_OBJ#                         INDEX
         8 I_IND1                         INDEX
SQL>
SQL> -- new and deleted records
SQL> SELECT * FROM(
  2    SELECT id, col1, col2, 'NEW' status FROM t_user
  3    UNION ALL
  4    SELECT id, col1, col2, 'DELETED' status FROM t_published
  5  )
  6  WHERE id NOT IN(
  7    SELECT id FROM t_user
  8    INTERSECT
  9    SELECT id FROM t_published
10  )
11  ;
        ID COL1                           COL2                STATUS
         9 I_CDEF2                        INDEX               NEW
         1 ICOL$                          TABLE               DELETED
SQL> Basically, I think the answer is in the query and not the Where Clause.
I think you want one of these queries in each block, so set the blocks' queries (are you changing that query based on the parameter passed in, or just executing the query, you're not clear on that) and then do
go_block('B2');
execute_query;
go_block('B1');
execute_query;

Similar Messages

  • Using SAMPLE with a WHERE clause

    (Oracle 9iR2)
    I am using the SAMPLE keyword in a SELECT statement with a WHERE clause. Is the sample extracted before or after applying the WHERE clause?
    For example, if I have the statement:
    SELECT emp_id FROM employees SAMPLE(10)
    WHERE salary > 50000;
    Does the database first extract a 10% sample of all the rows and then apply the salary filter on the sample (meaning it's possible that no rows are returned even though there are rows with salary > 50000)? Or does it return a 10% sample of the rows that meet the filter condition (meaning rows will always be returned as long as there are rows with salary > 50000)?

    The sample is extracted before the where clause:
    SQL> drop table sample_test;
    Table dropped.
    SQL> create table sample_test (id number, salary number);
    Table created.
    SQL>
    SQL> begin
    2 for i in 1..99 loop
    3 insert into sample_test values (i, 100);
    4 end loop;
    5
    6 insert into sample_test values (100, 1000);
    7 end;
    8 /
    PL/SQL procedure successfully completed.
    SQL>
    SQL> commit;
    Commit complete.
    SQL>
    SQL> select * from sample_test sample(5)
    2 where salary > 100;
    no rows selected

  • How to create a procedure to output REF CURSOR with any WHERE clause?

    I have an requirement like this: I have huge query which need to reuse in my code more than 10 times. This SQL has about 50 lines. Thing is for those 10 odd times sometimes the WHERE clause changes (columns are the same). So I cannot create a view since SQL is not static.
    I thought of writing a procedure with a WHERE_CLAUSE input para. I output a sys refcursor by adding the where clause. But I can't do it since you cannot add a where clause like that.
    i.e.
    PROCEDURE dynamyic_query (p_where_clause IN VARCHAR2, p_out_query OUT SYS_REFCURSOR ) IS
    BEGIN
      OPEN p_out_query FOR SELECT ......... FROM table WHERE || ' ' || p_where_clause;
    END;The above gives error.
    How to handle a situation like this???? Any help would be greatly appreciated.

    I tried this method:
    I created a table tab_test which has these records:
    TNAME                          TABTYPE    CLUSTERID                                                                                                                                                                  
    ABS_V4_P_ERROR_MESSAGES        TABLE                                                                                                                                                                                  
    ABS_V4_P_ORG_PARAM             TABLE                                                                                                                                                                                  
    ABS_V4_P_PARAMETER             TABLE                                                                                                                                                                                  
    ABS_V4_P_SYS_PARAM             TABLE                                                                                                                                                                                  
    ACCINTERFACE_PARAMETERS        TABLE                                                                                                                                                                                  
    ACCOUNTS                       TABLE                                                                                                                                                                                  
    ACCOUNT_EXTRACT_PERIODS        TABLE                                                                                                                                                                                  
    ACCOUNT_EXTRACT_PERIODS#       TABLE                                                                                                                                                                                  
    ACCOUNT_EXTRACT_PERIODS_1      TABLE                                                                                                                                                                                   Now I create this proc:
    PROCEDURE FORMS_TEXT_DYN_SQL_TEST(p_where_cluase IN VARCHAR2, p_out_cursor OUT SYS_REFCURSOR) IS
      v_stmt VARCHAR2(1000);
    BEGIN
      v_stmt := 'SELECT tname FROM tab_test WHERE tname LIKE ''%ABS_V4%'' AND tabtype = :x';
      OPEN p_out_cursor FOR v_stmt using p_where_cluase;
    END;I create this code block and run it:
    declare
      v_tname varchar2(200);
      out_cursor sys_refcursor;
    begin
      forms_text_dyn_sql_test('TABLE', out_cursor );
      LOOP
        fetch out_cursor INTO v_tname;
        exit when out_cursor%NOTFOUND;
        DBMS_OUTPUT.PUT_LINE(v_tname);
      END LOOP;
    end;
    /I get correct output:
    ABS_V4_P_ERROR_MESSAGES
    ABS_V4_P_ORG_PARAM
    ABS_V4_P_PARAMETER
    ABS_V4_P_SYS_PARAMHowever, when I change the proc like this:
    PROCEDURE FORMS_TEXT_DYN_SQL_TEST(p_where_cluase IN VARCHAR2, p_out_cursor OUT SYS_REFCURSOR) IS
      v_stmt VARCHAR2(1000);
    BEGIN
      v_stmt := 'SELECT tname FROM tab_test WHERE tname LIKE ''%ABS_V4%'' AND :y';
      OPEN p_out_cursor FOR v_stmt using p_where_cluase;
    END;And run this code block:
    declare
      v_tname varchar2(200);
      out_cursor sys_refcursor;
    begin
      forms_text_dyn_sql_test(' 1 = 1 ', out_cursor );
      LOOP
        fetch out_cursor INTO v_tname;
        exit when out_cursor%NOTFOUND;
        DBMS_OUTPUT.PUT_LINE(v_tname);
      END LOOP;
    end;
    /I get error:
    [1]: (Error): ORA-00920: invalid relational operator ORA-06512: at "ABS.FORMS_TEXT_DYN_SQL_TEST", line 6 ORA-06512: at line 5Looks like you can only put column_name = :z, column_name = :y type values. You cannot it seems replace it with any WHERE CLAUSE????

  • Using round off function in where clause

    Hi All,
    I'm trying to use round off function in where clause, I seek help in completing this script.
    WITH CR_Details AS
    (Select
    request_id,
    parent_request_id,
    fcpt.user_concurrent_program_name Request_Name, phase_code, status_code,
    round((fcr.actual_completion_date - fcr.actual_start_date),3) * 24 * 60 as Run_Time,
    round(avg(round(to_number(actual_start_date - fcr.requested_start_date),3) * 1440),2) wait_time,
    fu.User_Name Requestor,
    fcr.argument_text parameters,
    to_char (fcr.requested_start_date, 'MM/DD HH24:mi:SS') requested_start,
    to_char(actual_start_date, 'MM/DD/YY HH24:mi:SS') ACT_START,
    to_char(actual_completion_date, 'MM/DD/YY HH24:mi:SS') ACT_COMP,
    fcr.completion_text
    From
    apps.fnd_concurrent_requests fcr,
    apps.fnd_concurrent_programs fcp,
    apps.fnd_concurrent_programs_tl fcpt,
    apps.fnd_user fu
    Where 1=1
    and fcr.concurrent_program_id = fcp.concurrent_program_id
    and fcp.concurrent_program_id = fcpt.concurrent_program_id
    and fcr.program_application_id = fcp.application_id
    and fcp.application_id = fcpt.application_id
    and fcr.requested_by = fu.user_id
    and fcpt.language = 'US'
    and fcr.actual_start_date like sysdate )
         select crd.*
         from CR_Details crd
         where Run_time <> '0'
         AND wait_time <> '0'
    GROUP BY
    crd.request_id,
    crd.parent_request_id,
    crd.fcpt.user_concurrent_program_name,
    crd.requested_start_date,
    crd.User_Name,
    crd.argument_text,
    crd.actual_completion_date,
    crd.actual_start_date,
    crd.phase_code,
    crd.status_code,
    crd.resubmit_interval,
    crd.completion_text,
    crd.resubmit_interval,
    crd.resubmit_interval_unit_code,
    crd.description
    Not sure about the GROUPBY function referencing the "crd." .

    Hi,
    The best thing for you to do is start over. Start as small as possible, then take baby steps.
    Pick one of the tables; fcr perhaps, and write a query that just uses that table, like this:
    SELECT    *
    FROM       apps.fnd_concurrent_requests     fcr
    WHERE       fcr.actual_start_date          >= TRUNC (SYSDATE)
    AND       fcr.actual_start_dt          <  TRUNC (SYSDATE) + 1
    ;(I think this is what you meant to do when you said "... LIKE SYSDATE".)
    Make sure this little query gets credible results. When that tiny query is working perfectly, add another line or two. You can cut and paste code from what you posted, if that helps you.
    If you get stuck, post the last version of your code that worked perfectly, and the latest version (only a line or two bigger) that has the problem. Describe what the problem is. If you get an error, post the complete error message. In any event, post CREATE TABLE and INSERT statements for all the tables and columns needed to run the query, and the results you want to get from that query.
    When you post any code, format it, so that how the code looks on the screen gives some clues about how it is working.
    When you post any formatted text on this site, type these 6 characters:
    \(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.
    If you going to use the AVG function in the sub-query, then you probably need to do a GROUP BY in the sub-query.
    If you're not using any aggregate functions (like AVG) in the main query, then you probably don't want to do a GROUP BY in the main query.
    I know this is a lot of work.  I'm sorry.  If there was an easier way, I wouldn't ask you to do all this.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • "create columns with a where clause" in BMM

    Hi All,
    I have a question about OBI EE Meta data layer.
    We have OBIEE sitting on a Data Warehouse with a star schema.
    Our Fact table holds the following fields...
    EmployeeID
    CompanyID
    Measure ID
    Measure Name
    MEASURE
    This is what we have in the physical layer, BMM layer and the presentation layer but I want to be able to "create columns with a where clause"
    So my fact table in the presentation layer would look like this
    Amount Sold
    Unit Cost
    Company Amount
    I thought I could just create a logical column with
    Amount Sold = Measure
    where Measure Name = "Amount Sold"
    But I can't seem to find any to do that.
    Any ideas?
    Thanks

    Or you simply map your measure in the Logical Table source as something like :
    CASE WHEN MEASURE_NAME = 'Amount Sold' THEN MEASURE ELSE 0 END.
    You need to decide if you want the where clause adding in the Logical table source (be careful you will need a seperate LTS for each measure, this will mean more than one SQL being fired when you have more than one measure in the report).
    Or you go with this case method on each measure, be able to have all the measures mapped in 1 LTS, include all those in the report and they will be retrieved by one SQL block.

  • Insert Row is visible in other VO with excluded where-clause

    Hi,
    i found something that makes me a little bit confusing about ADF BC...
    TestCase:
    Env:
    JDev 10.1.2     
    HR Schema / Table "regions"
    All Objects created ´by ADF BC Wizards
    - ViewObject A and ViewObject B based on Entity "Regions"
         - ViewObject A with WHERE-CLAUSE region_id=10 at DesignTime
    - ViewObject B with NO WHERE-CLAUSE (select * from regions)
    JUnitTest:
    public void testInsertRow()
    ViewObject viewA = fixture1.getApplicationModule().findViewObject("RegionsAView");
    ViewObject viewB = fixture1.getApplicationModule().findViewObject("RegionsBView");
    System.out.println("ViewA:"+viewA.getRowCount()); //-->0
    assertTrue("Must 0 ! region_id = 10",viewA.getRowCount() == 0);
    Row row = viewB.createRow();
    row.setAttribute("RegionId",new Number(99));
    row.setAttribute("RegionName","NRW");
    viewB.insertRow(row);
    System.out.println("ViewB:"+viewB.getRowCount()); // -> 5
    System.out.println("ViewA:"+viewA.getRowCount()); // -> 1
    //this assert failt !
    assertTrue("Must 0 ! where clause is region_id = 10 and insert region_id was 99 ",viewA.getRowCount() == 0);
    Is this a bug or feature ? Can anybody explain that behavior ? thx :)
    uli

    See this article on my blog for an explanation and a code sample for how to gain more fine-grained control over this View Link Consistency feature...
    http://radio.weblogs.com/0118231/2004/02/27.html#a242

  • REPORT with dynamic WHERE CLAUSE (run RDF or REP) ?

    Hi:
    When running a REPORT (myreport.rep) with dynamic where clause using a lexical parameter, I got this error:
    REP-1439: Cannot compile .REP or .PLX file as it does not have source
    If i run the report specifiying RDF extension (myreport.rdf) the report run successfully! Is this normal ?
    If I specify RDF extension will Report Server COMPILE the report everytime I execute it ?
    When using dynamic WHERE CLAUSE I will have to run RDF files instead of REP ?
    I'm running Reports 9i under Linux, with IDS under Windows.
    Waiting Help
    Joao Oliveira

    It sounds like you are building the .rep files on one platform (windows) and running them on another (linux). The reason that the .rdf file continues to work is that Reports recompiles the PL/SQL within the report when you move from one platform to another or change schemas. .rep files can't be re-compiled in this way so you need to ensure they are compiled successfully when converting them.
    You need to convert from .rdf to .rep on the platform that you are intending to run on. Try running rwconverter on the linux platform with "compile_all=yes" to produce the .rep file and running that .rep file.

  • Query Tuning - using CASE statement in the WHERE clause - Duplicate Post

    Duplicate Post by mistake.
    Please check
    Query Tuning - using CASE statement in the WHERE clause
    Edited by: Chaitanya on Jun 9, 2011 2:45 AM
    Edited by: Chaitanya on Jun 9, 2011 2:46 AM

    Duplicate Post by mistake.
    Please check
    Query Tuning - using CASE statement in the WHERE clause
    Edited by: Chaitanya on Jun 9, 2011 2:45 AM
    Edited by: Chaitanya on Jun 9, 2011 2:46 AM

  • XSQL Using bind params with sql LIKE clause

    I am unable to use a bind-param with the LIKE clause in a SELECT statement.
    eg call .../temp.xsql?name=N
    XSQL query is this:
    <xsql:query max-rows="-1" bind-params="name">
    SELECT last_name
    FROM emp
    WHERE last_name LIKE '?%'
    </xsql:query>
    I have tried a few combinations so far with no success eg:
    WHERE last_name LIKE '{@name}%'
    WHERE last_name LIKE ?||%
    Any ideas?

    I highly recommend using XSQL's real bind variable feature wherever you can. You can read about it in the XSQL Online Documentation (Search for the "Using Bind Variables" section).
    Using this feature is more performant and more secure than using textual substitution variables.
    Here's what your page looks like using textual substitution:
    <page connection="UTD4" xmlns:xsql="urn:oracle-xsql">
      <xsql:query null-indicator="yes" >
        SELECT * FROM TC_HL7_SEG WHERE SEGMENT_CODE LIKE '{@code}%'
      </xsql:query>
    </page> .
    And here's what it would look like using real bind variables:
    <page connection="UTD4" xmlns:xsql="urn:oracle-xsql">
      <xsql:query null-indicator="yes" bind-params="code">
        SELECT * FROM TC_HL7_SEG WHERE SEGMENT_CODE LIKE ?||'%'
      </xsql:query>
    </page> .
    Using real bind variables allows the database to avoid reparsing the SQL statement everytime, which improves performance.
    Steve Muench
    JDeveloper/BC4J Development Team
    Author, Building Oracle XML Applications

  • Using bind variable in dynamic where clause and concatenate with query

    Hi,
    In my procedure i am framing where clause dynamically with bind variable,When i am concatenate this with my sql query for REF CURSOR i got sql command not properly ended exception.
    Is it possible to pass values to the bind variable through the dynamic variable/value?
    Please advise
    Thanks in advance
    Siva
    IF in_applicationId IS NOT NULL THEN
              optional_where := optional_where || ' AND a.APPLICATION_ID like '||':e%';
              optional_using := ' in_appFuncGroup'||',in_currentUserID'||',in_appFuncGroup'||',in_queue_id'||',in_applicationId';
         END IF;
    My query is like this
    open Out_Main FOR SelectQuery USING optional_using

    Thanks for reply,
    In my procedure, i suppose to frame the where clause with bind dynamically according to the input parameters. so that i am framing the values of the bind variables also dynamically like this,
    Please advise...
    IF in_assignedAppFlag IS NOT NULL THEN
              IF in_assignedAppFlag = 'Y' THEN
                   optional_where := optional_where || ' AND b.ASSIGNED_TO = :b' ;
              optional_using := ' in_appFuncGroup'||',in_currentUserID';          
              ELSe
                   IF in_isSupervisor = 0 THEN
                        optional_where := optional_where || ' AND (b.ASSIGNED_TO = :b'||' OR b.ASSIGNED_TO = ''-1'' OR b.ASSIGNED_TO IS NULL)';
              optional_using := ' in_appFuncGroup'||',in_currentUserID';
                   END IF;
              END IF;
         ELSE
              IF in_isSupervisor = 0 THEN
                   optional_where := optional_where || ' AND (b.ASSIGNED_TO = :b'||' OR b.ASSIGNED_TO = ''-1'' OR b.ASSIGNED_TO IS NULL)';
                   optional_using := ' in_appFuncGroup'||',in_currentUserID';
              END IF;
         END IF;
         IF in_appFuncGroup IS NOT NULL THEN
              optional_where := optional_where || ' AND e.APP_FUNC_GROUP= :c';
              optional_using := ' in_appFuncGroup'||',in_currentUserID'||',in_appFuncGroup';
         END IF;
         IF in_queue_id IS NOT NULL THEN
              optional_where := optional_where || ' AND b.QUEUE_ID = :d';
              optional_using := ' in_appFuncGroup'||',in_currentUserID'||',in_appFuncGroup'||',in_queue_id';
         END IF;
         IF in_applicationId IS NOT NULL THEN
              optional_where := optional_where || ' AND a.APPLICATION_ID like '||':e%';
              optional_using := ' in_appFuncGroup'||',in_currentUserID'||',in_appFuncGroup'||',in_queue_id'||',in_applicationId';
         END IF;
         IF in_sourceCode IS NOT NULL THEN
              optional_where := optional_where || ' AND e.APP_SOURCE_CODE like '||':f%';
              optional_using := ' in_appFuncGroup'||',in_currentUserID'||',in_appFuncGroup'
              ||',in_queue_id'||',in_applicationId'||',in_sourceCode';
         END IF;
         IF in_logo IS NOT NULL THEN
              optional_where := optional_where || ' AND appProds.PRODUCT_TYPE like '||':g%';
              optional_using := ' in_appFuncGroup'||',in_currentUserID'||',in_appFuncGroup'
              ||',in_queue_id'||',in_applicationId'||',in_sourceCode'||',in_logo';
         END IF;
         IF in_firstName IS NOT NULL THEN
              optional_where := optional_where || ' AND upper(a.FIRST_NAME) like upper(:h%)';
              optional_using := ' in_appFuncGroup'||',in_currentUserID'||',in_appFuncGroup'
              ||',in_queue_id'||',in_applicationId'||',in_sourceCode'||',in_logo'||',in_firstName';
         END IF;
         IF in_surName IS NOT NULL THEN
              optional_where := optional_where || ' AND upper(a.SURNAME) like upper(:i%)';
              optional_using := ' in_appFuncGroup'||',in_currentUserID'||',in_appFuncGroup'
              ||',in_queue_id'||',in_applicationId'||',in_sourceCode'||',in_logo'||',in_firstName'||',in_surName';
         END IF;
         IF in_retreival_id IS NOT NULL THEN
              optional_where := optional_where || ' AND e.RETREIVAL_ID like :j%';
              optional_using := ' in_appFuncGroup'||',in_currentUserID'||',in_appFuncGroup'
              ||',in_queue_id'||',in_applicationId'||',in_sourceCode'||',in_logo'||',in_firstName'||',in_surName'||',in_retreival_id';
         END IF;

  • Using inline view with NOT IN clause

    I have a query with a NOT IN clause in the where clause that I would like to convert to an inline view. The select looks something like this:
    select uid, SYSDATE from tab1, tab2
    where tab1.uid = tab2.uid
    and ...
    and tab1.uid not in (select uid from tab3 where....)
    I've used inline queries elsewhere to great effect, but this one has me stumped. If anyone can help, it would be greatly appreciated.

    There can be problem with using not in or not exists depending on the amount of data in the tables and the relationship between them.
    I didn't got if you had problem with the existing SQL-statement, created view or both.
    Check statistics and look at explain plan for the sql-statement and the view.
    The problem can actually be some where clause that you have in the sql-statement but not in the view, but apply later when using the view.
    //Anders

  • Improve the performance in stored procedure using sql server 2008 - esp where clause in very big table - Urgent

    Hi,
    I am looking for inputs in tuning stored procedure using sql server 2008. l am new to performance tuning in sql,plsql and oracle. currently facing issue in stored procedure - need to increase the performance by code optmization/filtering the records using where clause in larger table., the requirement is Stored procedure generate Audit Report which is accessed by approx. 10 Admin Users typically 2-3 times a day by each Admin users.
    It has got CTE ( common table expression ) which is referred 2  time within SP. This CTE is very big and fetches records from several tables without where clause. This causes several records to be fetched from DB and then needed processing. This stored procedure is running in pre prod server which has 6gb of memory and built on virtual server and the same proc ran good in prod server which has 64gb of ram with physical server (40sec). and the execution time in pre prod is 1min 9seconds which needs to be reduced upto 10secs or so will be the solution. and also the exec time differs from time to time. sometimes it is 50sec and sometimes 1min 9seconds..
    Pl provide what is the best option/practise to use where clause to filter the records and tool to be used to tune the procedure like execution plan, sql profiler?? I am using toad for sqlserver 5.7. Here I see execution plan tab available while running the SP. but when i run it throws an error. Pl help and provide inputs.
    Thanks,
    Viji

    You've asked a SQL Server question in an Oracle forum.  I'm expecting that this will get locked momentarily when a moderator drops by.
    Microsoft has its own forums for SQL Server, you'll have more luck over there.  When you do go there, however, you'll almost certainly get more help if you can pare down the problem (or at least better explain what your code is doing).  Very few people want to read hundreds of lines of code, guess what's it's supposed to do, guess what is slow, and then guess at how to improve things.  Posting query plans, the results of profiling, cutting out any code that is unnecessary to the performance problem, etc. will get you much better answers.
    Justin

  • How to use a case statement in where clause

    Hi All,
    I have a requirement which is to bring all the claims that are created in the last month.So, i wrote a query something like this
    select * from claims
    where
    (Month(ClaimOpenDate) = Month(Getdate())-1 and year(claimopendate) = year(getDate()))
    which would give me any new claims created in last month of current year, but this condition fails if we are in the first month of a new year( lets say if we are in 2016 jan then month(getdate())-1 would be 0 and year(getdate()) would be 2016 so we dont
    find any records where year is 2016 and month is 0 for claimopen).
    So, i would like to use a case statament or something which can help me get around this one.
    Can someone please help me with any suggestions?
    Thanks

    Hi Jason,
    Thanks a lot for your help. This is what exactly i am looking for but i just gave a sample query above below is my original query 
    select
    row_number() over (order by [ClaimNumber]) as DataElementName
    ,c.PolicyNumber as PolicyNum
    , c.FirstName as CustNameF
    ,c.LastName as CustNameL
    ,c.PolicyForm as PolType
    ,'Homesite' as Company
    ,[ClaimNumber] as ClaimNum
    ,E.office as Ofc
    ,e.Supervisior_FullName as Team
    , RIGHT(e.adjuster_Name ,LEN(e.adjuster_Name)- charindex(',' ,e.adjuster_Name)) as FORepF
    , case when charindex(',' ,e.adjuster_Name) <> 0 then left(e.adjuster_Name,charindex(',' ,e.adjuster_Name)-1) else e.adjuster_Name end as FORepL
    ,e.AdjusterID as RepC -- not sure
    ,CONVERT ( varchar,c.LossDate ,101) as DOL
    ,convert (varchar,c.ClaimOpenDate,101) as DOR
    ,rtrim(c.Loss_State) as LossSt
    ,c.Loss_ZipCode as LossZIP
    ,c.Loss_City as LossCity
    ,c.LossType as FOL
    ,'' as PR
    ,'' as PRNum
    ,1 as FeaNum
    ,'HO' as FeaType
    ,case when rtrim(c.claimStatus)= 'Closed' then 'Closed' else 'Open' end as FeaStat
    ,'' as FeaOpen
    ,'' as FeaClosed
    ,s.PaymentIndemnityAmount as PaidAmt
    ,s.ReserveIndemnityAmount as Reserve
    ,'' as Sub
    ,'' as Sal
    ,'' as FeatOwnOfc
    ,e.Supervisior_FullName as FeatOwnTeam
    ,RIGHT(e.adjuster_Name ,LEN(e.adjuster_Name)- charindex(',' ,e.adjuster_Name)) as FeatOwnRepF
    ,case when charindex(',' ,e.adjuster_Name) <> 0 then left(e.adjuster_Name,charindex(',' ,e.adjuster_Name)-1) else e.adjuster_Name end as FeatOwnRepL
    ,e.AdjusterID as FeatOwnRepCode
    ,NULL AS Description --not sure
    from [Stg].[HS_DW_RV_Claims] c
    inner join [dbo].[Claims_Primary_Adjuster] a on a.CLAIM_NUMBER = c.ClaimNumber
    inner join [dbo].[vw_Adjuster] e on e.adjuster_Name = a.primary_ADJUSTER
    left outer join [Stg].[HS_DW_LossClaimSummary] s on c.ClaimKey=s.ClaimKey
    where c.LoadSource = 'CMS'
    and
    (s.PaymentIndemnityAmount <>0 or s.PaymentExpenseAmount <>0)
    and
    ClaimOpenDate BETWEEN DATEADD(mm, DATEDIFF(mm, 0, CURRENT_TIMESTAMP) -1, 0) AND DATEADD(mm, DATEDIFF(mm, 0, CURRENT_TIMESTAMP), 0)
    UNION ALL
    select
    row_number() over (order by [ClaimNumber]) as DataElementName
    ,c.PolicyNumber as PolicyNum
    , c.FirstName as CustNameF
    ,c.LastName as CustNameL
    ,c.PolicyForm as PolType
    ,'Homesite' as Company
    ,[ClaimNumber] as ClaimNum
    ,E.office as Ofc
    ,e.Supervisior_FullName as Team
    , RIGHT(e.adjuster_Name ,LEN(e.adjuster_Name)- charindex(',' ,e.adjuster_Name)) as FORepF
    , case when charindex(',' ,e.adjuster_Name) <> 0 then left(e.adjuster_Name,charindex(',' ,e.adjuster_Name)-1) else e.adjuster_Name end as FORepL
    ,e.AdjusterID as RepC -- not sure
    ,CONVERT ( varchar,c.LossDate ,101) as DOL
    ,convert (varchar,c.ClaimOpenDate,101) as DOR
    ,rtrim(c.Loss_State) as LossSt
    ,c.Loss_ZipCode as LossZIP
    ,c.Loss_City as LossCity
    ,c.LossType as FOL
    ,'' as PR
    ,'' as PRNum
    ,1 as FeaNum
    ,'HO' as FeaType
    ,case when rtrim(c.claimStatus)= 'Closed' then 'Closed' else 'Open' end as FeaStat
    ,'' as FeaOpen
    ,'' as FeaClosed
    ,s.PaymentIndemnityAmount as PaidAmt
    ,s.ReserveIndemnityAmount as Reserve
    ,'' as Sub
    ,'' as Sal
    ,'' as FeatOwnOfc
    ,e.Supervisior_FullName as FeatOwnTeam
    ,RIGHT(e.adjuster_Name ,LEN(e.adjuster_Name)- charindex(',' ,e.adjuster_Name)) as FeatOwnRepF
    ,case when charindex(',' ,e.adjuster_Name) <> 0 then left(e.adjuster_Name,charindex(',' ,e.adjuster_Name)-1) else e.adjuster_Name end as FeatOwnRepL
    ,e.AdjusterID as FeatOwnRepCode
    ,DESCRIPTION --not sure
    from Stg.IG_Document D
    inner join [Stg].[HS_DW_RV_Claims] c on D.PARENTREF = C.ClaimNumber
    inner join [dbo].[Claims_Primary_Adjuster] a on a.CLAIM_NUMBER = c.ClaimNumber
    inner join [dbo].[vw_Adjuster] e on e.adjuster_Name = a.primary_ADJUSTER
    left outer join [Stg].[HS_DW_LossClaimSummary] s on c.ClaimKey=s.ClaimKey
    where c.LoadSource = 'CMS'
    and
    DESCRIPTION like '%Denial Letter%'
    and
    ClaimOpenDate BETWEEN DATEADD(mm, DATEDIFF(mm, 0, CURRENT_TIMESTAMP) -1, 0) AND DATEADD(mm, DATEDIFF(mm, 0, CURRENT_TIMESTAMP), 0)
    So if i use your logic in the end for both the where clauses its been more than 10 minutes and the query is still running however if i use my old method it doesnt even take a second. Looks like its affecting the execution plan. Any suggestions to get around
    this one please?
    Thanks

  • Performance with unspecific where clause

    Hi gurus,
    at the moment I do have a sql statement on a view with an unspecific where clause like
    select from <view> where <textfield> like %whatIsearch%
    The text field is not in the key fields which are used to create the view. An index on <textfield> does not help, because the where clause starts with a %.
    Other databases like Oracle do finish the statement within seconds, maxdb needs minutes.
    I there a possibility to speedup the statement in MaxDB? (Besides telling the user to use better qualified statments.)
    Why is Oracle that fast?
    Thanks for you help.
    Best regards
    Christian G

    > Other databases like Oracle do finish the statement within seconds, maxdb needs minutes.
    > I there a possibility to speedup the statement in MaxDB? (Besides telling the user to use better qualified statments.)
    > Why is Oracle that fast?
    Hi Christian,
    In that case Oracle can take advantage from beeing able to brute-force read many blocks at once (aka multiblock read).
    When we assume that there is an index on the oracle database available, then Oracle will likely decide to read all blocks of that index into the cache and look for matches then. It's called Fast Full Scan.
    It's not a very efficient method to address specific rows, but for this requirement it works well.
    Anyhow, you should be aware that this way of evaluating rows does not scale very well - in fact it get's more expensive with every block the index grows.
    MaxDB cannot easily read all blocks in a row, due to the fact that the pages are mixed over all data volumes. This way of storing data eliminates the need for reorganisations and evens out I/O traffic, but it comes for the price of beeing less performant when people use such unefficient predicates.
    Because of this and the way who indexes work in MaxDB (primary keys instead of rowids), MaxDB does only consider an index access for like conditions that start with a '%' when the query can be answered by only accessing the index (index only access).
    What you may try out to improve the situation is to activate the experimental read-ahead or prefetch feature, which is currently available in MaxDB 7.6. only (not in 7.5 or in 7.7).
    By setting READAHEAD_TABLE_THRESHOLD to a value >0, say 128, MaxDB can choose to
    perform table scans (no index scans!) in parallel with multiple server tasks for all table scans that are expected to pass the threshold (unit here is pages as visible in the execution plan of your statement).
    That way the usertask running the query can work on checking the data in the pages, while the server task load the pages into the cache.
    Another approach would be to have the DB Cache big enough so that most of the table would be found in the cache.
    regards,
    Lars

  • Combining Sum/Case queries with different where clauses into one query

    Hello,
    I'm trying to combine 2 queries that contain the SUM/CASE function into one query that'll produce the output in the same table, rather than having two The thing is, the two queries have different conditions. I've created a sample data table and outputs to better describe what I'm trying to achieve.
    SAMPLE_DATA
    DEPT
    PROD_CODE
    FLAG1
    FLAG2
    HO
    A
    NULL
    Y
    HO
    B
    NULL
    Y
    HO
    A
    Y
    NULL
    HO
    B
    Y
    Y
    IT
    A
    NULL
    Y
    IT
    C
    NULL
    NULL
    ENG
    B
    NULL
    Y
    ENG
    C
    NULL
    Y
    ENG
    C
    Y
    Y
    MKT
    A
    Y
    Y
    The first query I'm running is to sum the product codes department wise while checking if FLAG1 is Y. The second query is checking if FLAG2 is Y.
    First Query:
    select DEPT, sum(case PRODUCT_CODE when 'A' then 1 else 0 end),
    sum(case PRODUCT_CODE when 'B' then 1 else 0 end),
    sum(case PRODUCT_CODE when 'C' then 1 else 0 end)
    from SAMPLE_DATA where FLAG1 is not null group by DEPT;
    Second Query:
    select DEPT, sum(case PRODUCT_CODE when 'A' then 1 else 0 end),
    sum(case PRODUCT_CODE when 'B' then 1 else 0 end),
    sum(case PRODUCT_CODE when 'C' then 1 else 0 end)
    from SAMPLE_DATA where FLAG2 is not null group by DEPT;
    FIRST QUERY OUTPUT:
    DEPT
    PRODA_FL1
    PRODB_FL1
    PRODC_FL1
    HO
    1
    1
    0
    IT
    0
    0
    0
    ENG
    0
    0
    1
    MKT
    1
    0
    0
    SECOND QUERY OUTPUT:
    DEPT
    PRODA_FL2
    PRODB_FL2
    PRODC_FL2
    HO
    1
    2
    0
    IT
    1
    0
    0
    ENG
    0
    1
    2
    MKT
    1
    0
    0
    My aim is to combine both the queries so that the output is displayed the same way as the table below.
    DESIRED OUTPUT:
    DEPT
    PRODA_FL1
    PRODB_FL1
    PRODC_FL1
    PRODA_FL2
    PRODB_FL2
    PRODC_FL2
    Any help or tips will be greatly appreciated. Please note I'm working with more complex data and have simplified my question just to understand how to solve this.

    Just treat the two queries as tables, join them on DEPT and produce the results you want.
    with q1 as (
    select DEPT, sum(case PRODUCT_CODE when 'A' then 1 else 0 end) PRODA_FL1,
    sum(case PRODUCT_CODE when 'B' then 1 else 0 end) PRODB_FL1,
    sum(case PRODUCT_CODE when 'C' then 1 else 0 end) PRODC_FL1
    from SAMPLE_DATA where FLAG1 is not null group by DEPT),
    q2 as (
    select DEPT, sum(case PRODUCT_CODE when 'A' then 1 else 0 end) PRODA_FL2,
    sum(case PRODUCT_CODE when 'B' then 1 else 0 end) PRODB_FL2,
    sum(case PRODUCT_CODE when 'C' then 1 else 0 end) PRODC_FL2
    from SAMPLE_DATA where FLAG2 is not null group by DEPT;
    select q1.dept, proda_fl1, prodb_fl1, prodc_fl1, proda_fl2, prodb_fl2, prodc_fl2
    from q1, q2
    where q1.dept = q2.dept

Maybe you are looking for

  • Selling an Imac to a family member and want to delete the user

    So I'm selling my 2008 iMac to my mom because I just bought a new macbook pro. I've transferred everything to my new computer and now want to delete my user account on my old one (which is the only user on the computer). I want my mom to be able to m

  • Name collisions in NetGroup MulticastStreams

    Hi Everyone We ran into a problem with this new application we're developing. Say, we have a NetGroup with no publish password. Every user in this group can publish a NetStream with their video. Then consider this scenario: 1. User A joins the group,

  • Charts are not working in Multiple Presentation Services environment.

    Hi , I have implemented multiple presentation services enviornment bu follwoing this blog: http://rnm1978.wordpress.com/2009/08/25/multiple-rpds-on-one-server-part-2-presentation-services/. It was successfully implemented but charts are not working f

  • Illustrator CS6 (mac) crashes at startup while reading fonts! HELP PLEASE!!

    So I've had this problem for a while now. My illustrator crashes at startup while "reading fonts". BUT the strange thing is, illustrator opens fine in the other user accounts on my computer. I just want it to work on my main one but no luck getting i

  • Call Crystal Report from java

    <p>Hi,<br /><br />Can anyone pl send me an e.g of how to call crystal reports from java ? Preferably crsytal version 10. how to instantiate a crystal report viewer? how to pass parameters? how to set the connection string?</p><p>my email is <a href="