Rewrite a sql query

Hi All
i want to rewite the sql from
select x
from table1 t1
where y =
( select max(y) from table1 t2 where t1.id = t2.id )
to be more simple
i believe that analytic functions can do that
i tried
select x
from table1
having y = max(y) over()
but it did not work
any help please
thanks

thanks for all of you
i have rewriten the query , BUT the code did not become smaller , and i don't know which execution plan is better , any suggestions?
Old SQL:
SELECT scl1.claim_type,
scp.publisher_no,
scp.publisher_percentage,
sys.dual_claim_publisher_no,
effective_date
FROM song_claims scl1, song_claim_publishers scp, system_parameters sys
WHERE scl1.song_claim_no = scp.song_claim_no
AND scl1.song_no = 2
AND scl1.effective_date =
SELECT MAX(scl2.effective_date)
FROM song_claims scl2
WHERE scl2.song_no = 21
AND (scl2.effective_date <= '01-jan-2000'
OR scl2.effective_date =
SELECT MIN(scl3.effective_date)
FROM song_claims scl3
WHERE scl3.song_no = 2
Old SQL Execution Plan:
SELECT STATEMENT, GOAL = CHOOSE               Cost=8     Cardinality=1     Bytes=30
TABLE ACCESS BY INDEX ROWID     Object owner=CRS     Object name=SONG_CLAIM_PUBLISHERS     Cost=3     Cardinality=1     Bytes=10
NESTED LOOPS               Cost=8     Cardinality=1     Bytes=30
NESTED LOOPS               Cost=5     Cardinality=1     Bytes=20
TABLE ACCESS BY INDEX ROWID     Object owner=CRS     Object name=SONG_CLAIMS     Cost=3     Cardinality=1     Bytes=17
INDEX UNIQUE SCAN     Object owner=CRS     Object name=XAK1SONG_CLAIMS     Cost=2     Cardinality=1     
SORT AGGREGATE                    Cardinality=1     Bytes=12
FIRST ROW               Cost=3     Cardinality=1     Bytes=12
INDEX RANGE SCAN (MIN/MAX)     Object owner=CRS     Object name=XAK1SONG_CLAIMS     Cost=3     Cardinality=338621     
SORT AGGREGATE                    Cardinality=1     Bytes=12
FIRST ROW               Cost=3     Cardinality=1     Bytes=12
INDEX RANGE SCAN (MIN/MAX)     Object owner=CRS     Object name=XAK1SONG_CLAIMS     Cost=3     Cardinality=338621     
TABLE ACCESS FULL     Object owner=WISSYS     Object name=SYSTEM_PARAMETERS     Cost=2     Cardinality=1     Bytes=3
INDEX RANGE SCAN     Object owner=CRS     Object name=XPKSONG_CLAIM_PUBLISHERS     Cost=2     Cardinality=1     
New SQL:
select * from
SELECT scl1.claim_type,
scp.publisher_no,
scp.publisher_percentage,
sys.dual_claim_publisher_no,
scl1.effective_date,
max (effective_date) over (partition by null) max_eff_date,
min (effective_date) over (partition by null) min_eff_date
FROM song_claims scl1, song_claim_publishers scp, system_parameters sys
WHERE scl1.song_claim_no = scp.song_claim_no
AND scl1.song_no = 2
where
effective_date = case when max_eff_date <= '01-jan-2000' then to_char(max_eff_date)
when min_eff_date > '01-jan-2000' then to_char(min_eff_date)
else (SELECT to_char(MAX(effective_date)) FROM song_claims scl2 WHERE scl2.song_no = 2 and scl2.effective_date < '01-jan-2000')
end
New SQL Execution Plan:
SELECT STATEMENT, GOAL = CHOOSE               Cost=10     Cardinality=1     Bytes=69
VIEW     Object owner=BFH          Cost=10     Cardinality=1     Bytes=69
WINDOW BUFFER               Cost=10     Cardinality=1     Bytes=30
TABLE ACCESS BY INDEX ROWID     Object owner=CRS     Object name=SONG_CLAIM_PUBLISHERS     Cost=3     Cardinality=1     Bytes=10
NESTED LOOPS               Cost=8     Cardinality=1     Bytes=30
MERGE JOIN CARTESIAN               Cost=5     Cardinality=1     Bytes=20
TABLE ACCESS FULL     Object owner=WISSYS     Object name=SYSTEM_PARAMETERS     Cost=2     Cardinality=1     Bytes=3
BUFFER SORT               Cost=3     Cardinality=1     Bytes=17
TABLE ACCESS BY INDEX ROWID     Object owner=CRS     Object name=SONG_CLAIMS     Cost=3     Cardinality=1     Bytes=17
INDEX RANGE SCAN     Object owner=CRS     Object name=XAK1SONG_CLAIMS     Cost=2     Cardinality=1     
INDEX RANGE SCAN     Object owner=CRS     Object name=XPKSONG_CLAIM_PUBLISHERS     Cost=2     Cardinality=1     
SORT AGGREGATE                    Cardinality=1     Bytes=12
FIRST ROW               Cost=3     Cardinality=1     Bytes=12
INDEX RANGE SCAN (MIN/MAX)     Object owner=CRS     Object name=XAK1SONG_CLAIMS     Cost=3     Cardinality=338621     
Thanks

Similar Messages

  • Parsing and rewriting an SQL query

    Hi all,
    I need to rewrite bits of a valid PL/SQL query. In order to do so, I need semantic information about the query, such as "what are the table names columns are being selected from" or "do aggregate functions in a select provide column alias in order to use the query in +CREATE TABLE AS+ ...".
    Is it possible to somehow "ask" the Oracle parser for those bits of semantic info? I am using 9i.
    E.g.
    select X.ID, Y.NAME, SUM(ABS(Y.VALUE))
    from
    TABLE_X X,
    (select NAME, VALUE from TABLE_Z where DATE_STR = '20090101') Y
    where
    will become
    select X.ID, Y.NAME, SUM(ABS(Y.VALUE)) COL1
    from
    TABLE_X prefix. X,
    (select NAME, VALUE from prefix. TABLE_Z where DATE_STR = '20090101') Y
    where
    ...

    Thanks for your answers (which, unfortunately, do not give much hope)!
    +..so unfortunately you won't be able to use the 11g method introduced here (Anyhow still undocumented!).+
    Yes, that's very disappointing. I actually added the "has to be 9i compatible" remark after I found out the XML dump does not work on our servers - and read the manual page to realize why that's the case.
    I think you'd need to write your own, which will be extremely difficult and hard to maintain.*
    There is a BNF grammar of PL/SQL (homebrew, apparently - so no guarantees): http://www.antlr.org/grammar/1107752678378/PLSQLGrammar.g
    Now, if I only knew practical stuff about lexers and parsers and abstract syntax trees...

  • Need help in rewriting a sql query

    Can any one please tell me if there is any utility that can help me correcting the sql I have I need to tune the query as its taking lot of time. I want to use some tool that will help me re-formating the query.
    Any help in this regard will be highly appreciated.

    If you think that Oracle SQL Tuning Tools like SQL Tuning Advisor and SQL Access Advisor are not helping.
    You might look into thrid party tools like Quest- SQL Navigator and TOAD.
    But I don't advise this based on the following:
    Re: Oracle Third Party Tools and Oracle Database
    Oracle have enough tools of its own to satisfy the various needs.
    Adith

  • Rewrite sql query

    Hello,
    I need to rewrite this SQL query to give the same result, but in more resorcefull manner.
    Probably using aggregation, but I am not sure.
    Can somebody give me a head start.
    desc resource_bundles
    Name          Null     Type               
    LOCALE        NOT NULL CHAR(5)            
    BUNDLE_NAME   NOT NULL VARCHAR2(32)       
    RESOURCE_NAME NOT NULL VARCHAR2(64)       
    VALUE_STRING           VARCHAR2(2048 CHAR)
    select a.bundle_name,a.resource_name, a.value_string as Czech,(select b.value_string
                                             from resource_bundles b
                                             where b.bundle_name = a.bundle_name
                                             and b.resource_name = a.resource_name
                                             and b.locale = 'en_US'
                                            )as English,
                                             (select c.value_string
                                             from resource_bundles c
                                             where c.bundle_name = a.bundle_name
                                             and c.resource_name = a.resource_name
                                             and c.locale = 'ru_RU'
                                             ) as Russian,
                                             (select d.value_string
                                             from resource_bundles d
                                             where d.bundle_name = a.bundle_name
                                             and d.resource_name = a.resource_name
                                             and d.locale = 'it_IT'
                                            ) as Italian
    from resource_bundles a
    where a.locale = 'cs_CZ';Thank you
    Edited by: BluShadow on 15-Apr-2011 12:20
    added {noformat}{noformat} tags                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    It is always helpful to provide the following:
    1. Oracle version (SELECT * FROM V$VERSION)
    2. Sample data in the form of CREATE / INSERT statements.
    3. Expected output
    4. Explanation of expected output (A.K.A. "business logic")
    5. Use \ tags for #2 and #3. See FAQ (Link on top right side) for details.
    Also see the third post in this thread:
    {thread:id=2174552}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • How to modify a SQL query?

    Hi all,
    I am using Crystal Reports version 10. I have a number of reports that have been written by a software vendor wherby the name of the database they were connected to when the report was written is coded into the FROM command of the reports SQL query, eg "GCUK_2" in the of the SQL snippet below.
    SELECT "Clients"."NAME", "Quotes"."QUOTE_ID", "Quote_Items"."UPRICE", "Quote_Items"."QTY", "Quote_Items"."UOM", "Quote_Items"."QUSAGE_ID", "Report_Control"."QUSAGEID", "Quote_Items"."STANDARD", "Quote_Items"."SECT_FLAG", "Quote_Items"."DISPORDER", "Quotes"."DESCRIPT", "Report_Control"."SECT_NAME", "Quote_Items"."CNT", "Category_and_Type"."TYPEDESC", "Quote_Items"."DESCRIPT", "Report_Control"."DISP_SORT"
    FROM   ((("GCUK_2"."schedwin"."QTE_CTRL" "Report_Control" INNER JOIN "GCUK_2"."schedwin"."QUSAGE" "Quote_Items" ON "Report_Control"."QUSAGEID"="Quote_Items"."QUSAGE_ID") LEFT OUTER JOIN "GCUK_2"."schedwin"."QUOTES" "Quotes" ON
    I have tried setting the Datasource Location, but it doesn't change the query at all. I have read on another forum that you can generate another SQL query using the Database Expert, Current Connections, then right click the Add Command for the database you want to create a SQL command. Is this the only way to update the database names in the query?
    Thanks,
    Scott.

    Hi Sourashree,
    Thanks for that. All the reports were created by the vendor using tables as opposed to the command object. I would have thought that changing the datasource would automatically cause Crystal to rewrite the SQL query syntax, but this doesn't appear to be the case.
    Yes, I've noticed that modifying the record selection will change the sql query. The only way I can see to change the database name in the query is to change to the desired databsource and then remove and re-insert the tables, which will then update the query with the correct name. However, this seems to be a convoluted way of changing the db name in the query.

  • SQL Query rewrite, remove ORDER BY clause

    Hello,
    we've just installed a proprietary application which uses an Oracle 11.2.0.2 RAC database. We've seen that one of the auto-generated application's queries
    has poor performance (3-5 minutes for results), the query does a SELECT and at the end it uses an ORDER BY clause. If we remove the ORDER BY clause
    the query returns the results in less than 5 seconds. Unfortunately, we can't re-write the query in the application since we don't have any access to it and
    i was wondering if there is a way to rewrite the specific query from the database.
    We've already seen the SQL Patch but we can change only the hints of the query so we can't remove the ORDER BY clause from it. From what we've seen
    outlines also change only the hints and not the actual sql statement.
    Is there a way to rewrite the specific query from the database ?
    thanks in advance,
    Giannis

    Maybe DBMS_ADVANCED_REWRITE can help but this a SQL question than has very likely nothing to do with RAC.
    See http://www.oracle-base.com/articles/10g/dbms_advanced_rewrite.php.

  • SQL - Query rewrite ?

    Hi
    I have this query
    SELECT a.col1,
    a.col2,
    a.col3,
    a.col4
    FROM table1 a
    WHERE a.id = (SELECT MAX (id)
    FROM table1
    WHERE table1.datecol <= p_date AND table1.col5 = p_number);
    This is a cursor in a function so p_date and p_number are in parameters.
    In the example above table1 contains abot 300 million rows, and the query does 2 scans
    of the table1.
    Is there anyway to rewrite this SQL statment with one access only ?

    Both query will not give the same results
    WITH table1 AS
    (select 1 id, 1 col1, 1 col2, 1 col3, 1 col4, 1 col5, to_date('01/01/2011','dd/mm/yyyy') datecol from dual
    union
    select 1 id, 2 col1, 2 col2, 2 col3, 2 col4, 2 col5, to_date('02/01/2011','dd/mm/yyyy') datecol from dual
    union
    select 3 id, 3 col1, 3 col2, 3 col3, 3 col4, 3 col5, to_date('03/01/2011','dd/mm/yyyy') datecol from dual
    union
    select 4 id, 4 col1, 4 col2, 4 col3, 4 col4, 3 col5, to_date('03/01/2011','dd/mm/yyyy') datecol from dual
    SELECT a.col1,
    a.col2,
    a.col3,
    a.col4
    FROM table1 a
    WHERE a.id = (SELECT MAX (id)
    FROM table1
    WHERE table1.datecol <= to_date('03/01/2011','dd/mm/yyyy')
    AND table1.col5 = 3);
    WITH table1 AS
    (select 1 id, 1 col1, 1 col2, 1 col3, 1 col4, 1 col5, to_date('01/01/2011','dd/mm/yyyy') datecol from dual
    union
    select 1 id, 2 col1, 2 col2, 2 col3, 2 col4, 2 col5, to_date('02/01/2011','dd/mm/yyyy') datecol from dual
    union
    select 3 id, 3 col1, 3 col2, 3 col3, 3 col4, 3 col5, to_date('03/01/2011','dd/mm/yyyy') datecol from dual
    union
    select 4 id, 4 col1, 4 col2, 4 col3, 4 col4, 3 col5, to_date('03/01/2011','dd/mm/yyyy') datecol from dual
    SELECT * FROM
    (SELECT
    a.id,
    max(a.id) over (partition by a.id order by a.id) maxid,
    a.col1,
    a.col2,
    a.col3,
    a.col4,
    a.datecol,
    a.col5 
    FROM table1 a)
    WHERE datecol <= to_date('03/01/2011','dd/mm/yyyy')
        AND col5 =3    
        AND id = maxid;Best regards
    Mohamed Houri

  • A table is 'stuck' in the Discoverer SQL query after rewriting query.

    Hi,
    I'm using Discoverer 10.1.2.2 on an Oracle 9.2.0.6.0 DB.
    I've taken an existing Work Book and modified it. I've removed several fields as well as their table from the 'Selected Items' Window. I've also removed any references to all fields in that table in all Calculations and Conditions.
    Yet when I pull the SQL from the View: SQL Inspector That table still shows up and well as the join to it and a field from that table that I'm no longer using shows up as a field in the query. I'm not sure where else to check or what else to to do get this table out of this SQL query.
    Does anyone have any suggestions?

    Hi
    This can happen when someone has drilled inside a worksheet and saved the worksheet. The original or drilled to items are remembered,sometimes long after the drill item has been dispensed with. When this happens typically the only way to remedy the situation is to rebuild the worksheet from scratch.
    Before you get into that you do need to do one final scour to make sure that there is absolutely nothing in your worksheet that could cause the folder to be used. It could be in a long forgotten calculation. Sometimes when the only way to get from one folder to another one has to go via an intermediate folder by pulling any old item and then removing the item later. The folder willstill be used though. Could this be happening here?
    If you can rule out everything from the above paragraph then I am sorry to say but it sounds like you may have to rebuild from scratch.
    Best wishes
    Michael

  • SQL Query produces different results when inserting into a table

    I have an SQL query which produces different results when run as a simple query to when it is run as an INSERT INTO table SELECT ...
    The query is:
    SELECT   mhldr.account_number
    ,        NVL(MAX(DECODE(ap.party_sysid, mhldr.party_sysid,ap.empcat_code,NULL)),'UNKNWN') main_borrower_status
    ,        COUNT(1) num_apps
    FROM     app_parties ap
    SELECT   accsta.account_number
    ,        actply.party_sysid
    ,        RANK() OVER (PARTITION BY actply.table_sysid, actply.loanac_latype_code ORDER BY start_date, SYSID) ranking
    FROM     activity_players actply
    ,        account_status accsta
    WHERE    1 = 1
    AND      actply.table_id (+) = 'ACCGRP'
    AND      actply.acttyp_code (+) = 'MHLDRM'
    AND      NVL(actply.loanac_latype_code (+),TO_NUMBER(SUBSTR(accsta.account_number,9,2))) = TO_NUMBER(SUBSTR(accsta.account_number,9,2))
    AND      actply.table_sysid (+) = TO_NUMBER(SUBSTR(accsta.account_number,1,8))
    ) mhldr
    WHERE    1 = 1
    AND      ap.lenapp_account_number (+) = TO_NUMBER(SUBSTR(mhldr.account_number,1,8))
    GROUP BY mhldr.account_number;      The INSERT INTO code:
    TRUNCATE TABLE applicant_summary;
    INSERT /*+ APPEND */
    INTO     applicant_summary
    (  account_number
    ,  main_borrower_status
    ,  num_apps
    SELECT   mhldr.account_number
    ,        NVL(MAX(DECODE(ap.party_sysid, mhldr.party_sysid,ap.empcat_code,NULL)),'UNKNWN') main_borrower_status
    ,        COUNT(1) num_apps
    FROM     app_parties ap
    SELECT   accsta.account_number
    ,        actply.party_sysid
    ,        RANK() OVER (PARTITION BY actply.table_sysid, actply.loanac_latype_code ORDER BY start_date, SYSID) ranking
    FROM     activity_players actply
    ,        account_status accsta
    WHERE    1 = 1
    AND      actply.table_id (+) = 'ACCGRP'
    AND      actply.acttyp_code (+) = 'MHLDRM'
    AND      NVL(actply.loanac_latype_code (+),TO_NUMBER(SUBSTR(accsta.account_number,9,2))) = TO_NUMBER(SUBSTR(accsta.account_number,9,2))
    AND      actply.table_sysid (+) = TO_NUMBER(SUBSTR(accsta.account_number,1,8))
    ) mhldr
    WHERE    1 = 1
    AND      ap.lenapp_account_number (+) = TO_NUMBER(SUBSTR(mhldr.account_number,1,8))
    GROUP BY mhldr.account_number;      When run as a query, this code consistently returns 2 for the num_apps field (for a certain group of accounts), but when run as an INSERT INTO command, the num_apps field is logged as 1. I have secured the tables used within the query to ensure that nothing is changing the data in the underlying tables.
    If I run the query as a cursor for loop with an insert into the applicant_summary table within the loop, I get the same results in the table as I get when I run as a stand alone query.
    I would appreciate any suggestions for what could be causing this odd behaviour.
    Cheers,
    Steve
    Oracle database details:
    Oracle Database 10g Release 10.2.0.2.0 - Production
    PL/SQL Release 10.2.0.2.0 - Production
    CORE 10.2.0.2.0 Production
    TNS for 32-bit Windows: Version 10.2.0.2.0 - Production
    NLSRTL Version 10.2.0.2.0 - Production
    Edited by: stevensutcliffe on Oct 10, 2008 5:26 AM
    Edited by: stevensutcliffe on Oct 10, 2008 5:27 AM

    stevensutcliffe wrote:
    Yes, using COUNT(*) gives the same result as COUNT(1).
    I have found another example of this kind of behaviour:
    Running the following INSERT statements produce different values for the total_amount_invested and num_records fields. It appears that adding the additional aggregation (MAX(amount_invested)) is causing problems with the other aggregated values.
    Again, I have ensured that the source data and destination tables are not being accessed / changed by any other processes or users. Is this potentially a bug in Oracle?Just as a side note, these are not INSERT statements but CTAS statements.
    The only non-bug explanation for this behaviour would be a potential query rewrite happening only under particular circumstances (but not always) in the lower integrity modes "trusted" or "stale_tolerated". So if you're not aware of any corresponding materialized views, your QUERY_REWRITE_INTEGRITY parameter is set to the default of "enforced" and your explain plan doesn't show any "MAT_VIEW REWRITE ACCESS" lines, I would consider this as a bug.
    Since you're running on 10.2.0.2 it's not unlikely that you hit one of the various "wrong result" bugs that exist(ed) in Oracle. I'm aware of a particular one I've hit in 10.2.0.2 when performing a parallel NESTED LOOP ANTI operation which returned wrong results, but only in parallel execution. Serial execution was showing the correct results.
    If you're performing parallel ddl/dml/query operations, try to do the same in serial execution to check if it is related to the parallel feature.
    You could also test if omitting the "APPEND" hint changes anything but still these are just workarounds for a buggy behaviour.
    I suggest to consider installing the latest patch set 10.2.0.4 but this requires thorough testing because there were (more or less) subtle changes/bugs introduced with [10.2.0.3|http://oracle-randolf.blogspot.com/2008/02/nasty-bug-introduced-with-patch-set.html] and [10.2.0.4|http://oracle-randolf.blogspot.com/2008/04/overview-of-new-and-changed-features-in.html].
    You could also open a SR with Oracle and clarify if there is already a one-off patch available for your 10.2.0.2 platform release. If not it's quite unlikely that you are going to get a backport for 10.2.0.2.
    Regards,
    Randolf
    Oracle related stuff blog:
    http://oracle-randolf.blogspot.com/
    SQLTools++ for Oracle (Open source Oracle GUI for Windows):
    http://www.sqltools-plusplus.org:7676/
    http://sourceforge.net/projects/sqlt-pp/

  • Problem using alias field names in a sql query

    Hello,
    I have a question regarding a simple Oracle database SQL query writeup:
    In the following (badly written but properly working) SQL query:
    Query 1:
    select
    soe.field1,
    (soe.field2 + soe.field3) as field4,
    (soe.field5 - (soe.field2 + soe.field3)) as field6,
    (select comp.parValue*soe.field7
    from
    CompTable comp) as parValue,
    (select soe.field8 - (comp.parValue*soe.field7+ soe.field9)
    from
    CompTable comp) as field10
    from
    SomeTable soe
    PROBLEM 1:
    I am re writing the code (soe.field2 + soe.field3) to get the alias field4 or column name field4 that I have created on the fly in the previously for use with the following fields. Can't I rewrite the query as follows. There is something simple missing!
    Query 2:
    select
    soe.field1,
    (soe.field2 + soe.field3) as field4,
    soe.field5 - field4 as field6, <<< field4 does not work here
    (select
    comp.parValue*soe.field7
    from
    CompTable comp) as parValue,
    (select
    soe.field8 - (comp.parValue*soe.field7+ soe.field9)
    from
    CompTable comp) as field10
    from
    SomeTable soe
    PROBLEM 2:
    Similar to the above problem, I was thinking to get a field parValue out of the CompTable table and re-use many times rather than the code shown in Query 1:
    Query 3:
    select
    soe.field1,
    (soe.field2 + soe.field3) as field4,
    soe.field5 - field4 as field6,
    soe.field7* (select comp.parValue from CompTable comp) as parValue1,
    soe.field8 - (parValue1*soe.field7+ soe.field9) as field10      <<<< parvalue1 does not work here
    parValue1*soe.field9 as TaxCondition               <<<< parvalue1 does not work here
    from
    SomeTable soe
    See that the query becomes so simple, but the above query does not work. There is something fundamentally wrong in my usage of the alias field names in creating other fields. The Query1 seems to be the only working option but its very slow as I am redoing and re-writing the whole code again and again to get the parValue field out of the CompTable table for use to create many other fields.
    I will appreciate if you can guide me in the right direction on this issue.
    Thanks and Regards
    Rama

    SELECT tmp.contract_no, tmp.Actual, tmp.Actual - tmp.NbHours
    FROM ( SELECT t.contract_no, sum(l.hrs) AS Actual, (c.labour_hours * c.labour_progress_per) / 100 AS NbHours
    FROM TASK_DELEGATION t
    INNER JOIN COST_CODE c
    ON t.cost_code = c.cost_code AND t.contract_no = c.contract_no AND t.is_inactive=0
    INNER JOIN Labour.dbo.LABOURALLOT l
    ON l.contractNo = c.contract_no AND l.costcode = c.cost_code AND l.pm = 'N'
    GROUP BY t.contract_no, c.labour_hours, c.labour_progress_per
    ) tmp

  • Pl/sql function body returning SQL query - Print function

    Hello all,
    I have pl/sql function body returning SQL query for my reports for my new project that I am developing. We dont have any BI tool or anything for APEX so we use Oracle reports to get the same reports to be printed in PDF format. I had been using SQL function for Reports all these days and grabbing the data using SQL query was easy in Oracle reports. But this time we had atleast 8 fields in search criteria and hence I thouhgt PL/sql function body returning SQL query could be something easy to handle that scenario. We have 11 such reports in our project. Now when we tried to use the same PL/sql function to oracle reports , I was told by one of our Oracle reports expert, that we have to write it into functions and use it in SQL query to get the Reports in Oracle reports. Is there any Easy way to convert the same Pl/SQL function or get a PDF format of the same report in APEX without going thru the much pains of rewriting the whole SQL Query.
    thank you
    Devisri

    Hi,
    give this a go.
    I can't test it as I don't have the tables in my schema.
    create or replace package MK_TEST_PF is
    -- Author  : MK
    -- Created : 21/06/2010 16:30:19
    -- Purpose : FOR LUCY_DISCOVER
    -- Public type declarations
    /*     -- just guess the table row types.....
         -- otherwise it won't compile
         type test_rec is record
              (INV REP.inv%type
              ,cNUMBER REP.cNUMBER%type
              ,OPENDATE REP.OPENDATE%type
              ,TARGETDATE REP.ESTCOMPLETE%type
              ,DATECLOSED REP.COMPLETED%type
              ,STATUS REP.STATUS%type
              ,cCODE REP.cCODE%type
              ,line varchar2(4000)
              ,SIGc varchar2(4000)
              ,CLASS REP.CLASS%type
              ,SUMM REP.SUMM%type
              ,AREA REP.AREA%type
         type test_rec is record
              (INV varchar2(4000)
              ,cNUMBER varchar2(4000)
              ,OPENDATE varchar2(4000)
              ,TARGETDATE varchar2(4000)
              ,DATECLOSED varchar2(4000)
              ,STATUS varchar2(4000)
              ,cCODE varchar2(4000)
              ,line varchar2(4000)
              ,SIGc varchar2(4000)
              ,CLASS varchar2(4000)
              ,SUMM varchar2(4000)
              ,AREA varchar2(4000)
         type test_tab is table of test_rec;
    -- Public constant declarations
    -- Public variable declarations
    -- Public function and procedure declarations
    end MK_TEST_PF;
    create or replace package body MK_TEST_PF is
    -- Private type declarations
    -- Private constant declarations
    -- Private variable declarations
    -- Function and procedure implementations
         function get_query_f
              (p_inv VARCHAR2 := UPPER(v('P44_INV'))
              ,p_reg VARCHAR2 := UPPER(v('P44_CLASS'))
              ,p_proarea VARCHAR2 := UPPER(v('P44_PROGRAM_AREA'))
              ,p_disp VARCHAR2 := UPPER(v('P44_DISPOSITION'))
              ,p_coding VARCHAR2 := UPPER(v('P44_CODING'))
              ,p_status VARCHAR2 := UPPER(v('P44_STATUS'))
              ,p_SIG VARCHAR2 := UPPER(v('P44_SIG_c'))
              ,p_inc_sum VARCHAR2 := UPPER(v('P44_INCLUDE_SUMM_FIELD'))
              ,p_word VARCHAR2 := UPPER(v('P44_WORD_IN_SUMM'))
              ,p_timeframe VARCHAR2 := UPPER(v('P44_TIME_FRAME'))
              ,p_rec VARCHAR2 := UPPER(v('P44_RECORD_KEEPING'))
              ,p_WORD_IN_SUMM VARCHAR2 := UPPER(v('P44_WORD_IN_SUMM'))
              ,p_ON_AFTER VARCHAR2 := UPPER(v('P44_ON_AFTER'))
              ,p_ON_BEFORE VARCHAR2 := UPPER(v('P44_ON_BEFORE'))
              return varchar2
         is
              v_sql VARCHAR2(5000);
         --     v_inv VARCHAR2(100);
         --     v_reg VARCHAR2(100);
         --     v_proarea VARCHAR2(100);
         --     v_status VARCHAR2(100);
         --     v_SIG VARCHAR2(100);
         --     v_disp VARCHAR2(100);
         --     v_coding VARCHAR2(100);
         --     v_inc_sum VARCHAR2(4);
         --     v_word VARCHAR2(4000);
              v_wildcard VARCHAR2(2000);
         --     v_timeframe VARCHAR2(100);
         --     v_rec VARCHAR2(5);
              v_record VARCHAR2(5);
              v_open VARCHAR2(100);
              v_closed VARCHAR2(100);
              v_PEND VARCHAR2(100);
              v_refSIG VARCHAR2(100);
              v_refreg VARCHAR2(100);
              v_refother VARCHAR2(100);
              v_y varchar2(100);
         BEGIN
              --v_inv := UPPER(v('P44_INV')) ;
              v_record := 'R%';
              v_wildcard := '%';
              v_open := 'OPEN';
              v_closed := 'CLOSED';
              v_PEND := 'PEND';
              v_refSIG := 'REF - SIG';
              v_refreg := 'REF - CLASS';
              v_refother := 'REF - OTHER';
              v_y := 'Y';
              v_sql := 'SELECT REP.INV as INV, REP.cNUMBER as cNUMBER, REP.OPENDATE as OPENDATE,
              REP.ESTCOMPLETE as TARGETDATE, REP.COMPLETED as DATECLOSED, REP.STATUS as STATUS,
              REP.cCODE as cCODE, apex_item.checkbox(1,REP.line,null,'''||v_y||''') line , apex_item.checkbox(1,REP.SIG,null,'''||v_y||''') SIGc ,
              REP.CLASS as CLASS, REP.SUMM as SUMM, REP.AREA as AREA from REP where 1=1';
              IF p_rec is not null then
                   IF p_rec = 'E' then
                        v_sql := v_sql|| ' and upper(REP.cnumber) not like '''||v_record||'''';
                   ELSIF p_rec = 'D' then
                        v_sql := v_sql|| ' and upper(REP.cnumber) like '''||v_record||'''';
                   ELSIF p_rec = 'I' then
                        v_sql := v_sql|| ' and REP.cnumber = REP.cnumber ';
                   end if ;
              end if ;
              IF upper(p_status) not like '%NULL%' then
                   IF upper(p_status) like '%OPEN%' then
                   v_sql := v_sql||' AND upper(REP.status) like '''||v_open||'''';
                   ELSIF upper(p_status) like '%CLOSED%' then
                   v_sql := v_sql||' AND upper(REP.status) like '''||v_closed||'''';
                   ELSIF upper(v_PEND) like '%PEND%' then
                   v_sql := v_sql||' AND upper(REP.status) like '''||v_PEND||'''';
                   ELSIF upper(v_refSIG) like '%REF - SIG%' then
                   v_sql := v_sql||' AND upper(REP.status) like '''||v_refSIG||'''';
                   ELSIF upper(v_refreg) like '%REF - CLASS%' then
                   v_sql := v_sql||' AND upper(REP.status) like '''||v_refreg||'''';
                   ELSIF upper(v_refother) like '%REF - OTHER%' then
                   v_sql := v_sql||' AND upper(REP.status) like '''||v_refother||'''';
                   END IF ;
              END IF ;
              IF p_inv = 'NULL' THEN
                   v_sql := v_sql||' AND instr(upper(REP.INV),'''||p_inv||''') > 0';
              END IF ;
              IF p_reg = 'NULL' THEN
                   v_sql := v_sql||' AND instr(upper(REP.CLASS),'''||p_reg||''') > 0';
              END IF ;
              IF p_proarea = 'NULL' THEN
                   v_sql := v_sql||' AND instr(upper(REP.AREA),'''||p_proarea||''') > 0';
              END IF ;
              IF p_disp = 'NULL' THEN
                   v_sql := v_sql||' AND instr(upper(REP.disposition),'''||p_disp||''') > 0';
              END IF ;
              IF p_coding = 'NULL' THEN
                   v_sql := v_sql||' AND instr(upper(REP.ccode),'''||p_coding||''') > 0';
              END IF ;
              IF p_SIG = ' ' THEN
                   v_sql := v_sql||' AND instr(upper(REP.SIG),'''||p_SIG||''') > 0';
              END IF ;
              IF p_word is not null then
                   v_sql := v_sql|| ' and
                   instr(upper(REP.SUMM),
                   upper(nvl('''||p_WORD_IN_SUMM||''',REP.SUMM))) > 0';
              end if ;
              If p_timeframe is not null then
                   if upper(p_timeframe) = 'OPEN' then
                   v_sql := v_sql|| ' and to_date(REP.opendate) between to_date ('''||p_ON_AFTER||''') and to_date('''||p_ON_BEFORE||''')';
                   elsif upper(p_timeframe) = 'CLOSED' then
                   v_sql := v_sql|| ' and to_date(REP.completed) between to_date ('''||p_ON_AFTER||''') and to_date('''||p_ON_BEFORE||''')';
                   elsif upper(p_timeframe) = 'EST' then
                   v_sql := v_sql|| ' and to_date(REP.estcomplete) between to_date ('''||p_ON_AFTER||''') and to_date('''||p_ON_BEFORE||''')';
                   end if;
              end if;
              v_sql := v_sql ||' order by REP.INV ';
              return v_sql;
         end get_query_f;
         function test_pf
              (p_inv VARCHAR2 := UPPER(v('P44_INV'))
              ,p_reg VARCHAR2 := UPPER(v('P44_CLASS'))
              ,p_proarea VARCHAR2 := UPPER(v('P44_PROGRAM_AREA'))
              ,p_disp VARCHAR2 := UPPER(v('P44_DISPOSITION'))
              ,p_coding VARCHAR2 := UPPER(v('P44_CODING'))
              ,p_status VARCHAR2 := UPPER(v('P44_STATUS'))
              ,p_SIG VARCHAR2 := UPPER(v('P44_SIG_c'))
              ,p_inc_sum VARCHAR2 := UPPER(v('P44_INCLUDE_SUMM_FIELD'))
              ,p_word VARCHAR2 := UPPER(v('P44_WORD_IN_SUMM'))
              ,p_timeframe VARCHAR2 := UPPER(v('P44_TIME_FRAME'))
              ,p_rec VARCHAR2 := UPPER(v('P44_RECORD_KEEPING'))
              ,p_WORD_IN_SUMM VARCHAR2 := UPPER(v('P44_WORD_IN_SUMM'))
              ,p_ON_AFTER VARCHAR2 := UPPER(v('P44_ON_AFTER'))
              ,p_ON_BEFORE VARCHAR2 := UPPER(v('P44_ON_BEFORE'))
              RETURN test_tab PIPELINED
         is
              type test_c is ref cursor;
              v_row test_tab;
              v_sql varchar2(4000);
              v_cursor test_c;
         begin
              v_sql := get_query_f
                   (p_inv
                   ,p_reg
                   ,p_proarea
                   ,p_disp
                   ,p_coding
                   ,p_status
                   ,p_SIG
                   ,p_inc_sum
                   ,p_word
                   ,p_timeframe
                   ,p_rec
                   ,p_WORD_IN_SUMM
                   ,p_ON_AFTER
                   ,p_ON_BEFORE
              open v_cursor for v_sql;
              fetch v_cursor bulk collect into v_row;
              close v_cursor;
              for i in 1 .. v_row.count loop
                   pipe row (v_row(i));
              end loop;
              return;
         end test_pf;
    end MK_TEST_PF;
    /Regards
    Michael

  • Command the execute sql query and does not clean up data in Table

    Hi Team
    I have an SP, which writes source and target data to Temp Tables and runs except query to get mismatch details
    I am using Exec command to execute source query that writes data to Temp Table, once I execute query using Exec, data is written and immediately #temp table is cleaned, now I cannot use #temp table for comparition.
    Is there any way to execute sql query in SP without using EXEC and will hold the data in temp table.

    You need to create temp table before EXEC statement and rewrite your dynamic query also as below
    declare @source_Sql nvarchar(1000)
    ,@target_Sql nvarchar(1000)
    create table #TempTable1 (name nvarchar(10))
    create table #TempTable2 (name nvarchar(10))
    set @source_Sql = 'INSERT INTO #TempTable1 SELECT [Name] from Employee'
    set @target_Sql = 'INSERT INTO #TempTable2 SELECT [Name] from Employee2'
    EXEC (@source_Sql)   
    EXEC (@target_Sql)             
    select * from #TempTable1 
     Except 
    select * from #TempTable2

  • Can I rewrite the following query without using Row_number() function ??!!

    Hello every one, can I rewrite the following query without using the 'ROW_NUMBER() OVER ' part.
    The query is supposed to pull out the records whose CODE is not NULL and has most
    recent date for UPDATE_DATE . The reason I wanted to do this is, When I embed this query
    in between many other queries along with JOINs, My oracle server is unable to execute. So, I thought
    its better to supplant 'ROW_NUMBER() OVER ' logic with something else and try it. .
    SELECT a.* FROM
    (SELECT b.*, ROW_NUMBER() OVER (PARTITION BY b.PIDM
    ORDER BY b.UPDATE_DATE DESC) AS Rno
    FROM
    SELECT *
    FROM SHYNCRO WHERE CODE IS NOT NULL
    )b
    )a
    WHERE a.Rno = 1

    Hi,
    You didn't write over 150 lines of code and then start testing it, did you?
    Don't.
    Take baby steps. Write as little as pssiblem test that. Debug and test again until you have something that does exactly what you want it to do.
    When you have somehting that works perfectly, take one baby step. Add a tiny amount of code, maybe 1 or 2 lines more, and test again.
    When you do get an error, or wrong results, you'll have a much better idea of where the problem is. also, you won't be building code on a flimsy foundation.
    If you need help, post the last working version and the new version with the error. Explain what you're trying to do in the new version.
    The error message indicates line 133. It looks like line 133 of your code is blank. Does your front end allow completely blank lines in the middle of a query? SQL*Plus doesn't by default; you have to say
    SET  SQLBLANKLINES  ONto have a completely blank line in SQL*Plus. (However, lines containing nothing but at commnet are always allowed.)
    You may have noticed that this site normally doesn't display multiple spaces in a row.
    Whenever you post formatted text (such as indented code) on this site, type these 6 characters:
    \(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.
    The 4 people who posted small code fragments for you to read all did this.  It would be so much easier for people to read your humongeous query if it were formatted.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to improve performance of this SQL query?

    Hi,
    I have a query that tries to build a string (RPATH) for use as a url parameter. The query is:
    SELECT DISTINCT USERNAME, PASSWORD, ROLE, RIGHTS,
    DECODE(GEO, ROLE, 'g='||NVL(GEO,'none'), NULL)||
         DECODE(AREA, ROLE, 'g='||NVL(GEO,'none')||'&a='||NVL(AREA,'none'), NULL)||
         DECODE(REGION, ROLE, 'g='||NVL(GEO,'none')||'&a='||NVL(AREA,'none')||'&r='||NVL(REGION,'none'), NULL)||
         DECODE(DISTRICT, ROLE, 'g='||NVL(GEO,'none')||'&a='||NVL(AREA,'none')||'&r='||NVL(REGION,'none')||'&d='||NVL(DISTRICT,'none'), NULL)||
         DECODE(OFFICE, ROLE, 'g='||NVL(GEO,'none')||'&a='||NVL(AREA,'none')||'&r='||NVL(REGION,'none')||'&d='||NVL(DISTRICT,'none')||'&o='||NVL(OFFICE,'none')
    , NULL) RPATH
    FROM (SELECT U.*, L.*
         FROM (SELECT * FROM T_USERS WHERE USERNAME='xxx' AND PASSWORD='yyy') U, T_LOC_SUB L
         WHERE U.ROLE IN ('WW', L.GEO, L.AREA, L.REGION, L.DISTRICT, L.OFFICE))
    GROUP BY USERNAME, PASSWORD, ROLE, RIGHTS, GEO, AREA, REGION, DISTRICT, OFFICE;
    T_USERS is defined as
    CREATE TABLE T_USERS (
    username          VARCHAR2(10)     CONSTRAINT T_USERS_username_pk PRIMARY KEY,
    password          VARCHAR2(10),
    role                    CONSTRAINT T_USERS_role_FK REFERENCES T_LOC_MAIN(loc),
    rights          VARCHAR2(3)
    T_LOC_SUB is defined as
    CREATE TABLE T_LOC_SUB (
    geo          CONSTRAINT T_LOC_SUB_geo_FK REFERENCES T_LOC_MAIN(loc),
    area          CONSTRAINT T_LOC_SUB_area_FK REFERENCES T_LOC_MAIN(loc),
    region          CONSTRAINT T_LOC_SUB_region_FK REFERENCES T_LOC_MAIN(loc),
    district     CONSTRAINT T_LOC_SUB_district_FK REFERENCES T_LOC_MAIN(loc),
    office          CONSTRAINT T_LOC_SUB_office_FK REFERENCES T_LOC_MAIN(loc)
    T_LOC_MAIN is defined as
    CREATE TABLE T_LOC_MAIN (
    loc          VARCHAR2(4)     CONSTRAINT T_LOC_MAIN_loc_PK PRIMARY KEY,
    label          VARCHAR2(60),
    rank          NUMBER
    REGION and DISTRICT columns in T_LOC_SUB may be NULL at times. How can I rewrite the SQL to make it run faster or more efficiently?
    Please help.. Thank you..

    Hi,
    I just realised I can simplify the query to:
    SELECT DISTINCT USERNAME, PASSWORD, ROLE, RIGHTS,
    DECODE(ROLE,
         GEO, 'g='||NVL(GEO,'none'),
         AREA, 'g='||NVL(GEO,'none')||'&a='||NVL(AREA,'none'),
         REGION, 'g='||NVL(GEO,'none')||'&a='||NVL(AREA,'none')||'&r='||NVL(REGION,'none'),
         DISTRICT, 'g='||NVL(GEO,'none')||'&a='||NVL(AREA,'none')||'&r='||NVL(REGION,'none')||'&d='||NVL(DISTRICT,'none'),
         OFFICE, 'g='||NVL(GEO,'none')||'&a='||NVL(AREA,'none')||'&r='||NVL(REGION,'none')||'&d='||NVL(DISTRICT,'none')||'&o='||NVL(OFFICE,'none'),
         NULL) RPATH
    FROM (SELECT U.*, L.*
    FROM (SELECT * FROM T_USERS WHERE USERNAME='xxx' AND PASSWORD='yyy') U, T_LOC_SUB L
    WHERE U.ROLE IN ('WW', L.GEO, L.AREA, L.REGION, L.DISTRICT, L.OFFICE))
    GROUP BY USERNAME, PASSWORD, ROLE, RIGHTS, GEO, AREA, REGION, DISTRICT, OFFICE;
    Anyone can offer a better and more efficient improvement?
    Thanx!

  • Need help with sql query dates

    Hi,
    I have a sql query where i need to extract some info between given dates. The where clause of this query is as follows:
    WHERE CPD_BUS_UNIT=:ESI_PRM_1
    AND CPD_VOUCHER_DATE >= :P_DATE_FROM
    AND CPD_VOUCHER_DATE < (:P_DATE_TO+1)
    When i execute the query in toad, i can view the data but not the execution plan.It gives an error ORA-00932-Inconsistent Datatypes.
    But when i remove (+1) from :P_DATE_TO, i can c the execution plan and data. Will the data be different from the previous one.
    Please suggest how to rewrite the query.

    Can you please give it a try?
    WHERE CPD_BUS_UNIT=:ESI_PRM_1
    AND CPD_VOUCHER_DATE >= :to_date(P_DATE_FROM)
    AND CPD_VOUCHER_DATE < (to_date(:P_DATE_TO)+1) Regards

Maybe you are looking for