With clause within proc

Hi Gurus
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - Prod
I am trying to create a procedure that I would run occasionally for reporting purposes, the procedure is going to populate test_stats table, which then will be accessed through Excel.
Following code gives out an error. I think it is regarding WITH clause...
ERROR line 10, col 12, ending_line 10, ending_col 12, Found 'x', Expecting: ( or SELECT VALUES
1. Is wrapping up all insert statements into one proc a good idea? Other options?
2. I have checked the oracle docs and I didnt see any restriction regarding the use of WITH within proc. What is the cause of the error?
test_stats has only one column NUMBER.
CREATE OR REPLACE PROCEDURE test_stats_1
IS
BEGIN
   INSERT INTO test_stats
      WITH x AS
           (SELECT count(*) cnt
              FROM DUAL) --some complex query
      SELECT cnt
        FROM x;
END;
/ Thanks
T

zx8754 wrote:
My client version is:
DEFINE _SQLPLUS_RELEASE = "1002000400" (CHAR)It is higher value than yours, does this mean mine is newer?
btw, that INSERT statement on its own without proc works fine.
Edited by: zx8754 on 02-Jul-2010 03:10What is your exact database version? The client version shouldn't matter.
I had a similiar problem once in oracle 9.2.0.3. The SQL syntax inside PL was slightly behind the normal SQL syntax. This lead to the effect that I could run a specific SQL statement in SQL*PLUS but not from inside a package. At this time it had been the order clause of the XMLAGG function. This was a bug and was fixed in a later version (9.2.0.4 or 9.2.0.8).
Maybe you have a similiar issue, also I thought that this versioning conflict was fixed in Oracle 10.x.
btw it works for me:
SQL*Plus: Release 10.2.0.1.0 - Production on Fri Jul 2 16:57:54 2010
Copyright (c) 1982, 2005, Oracle.  All rights reserved.
Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
xxx@yyy> CREATE OR REPLACE PROCEDURE test_stats_1
  2  IS
  3  BEGIN
  4     INSERT INTO test_stats
  5  WITH x AS
  6             (SELECT count(*) cnt
  7                FROM DUAL) --some complex query
  8        SELECT cnt
  9          FROM x;
10  END;
11  /
Procedure created.
xxx@yyy> Edited by: Sven W. on Jul 2, 2010 4:59 PM

Similar Messages

  • With clause within the cursor ???

    Hello gurus,
    Can we have a with clause within the cursor ???
    something like this ..
    cursor test_cur is
    WITH unpivoted_data     AS
         SELECT DISTINCT
    f.cust_id
              f.office_cd
              f.type_cd
         FROM      refoff      ro,
              cutomer     p,
              office     f
         WHERE     f.cust_id     = p.cust_id
         AND     f.office_cd      = ro.office_cd
         AND      f.type_cd      IN ('ACCT', 'pay')
    SELECT     cust_id
    ,     MAX (CASE WHEN type_cd = 'ACCT' THEN office_id END)     AS acct_office_id
    ,     MAX (CASE WHEN type_cd = 'pay' THEN office_id END)     AS pay_office_id
    FROM     unpivoted_data
    GROUP BY cust_id
    test_cur_rec test_cur% rowtype;
    Begin
    for test_cur_rec in test_cur
    loop
    insert into test1 (.....) values (.......);
    end loop;
    end;
    One more quick question .... How do u guys past in the posting ??? Like somesought of a box .....I have seen lot senior gurus when they are replying, they post the code in some sought of a box ....that makes very easy to understand and take look at the code in the posting....???
    Thank you so much!!!

    Hi,
    user642297 wrote:
    Hello gurus,
    Can we have a with clause within the cursor ???Sure, but don't take my word for it. Try it and see!
    If you get an error, post the error message.
    If you get unexpected results, explain.
    Whenever you have a problem, post your full Oracle version number.
    One more quick question .... How do u guys past in the posting ??? Like somesought of a box .....I have seen lot senior gurus when they are replying, they post the code in some sought of a box ....that makes very easy to understand and take look at the code in the posting....??? Type these 6 characters:
    (all small letters, inside curly brackets) before and after formatted sections.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • With Clause in Pro*C?

    Is it possible to use version 9's with clause (aka
    subquery factoring) within pro*C? Queries that work
    fine in SQL*Plus cause the pre-compiler to fail. For
    example:
    SQL> with test as (select 1 one from dual)
    2 select * from test
    3 /
    ONE
    1
    Taking the same query and embedding it in a Pro*C program,
    produces the following results:
    EXEC SQL
    with test as (select 1 one from dual)
    SELECT *
    INTO :n
    FROM test;
    $ proc ora_test.pc
    Pro*C/C++: Release 9.2.0.5.0 - Production on Mon Dec 20 13:27:16 2004
    Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.
    System default option values taken from: /ora/product/9.2.0/precomp/admin/pcscfg.cfg
    Syntax error at line 20, column 7, file ora_test.pc:
    Error at line 20, column 7 in file ora_test.pc
    with test as (select 1 one from dual)
    ......1
    PCC-S-02201, Encountered the symbol "with" when expecting one of the following:
    for, register, at, close, commit, connect, declare, describe,
    execute, fetch, open, prepare, rollback, select, whenever,
    alter, audit, comment, create, delete, drop, get, grant,
    insert, lock, noaudit, rename, revoke, set, update, validate,
    arraylen, allocate, cache, call, collection, context,
    deallocate, enable, free, lob, object, savepoint, analyze,
    explain, truncate,
    The symbol "alter," was substituted for "with" to continue.
    Parser error at line 22, column 15, file ora_test.pc:
    Error at line 22, column 15 in file ora_test.pc
    INTO :n
    ..............1
    PCC-S-02206, Host variables are not permitted within a DDL statement
    Error at line 0, column 0 in file ora_test.pc
    PCC-F-02102, Fatal error while doing C preprocessing

    I suppose that the 'with clause ' is a new feature of ORACLE9 ? Well, lets dive in the fabulous world of ORACLE development :
    When the parser of ORACLE9 has been enhanced to accept ORACLE9 new features and syntax (especially the SQL1999 join syntax), the parser of PRO*C and PRO*Cobol still stayed at the ORACLE8 syntax level. The parser is at the Precompiler side.
    This means that you have NO CHANCE to even precompile a ORACLE9 syntax SQL statement with any precompiler tool.
    This is not a bug (from metalink) because the Oracle Development project for the new parser has not been started yet. I the product is not developped, it is not a bug , and i understand that they cannot correct the flaw.
    This is not corrected in any known ORACLE10 version - just because the project has not yet started !!!
    The only workaround that i have found consists in using a View which contains the syntax. This works fine for JOIN queries, i do not have tested for the 'with clause'.
    Maybe other workarounds available at the metalink side.
    Regards
    Frederic

  • Report with multiplying columns  and WITH clause

    Hello
    I saw sth strange in my report. I assume that it could happens very often.
    I have report with few columns which two of them ar most complicated (many joins subqueries aggreagations on joined values etc.) These two columns (i.e C3,C4) should be multiplied (C3*C4).
    When i do pure report without multiplying only columns C1,C2,C3,C4 everything is ok - duration about 15 sec. but... when I put next column on report which multiply these columns (in Answers C5=C3*C4)
    I wait 3-4 minutes and my database hungs :(. After investigation I saw that in first case to databese goes pure "SELECT" statement it means:
    "Select ... as C1, ... as C2, max(...) as C3, sum(xxx)... C4 from yyy,sss,ttt WHERE aaa"
    but in second case BI uses WITH clause it means:
    WITH SAWITH0 AS
    ( Select ... as C1, ... as C2, max(...) as C3, sum(xxx)... C4 from yyy,sss,ttt WHERE aaa )
    SELECT SAWITH0.C1 as C1,
    SAWITH0.C2 as C2,
         SAWITH0.C3 as C3,
         SAWITH0.C4 as C4,
         SAWITH0.C3*SAWITH0.C4 as C5 FROM SSS
    and this statement is long runninq query and kills my database :(.
    I checked that SQL like this:
    Select ... as C1, ... as C2, max(...) as C3, sum(xxx)... C4, max(...)*sum(xxx)... As C5 from yyy,sss,ttt WHERE aaa" -
    runs few times faster than that above
    I know that I can do this multiply in business model layer but sometimes users can multiply(or other operations) on columns in reports without my knowledge and it kills my db :(. Where is bug? Why SQLs with WITH clause takes so much db time?
    Thank you for each kind of help

    WITH clause or Subquery Factoring allows the set of data to be reused multiple times within the SQL. Oracle will usually materialize the data into a temporary table (you will see it if you take an explain plan of the SQL).
    I would be surprised if it was the actual WITH clause that was causing the performance issue, however you can test this by turning the WITH clause feature off. Go to the Physical model, right mouse click on your Database > Properties > Features Tab, scroll down to WITH_CLAUSE_SUPPORTED and switch it off.
    I'd be interested to know if you do see actual improvement.
    Good Luck.

  • Use of WITH clause

    Hi,
    I am using Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 .
    I am working in a procedure where I want to manipulate the data produced by a WITH AS clause.  But it is giving "PL/SQL: ORA-00942: table or view does not exist" error. A small example to illustrate my problem is given below. Here in the example am just trying to get a replaced string by using the out put of a WITH AS clause.
    SET SERVEROUTPUT ON;
    DECLARE
    CNT INTEGER;
    LETTER CHAR(1);
    REPLACED_STRING VARCHAR2(10);
    BEGIN
    REPLACED_STRING := 'ABC';
    WITH T AS
      (SELECT 'ABC' VAL FROM DUAL),
      TMP (LEN, SUBVAL) AS
      (SELECT LENGTH(VAL) LEN,
        SUBSTR(VAL, 1, INSTR(VAL, 'B', 1, 1)) SUBVAL
       FROM T
       UNION ALL
       SELECT LENGTH(VAL)-1 LEN,
       SUBSTR(VAL, 2, INSTR(VAL, 'C', 1, 1)) SUBVAL
       FROM T
      SELECT COUNT(*) INTO CNT FROM TMP,T ;
      FOR I IN 1..CNT LOOP
      SELECT SUBSTR(SUBVAL,1,1) INTO LETTER FROM  TMP,T;
      SELECT REPLACE(REPLACED_STRING,LETTER,'X')INTO REPLACED_STRING FROM DUAL;
      DBMS_OUTPUT.PUT_LINE(REPLACED_STRING);
    END LOOP;
    END;
    I thought of declaring a cursor which will hold the data produced by WITH clause but it did not work. Can you please let me know what are the possible options to do this.
    Thanks

    I think, I can not use the WITH inside loop as, I want to manipulate on data resulted by WITH reading row by row from it. I have a complex procedure and I wont be able to explain that scenario here and thus i came up with a similar problem through a very simple example. I will try to explain my problem thru my example here.
    The WITH in my example give an out put as :
    SUBVAL
    AB
    BC
      WITH T AS
      (SELECT 'ABC' VAL FROM DUAL),
      TMP (LEN, SUBVAL) AS
      (SELECT LENGTH(VAL) LEN,
        SUBSTR(VAL, 1, INSTR(VAL, 'B', 1, 1)) SUBVAL
       FROM T
       UNION ALL
       SELECT LENGTH(VAL)-1 LEN,
       SUBSTR(VAL, 2, INSTR(VAL, 'C', 1, 1)) SUBVAL
       FROM T
      SELECT subval FROM TMP,T;
    and then by using this in the PLSQL block mentioned above
      FOR I IN 1..CNT LOOP
      SELECT SUBSTR(SUBVAL,1,1) INTO LETTER FROM  TMP,T;
      SELECT REPLACE(REPLACED_STRING,LETTER,'X')INTO REPLACED_STRING FROM DUAL;
      DBMS_OUTPUT.PUT_LINE(REPLACED_STRING);
      END LOOP;
    I want to have an output like:
    XBC
    XXC
    Please note that nature of my original problem is that I want to manipulate the data given by WITH clause in the same procedure by passing it to other functions/procs to get the desired result. So please advice me following this approach only which would be helpful.
    Thanks

  • Adding dynamic 'start with' clause in Hierarchial query in Discoverer 4i

    I have created a custom folder based upon the following hierarchial guery:
    SELECT supervisor_name, level
    FROM xxhr084_hr_emps_v
    START WITH supervisor_name = 'TEST SUPER'
    CONNECT BY prior person_id = supervisor_id
    ORDER SIBLINGS by supervisor_name
    I want the 'START WITH' value to be based upon a parameter i.e. the User enters the value of supervisor name at runtime.
    However, I can't use a parameter within the custom folder and I can't generate the 'start with' condition in my workbook.
    Anyone have a solution for populating the start with clause at run-time?
    Thanks,
    Kevin

    Can you create the custom folder without a condition on supervisor_name - i.e. without the supervisor_name = 'X' starts with clause - in the EUL, and then define the condition on the supervisor_name field within the report?
    SELECT supervisor_name, level
    FROM xxhr084_hr_emps_v
    CONNECT BY prior person_id = supervisor_id
    ORDER SIBLINGS by supervisor_name
    You can then restrict the results that the hierarchical query returns (from the custom folder) within the report, by adding a condition on supervisor_name.
    Hope that makes some sense.

  • Problems clause within (Intermedia text)

    I have problems using the clause within in a XML file. I suspect that is impossible for the intermedia text to find words within tags with attributes, could you help me, my friend?
    Thanks a lot.
    And Merry Christmas.

    Hi Ralf,
    please define first your own preferences like this:
    exec CTX_DDL.drop_preference('MY_LEXER');
    exec CTX_DDL.create_preference('MY_LEXER','BASIC_LEXER');
    exec CTX_DDL.set_attribute('MY_LEXER','ALTERNATE_SPELLING',
    'GERMAN');
    exec CTX_DDL.set_attribute('MY_LEXER','BASE_LETTER','YES');
    exec CTX_DDL.set_attribute('MY_LEXER','MIXED_CASE', 'NO');
    exec CTX_DDL.set_attribute('MY_LEXER','INDEX_THEMES','NO');
    exec CTX_DDL.set_attribute('MY_LEXER','INDEX_TEXT', 'YES');
    exec CTX_DDL.set_attribute('MY_LEXER','COMPOSITE', 'GERMAN');
    exec ctx_ddl.Drop_Preference ('MY_FILTER');
    exec ctx_ddl.Create_Preference ('MY_FILTER','NULL_FILTER');
    exec ctx_ddl.drop_section_group ('MY_SECTION');
    exec ctx_ddl.create_section_group
    ('MY_SECTION','NULL_SECTION_GROUP');
    and then create your index with this preferences. You only need
    an INSO filter if you want to index pdf,word,...
    create index test.alldocs_ctx on test.alldocs(data)
         indextype is ctxsys.context
         parameters ('DATASTORE CTXSYS.MyUserDS FILTER
    CTXSYS.INSO_FILTER LEXER BASIC_LEXER');create index test.alldocs_ctx on test.alldocs(data)
         indextype is ctxsys.context
         parameters ('
    DATASTORE CTXSYS.MyUserDS
    lexer MY_LEXER
    filter MY_FILTER
    section group MY_SECTION');
    Then see in the token table what tokens are in the index:
    select token_text from dr$alldocs_ctx$i;
    If you got also an ORA-3113 see in alert.log if there is a trace
    referenced with this error and have a look in this file to find a
    better error message.
    Good luck.
    Thomas

  • WITH clause, ORDER BY and SDO_GEOMETRY bug?

    I am having a problem using SDO_GEOMETRY within a WITH clause. Specifically with ORDER BY. I will show a shortened version of the SQL here. Am I doing something wrong or is this a bug?
    This works:
                         SELECT
            loc.location_id,
                        SDO_GEOM.SDO_DISTANCE(cent.lat_long,
                        MDSYS.SDO_GEOMETRY
                        2001, -- SDO_GTYPE attribute: 2 in 2001 specifies dimensionality is 2.
                        '4326',
                        SDO_POINT_TYPE(-78.6386145, 35.772096, NULL),
                        NULL,
                        NULL
                       0.01, -- tolerance
                        'unit=mile') result_center_distance
                         FROM location loc
                         JOIN centroid cent ON loc.centroid_id = cent.centroid_id
             ORDER BY result_center_distanceAfter putting the select statement in a with clause, this does not work, giving a ORA-00904 "SDO_GEOMETRY" Invalid Identifier:
    WITH location_distance AS
                         SELECT
            loc.location_id,
                        SDO_GEOM.SDO_DISTANCE(cent.lat_long,
                        MDSYS.SDO_GEOMETRY
                        2001, -- SDO_GTYPE attribute: 2 in 2001 specifies dimensionality is 2.
                        '4326',
                        SDO_POINT_TYPE(-78.6386145, 35.772096, NULL),
                        NULL,
                        NULL
                       0.01, -- tolerance
                        'unit=mile') result_center_distance                    
                         FROM location loc
                         JOIN centroid cent ON loc.centroid_id = cent.centroid_id
             ORDER BY result_center_distance
      ) SELECT * from location_distanceIf I duplicate the distance function in the ORDER BY, it works:
    WITH location_distance AS
                         SELECT
            loc.location_id,
                        SDO_GEOM.SDO_DISTANCE(cent.lat_long,
                        MDSYS.SDO_GEOMETRY
                        2001, -- SDO_GTYPE attribute: 2 in 2001 specifies dimensionality is 2.
                        '4326',
                        SDO_POINT_TYPE(-78.6386145, 35.772096, NULL),
                        NULL,
                        NULL
                       0.01, -- tolerance
                        'unit=mile') result_center_distance                    
                         FROM location loc
                         JOIN centroid cent ON loc.centroid_id = cent.centroid_id
             ORDER BY                     SDO_GEOM.SDO_DISTANCE(cent.lat_long,
                MDSYS.SDO_GEOMETRY
                2001, -- SDO_GTYPE attribute: 2 in 2001 specifies dimensionality is 2.
                '4326',
                SDO_POINT_TYPE(-78.6386145, 35.772096, NULL),
                NULL,
                NULL
                  0.01, -- tolerance
                'unit=mile')
      ) SELECT * from location_distance

    Version: Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - Production
    Here's a test script:
      CREATE TABLE "MY_LOCATION"
       (     "LOCATION_ID" NUMBER NOT NULL ENABLE,
          "CENTROID_ID" NUMBER(38,0),
          CONSTRAINT "MY_LOCATION_PK" PRIMARY KEY ("LOCATION_ID")
      CREATE TABLE "MY_CENTROID"
       (     "CENTROID_ID" NUMBER(38,0) NOT NULL ENABLE,
         "LAT_LONG" "MDSYS"."SDO_GEOMETRY"  NOT NULL ENABLE,
          PRIMARY KEY ("CENTROID_ID"));
    INSERT INTO user_sdo_geom_metadata VALUES (
        'MY_CENTROID',
        'LAT_LONG',
        MDSYS.SDO_DIM_ARRAY(
    MDSYS.SDO_DIM_ELEMENT('X', -180, 180, 0.05),
    MDSYS.SDO_DIM_ELEMENT('Y', -90, 90, 0.05)),
        '4326');
    CREATE INDEX my_centroid_spatial_idx ON my_centroid(lat_long)
    INDEXTYPE IS mdsys.spatial_index;
    WITH location_distance AS
                         SELECT
            loc.location_id,
                        SDO_GEOM.SDO_DISTANCE(cent.lat_long,
                        MDSYS.SDO_GEOMETRY
                        2001, -- SDO_GTYPE attribute: 2 in 2001 specifies dimensionality is 2.
                        '4326',
                        SDO_POINT_TYPE(-78.6386145, 35.772096, NULL),
                        NULL,
                        NULL
                       0.01, -- tolerance
                        'unit=mile') result_center_distance                    
                         FROM my_location loc
                         JOIN my_centroid cent ON loc.centroid_id = cent.centroid_id
             ORDER BY result_center_distance
      ) SELECT * from location_distance

  • Help with WITH clause

    I have a complicated summary report that I am trying to put together. Using the WITH clause is substantially reducing the query time. Here's what I have (it works):
    with ldsntons as
    (select c.DATE_INDEX, j.FACTORY_ID, s.SHORT_NM||' ('||j.STATION_ID||') '||j.PILE_CODE_ALT_FLAG as STN_NM,
           COUNT(j.LOAD_JOB_ID) as LDS,
        CASE SUM(w.SPOT_WEIGHT)
           WHEN 0 THEN SUM(j.MAN_SPOT_WT)
           ELSE SUM(w.SPOT_WEIGHT)
         END TONS
      from TC c, TC_LOAD_JOBS j, SPOT_WEIGHTS w, STATIONS s
    where c.TC_ID = j.TC_ID
       and FN_STN_KEY(j.FACTORY_ID, j.STATION_ID) = s.KEY_ID
       and j.LOAD_RATE_ID = w.LOAD_RATE_ID
       and c.DATE_INDEX = w.DATE_INDEX
       and c.DATE_INDEX BETWEEN to_date(:P2053_DT,'MM/DD/YYYY') AND to_date(:P2053_DT,'MM/DD/YYYY') +15  -- Optional filter
    group by c.DATE_INDEX, j.FACTORY_ID, j.STATION_ID, s.SHORT_NM, j.PILE_CODE_ALT_FLAG)
    SELECT STN_NM as STN,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')    THEN LDS  END), 0) D01LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')    THEN TONS END), 0) D01TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+1  THEN LDS  END), 0) D02LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+1  THEN TONS END), 0) D02TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+2  THEN LDS  END), 0) D03LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+2  THEN TONS END), 0) D03TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+3  THEN LDS  END), 0) D04LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+3  THEN TONS END), 0) D04TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+4  THEN LDS  END), 0) D05LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+4  THEN TONS END), 0) D05TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+5  THEN LDS  END), 0) D06LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+5  THEN TONS END), 0) D06TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+6  THEN LDS  END), 0) D07LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+6  THEN TONS END), 0) D07TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+7  THEN LDS  END), 0) D08LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+7  THEN TONS END), 0) D08TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+8  THEN LDS  END), 0) D09LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+8  THEN TONS END), 0) D09TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+9  THEN LDS  END), 0) D10LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+9  THEN TONS END), 0) D10TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+10 THEN LDS  END), 0) D11LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+10 THEN TONS END), 0) D11TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+11 THEN LDS  END), 0) D12LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+11 THEN TONS END), 0) D12TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+12 THEN LDS  END), 0) D13LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+12 THEN TONS END), 0) D13TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+13 THEN LDS  END), 0) D14LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+13 THEN TONS END), 0) D14TNS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+14 THEN LDS  END), 0) D15LDS,
    NVL(SUM(CASE WHEN DATE_INDEX = to_date(:P2053_DT,'MM/DD/YYYY')+14 THEN TONS END), 0) D15TNS,
    SUM(LDS),
    SUM(TONS)
      FROM ldsntons
    WHERE FACTORY_ID = :P2053_ORG_ID
    GROUP BY STN_NMBasically the report lists a location with daily activity in columns for 15 days from that location. What I need to add are subtotals at the end of the line. I tried duplicating my WITH clause to pull the subtotals, but I kept getting an incorrect join that was listing all the amounts regardless of the date, which isn't correct.
    The other kicker is that I can get it to work fine if I restrict the initial WITH statement to include a WHERE clause (-- Optional filter) that filters it down to only data within the range, but the requestor wants to see all the locations regardless of whether they haul during the time period or not.
    Your help is greatly appreciated.

    This report is a cross-tab of data compiled from 4-5 other tables. I understand what you are asking, but I can't possibly post that much information. This is an aggregation of hundreds of employee timecards per day having dozens of loads; even to get a representative set you would need several hundred lines. The report lists the loads and tons for each of the 15 days on the report by virtue of the case statement. What I need is a sub-total (by line) of those 15 days into one field at the end of the line. It's not that hard to do in a spreadsheet, but we're trying to skip the need to export to csv and do manual manipulations after the fact.
    This is what I want the report to look like:
    STATION     DAY1LOADS   DAY1TONS   DAY2LOADS   DAY2TONS ...  DAY15LOADS   DAY15TONS   SUBTTLLOADS   SUBTTLTONS
    Ada            10           300          12        350             5         150       40        1200SUBTTLTONS = DAY1TONS + DAY2TONS + DAY3TONS, etc.
    I was hoping there was a simpler way of doing it than adding the individual columns into an aggregate. I can develop the query I need, I just need help with joining it in to the base query. This query gets me the subtotals:
    select s.SHORT_NM||' ('||j.STATION_ID||') '||j.PILE_CODE_ALT_FLAG as STN_NM,
           COUNT(j.LOAD_JOB_ID) as LDS,
        CASE SUM(w.SPOT_WEIGHT)
           WHEN 0 THEN SUM(j.MAN_SPOT_WT)
           ELSE SUM(w.SPOT_WEIGHT)
         END TONS
      from TC c, TC_LOAD_JOBS j, SPOT_WEIGHTS w, STATIONS s
    where c.TC_ID = j.TC_ID
       and FN_STN_KEY(j.FACTORY_ID, j.STATION_ID) = s.KEY_ID
       and j.LOAD_RATE_ID = w.LOAD_RATE_ID
       and c.DATE_INDEX = w.DATE_INDEX
       and j.FACTORY_ID = :P2053_ORG_ID
       and c.DATE_INDEX BETWEEN to_date(:P2053_DT,'MM/DD/YYYY') AND to_date(:P2053_DT,'MM/DD/YYYY') +15
    group by s.SHORT_NM||' ('||j.STATION_ID||') '||j.PILE_CODE_ALT_FLAG

  • Difference between global temporary table and with clause

    what is the difference between global temporary table and with claue .(with clause is used as table in select query)

    what is the difference between global temporary table and with claue .(with clause is used as table in select query)Its big difference between the two.
    Global temporary table exists for a session or a transaction while, with clause lives only for a query.
    GTT is a named permanent storage table whose data flushes away on session exit or at end of a transaction while WITH clause just provides names to a reference data within a query (which is as good as having union subquery in FROM clause)
    eg
    SQL> with c as
      2  (
      3  select 1 id1, 2 id2 from dual union all
      4  select 2,4 from dual union all
      5  select 3,5 from dual)
      6  select * from c
      7  /
           ID1        ID2
             1          2
             2          4
             3          5
    SQL> ed
    Wrote file afiedt.buf
      1  select *
      2  from
      3  (
      4  select 1 id1, 2 id2 from dual union all
      5  select 2,4 from dual union all
      6* select 3,5 from dual)
      7  /
           ID1        ID2
             1          2
             2          4
             3          5But GTT serves its purpose very well in case of session specific transaction and the scnearion with multiple users working on same data.

  • Issue in use of "WITH CLAUSE"

    My DB version is 10.2.0
    One of my query takes long time for execution and here is the Old Query,
    SELECT HD.DATUM DATUM, HA2.GELDEINGAENGE_INSG-NVL(HA3.VERWERTUNGSERLOESE,0)
      GELDEINGANG, HA3.VERWERTUNGSERLOESE
    FROM
    ( SELECT DISTINCT(TO_CHAR(ERFASSDATUM,'YYYY/MM')) DATUM
      FROM TRANS_HIST H1 ,
        (SELECT BUCHUNGSGRUPPE, LFDNR, SICHERHEITBEZUG
        FROM BUCHUNGSSCHL
        WHERE STORNOMM=0) B1
      WHERE H1.ERFASSDATUM >=TO_DATE('01.10'||TO_CHAR(ADD_MONTHS(SYSDATE,-9),'YYYY')||' 00.00.00','DD.MM.YYYY HH24:MI:SS')
      AND H1.BUCHUNGSGRUPPE = B1.BUCHUNGSGRUPPE AND H1.LFDNR = B1.LFDNR
      AND (H1.BUCHUNGSGRUPPE = '8888' OR ( H1.BUCHUNGSGRUPPE > 5999 AND H1.BUCHUNGSGRUPPE < 7100 AND B1.SICHERHEITBEZUG = 1)) ) HD,
      (SELECT TO_CHAR(ERFASSDATUM,'YYYY/MM') DATUM, SUM(BETRAG) GELDEINGAENGE_INSG
      FROM TRANS_HIST H2,
      (SELECT F.GLAEUBIGERNR,F.FORDNR,F.FORDERGNR,A.MAHN_NUM
      FROM FRD_ACCT F,
      (SELECT * FROM ANS_PRCH WHERE RANGMM=1) A
      WHERE F.GLAEUBIGERNR=A.GLAEUBIGERNR (+) AND F.FORDNR=A.FORDNR(+)
      AND F.FORDERGNR=A.FORDERGNR(+) AND NVL(F.INDIVIDUALFLAG,0)=0 ) F1
      WHERE ( (F1.GLAEUBIGERNR= H2.GLAEUBIGERNR AND F1.FORDNR=H2.FORDNR AND F1.FORDERGNR=H2.FORDERGNR) OR
      F1.MAHN_NUM = H2.MAHN_NUM) AND H2.BUCHUNGSGRUPPE = '8888' AND
      H2.ERFASSDATUM >= TO_DATE('01.10'||TO_CHAR(ADD_MONTHS(SYSDATE,-9),'YYYY')||' 00.00.00','DD.MM.YYYY HH24:MI:SS')
      GROUP BY TO_CHAR(ERFASSDATUM,'YYYY/MM') ) HA2,
      (SELECT TO_CHAR(ERFASSDATUM,'YYYY/MM') DATUM, SUM(BETRAG) VERWERTUNGSERLOESE
       FROM TRANS_HIST H3, (SELECT BUCHUNGSGRUPPE, LFDNR,
      SICHERHEITBEZUG, NACHMIETVERTRAGE
      FROM BUCHUNGSSCHL
      WHERE STORNOMM=0) B3,
      (SELECT F.GLAEUBIGERNR,F.FORDNR,F.FORDERGNR,A.MAHN_NUM
      FROM FRD_ACCT F,
      (SELECT * FROM ANS_PRCH WHERE RANGMM=1) A
      WHERE F.GLAEUBIGERNR= A.GLAEUBIGERNR (+) AND F.FORDNR=A.FORDNR(+)
      AND F.FORDERGNR=A.FORDERGNR(+) AND NVL(F.INDIVIDUALFLAG,0)=0 ) F2
      WHERE ( (F2.GLAEUBIGERNR=H3.GLAEUBIGERNR AND F2.FORDNR=H3.FORDNR AND F2.FORDERGNR=H3.FORDERGNR)
      OR F2.MAHN_NUM = H3.MAHN_NUM)
      AND H3.ERFASSDATUM >=TO_DATE('01.10'||TO_CHAR(ADD_MONTHS(SYSDATE,-9),'YYYY')||' 00.00.00','DD.MM.YYYY HH24:MI:SS')
      AND H3.BUCHUNGSGRUPPE = B3.BUCHUNGSGRUPPE AND
      H3.LFDNR = B3.LFDNR AND H3.BUCHUNGSGRUPPE > 5999
      AND H3.BUCHUNGSGRUPPE < 7100 AND (B3.SICHERHEITBEZUG = 1 OR B3.NACHMIETVERTRAGE =1)
      GROUP BY TO_CHAR(ERFASSDATUM,'YYYY/MM') ) HA3
      WHERE HD.DATUM=HA2.DATUM (+)
      AND HD.DATUM=HA3.DATUM (+)
      ORDER BY DATUM ASC
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        1      0.22       0.22          0          0          0           0
    Execute      1      0.00       0.00          0          0          0           0
    Fetch        1    469.61    1448.30    2874498    3017355          1           9
    total        3    469.83    1448.53    2874498    3017355          1           9
    Misses in library cache during parse: 1
    Optimizer mode: ALL_ROWS
    Parsing user id: 62     (recursive depth: 1)
    Rows     Row Source Operation
          9  SORT ORDER BY (cr=3017355 pr=2874498 pw=0 time=1448309418 us)
          9   HASH JOIN RIGHT OUTER (cr=3017355 pr=2874498 pw=0 time=1448309191 us)
          9    VIEW  (cr=1228085 pr=1175604 pw=0 time=906871801 us)
          9     HASH GROUP BY (cr=1228085 pr=1175604 pw=0 time=906871785 us)
       1559      CONCATENATION  (cr=1228085 pr=1175604 pw=0 time=564453620 us)
        233       HASH JOIN  (cr=614043 pr=589377 pw=0 time=562088377 us)
         94        TABLE ACCESS FULL BUCHUNGSSCHL (cr=29 pr=0 pw=0 time=505 us)
    254136        HASH JOIN  (cr=614014 pr=589377 pw=0 time=509476999 us)
    497464         TABLE ACCESS FULL TRANS_HIST (cr=586339 pr=562603 pw=0 time=65783878 us)
    737515         HASH JOIN RIGHT OUTER (cr=27675 pr=26774 pw=0 time=18577731 us)
    372656          TABLE ACCESS FULL ANS_PRCH (cr=6346 pr=5910 pw=0 time=408778 us)
    737515          TABLE ACCESS FULL FRD_ACCT (cr=21329 pr=20864 pw=0 time=2254657 us)
       1326       HASH JOIN  (cr=614042 pr=586227 pw=0 time=520726941 us)
         94        TABLE ACCESS FULL BUCHUNGSSCHL (cr=29 pr=0 pw=0 time=641 us)
    221360        FILTER  (cr=614013 pr=586227 pw=0 time=372791872 us)
    221360         HASH JOIN OUTER (cr=614013 pr=586227 pw=0 time=372570499 us)
    221360          HASH JOIN  (cr=607668 pr=580286 pw=0 time=368077766 us)
    243053           TABLE ACCESS FULL TRANS_HIST (cr=586339 pr=563978 pw=0 time=1425434011 us)
    737515           TABLE ACCESS FULL FRD_ACCT (cr=21329 pr=16308 pw=0 time=8859226 us)
    372656          TABLE ACCESS FULL ANS_PRCH (cr=6345 pr=5941 pw=0 time=1872464 us)
          9    HASH JOIN OUTER (cr=1789270 pr=1698894 pw=0 time=541436637 us)
          9     VIEW  (cr=586667 pr=562439 pw=0 time=213337882 us)
          9      HASH UNIQUE (cr=586667 pr=562439 pw=0 time=213337873 us)
    748717       HASH JOIN  (cr=586667 pr=562439 pw=0 time=104432018 us)
        830        TABLE ACCESS FULL BUCHUNGSSCHL (cr=29 pr=0 pw=0 time=1042 us)
    1241936        TABLE ACCESS FULL TRANS_HIST (cr=586638 pr=562439 pw=0 time=339666777 us)
          9     VIEW  (cr=1202603 pr=1136455 pw=0 time=328097826 us)
          9      HASH GROUP BY (cr=1202603 pr=1136455 pw=0 time=328097809 us)
    695373       CONCATENATION  (cr=1202603 pr=1136455 pw=0 time=324453471 us)
          0        HASH JOIN  (cr=587003 pr=557994 pw=0 time=167168982 us)
    744472         TABLE ACCESS FULL TRANS_HIST (cr=587003 pr=557994 pw=0 time=30622271 us)
          0         HASH JOIN RIGHT OUTER (cr=0 pr=0 pw=0 time=0 us)
          0          TABLE ACCESS FULL ANS_PRCH (cr=0 pr=0 pw=0 time=0 us)
          0          TABLE ACCESS FULL FRD_ACCT (cr=0 pr=0 pw=0 time=0 us)
    695373        FILTER  (cr=615600 pr=578461 pw=0 time=157284464 us)
    695373         HASH JOIN OUTER (cr=615600 pr=578461 pw=0 time=156589072 us)
    695373          HASH JOIN  (cr=609255 pr=572518 pw=0 time=150571393 us)
    744472           TABLE ACCESS FULL TRANS_HIST (cr=587926 pr=556115 pw=0 time=31820718 us)
    737515           TABLE ACCESS FULL FRD_ACCT (cr=21329 pr=16403 pw=0 time=3696334 us)
    372656          TABLE ACCESS FULL ANS_PRCH (cr=6345 pr=5943 pw=0 time=391928 us)I tried fine tuning the query using "With Clause" but landed up with oracle error, which prevents me from using with clause inside a paranthesis.
    SELECT HD.DATUM DATUM, HA2.GELDEINGAENGE_INSG-NVL(HA3.VERWERTUNGSERLOESE,0)
      GELDEINGANG, HA3.VERWERTUNGSERLOESE
    FROM
    ( WITH HIST_VIEW AS (SELECT GLAEUBIGERNR,FORDNR,FORDERGNR,MAHN_NUM,BUCHUNGSGRUPPE,LFDNR,STORNOMM,ERFASSDATUM,BETRAG
                         FROM TRANS_HIST H
                         WHERE ERFASSDATUM >=TO_DATE('01.10'||TO_CHAR(ADD_MONTHS(SYSDATE,-9),'YYYY')||' 00.00.00','DD.MM.YYYY HH24:MI:SS')
                         AND  (H.BUCHUNGSGRUPPE = '8888' OR ( H.BUCHUNGSGRUPPE > 5999 AND H.BUCHUNGSGRUPPE < 7100))),
           FORD_VIEW AS (SELECT F.GLAEUBIGERNR,F.FORDNR,F.FORDERGNR,A.MAHN_NUM
                         FROM FRD_ACCT F,ANS_PRCH A
                         WHERE F.GLAEUBIGERNR=A.GLAEUBIGERNR(+) AND F.FORDNR=A.FORDNR(+)
                         AND F.FORDERGNR=A.FORDERGNR(+) AND NVL(F.INDIVIDUALFLAG,0)=0 AND  A.RANGMM=1)
    (SELECT DISTINCT(TO_CHAR(ERFASSDATUM,'YYYY/MM')) DATUM
      FROM HIST_VIEW H1 ,BUCHUNGSSCHL B1
      WHERE B1.STORNOMM=0  AND H1.BUCHUNGSGRUPPE = B1.BUCHUNGSGRUPPE AND H1.LFDNR = B1.LFDNR
      AND (H1.BUCHUNGSGRUPPE = '8888' OR (H1.BUCHUNGSGRUPPE > 5999 AND H1.BUCHUNGSGRUPPE < 7100 AND B1.SICHERHEITBEZUG = 1))) HD,
    (SELECT TO_CHAR(ERFASSDATUM,'YYYY/MM') DATUM, SUM(BETRAG) GELDEINGAENGE_INSG
      FROM HIST_VIEW H2,FORD_VIEW F1
      WHERE ((F1.GLAEUBIGERNR= H2.GLAEUBIGERNR AND F1.FORDNR=H2.FORDNR AND F1.FORDERGNR=H2.FORDERGNR) OR
      F1.MAHN_NUM = H2.MAHN_NUM) AND H2.BUCHUNGSGRUPPE = '8888'
      GROUP BY TO_CHAR(ERFASSDATUM,'YYYY/MM') ) HA2,
    (SELECT TO_CHAR(ERFASSDATUM,'YYYY/MM') DATUM, SUM(BETRAG) VERWERTUNGSERLOESE
      FROM HIST_VIEW H3, BUCHUNGSSCHL B3,FORD_VIEW F2
      WHERE ((F2.GLAEUBIGERNR=H3.GLAEUBIGERNR AND F2.FORDNR=H3.FORDNR
      AND F2.FORDERGNR=H3.FORDERGNR) OR F2.MAHN_NUM = H3.MAHN_NUM) AND B3.STORNOMM=0
      AND H3.BUCHUNGSGRUPPE = B3.BUCHUNGSGRUPPE AND
      H3.LFDNR = B3.LFDNR AND H3.BUCHUNGSGRUPPE > 5999
      AND H3.BUCHUNGSGRUPPE < 7100 AND (B3.SICHERHEITBEZUG = 1 OR B3.NACHMIETVERTRAGE =1)
      GROUP BY TO_CHAR(ERFASSDATUM,'YYYY/MM')) HA3
      WHERE HD.DATUM=HA2.DATUM (+)
      AND HD.DATUM=HA3.DATUM (+)
      ORDER BY DATUM ASC )
    ORA-00907: missing right parenthesis

    If you format your code it makes it far easier to spot mistakes...
    WITH HIST_VIEW AS (SELECT GLAEUBIGERNR,FORDNR,FORDERGNR,MAHN_NUM,BUCHUNGSGRUPPE,LFDNR,STORNOMM,ERFASSDATUM,BETRAG
                       FROM   TRANS_HIST H
                       WHERE  ERFASSDATUM >=TO_DATE('01.10'||TO_CHAR(ADD_MONTHS(SYSDATE,-9),'YYYY')||' 00.00.00','DD.MM.YYYY HH24:MI:SS')
                       AND   (  H.BUCHUNGSGRUPPE = '8888'
                            OR (H.BUCHUNGSGRUPPE > 5999 AND H.BUCHUNGSGRUPPE < 7100)
         FORD_VIEW AS (SELECT F.GLAEUBIGERNR,F.FORDNR,F.FORDERGNR,A.MAHN_NUM
                       FROM   FRD_ACCT F,ANS_PRCH A
                       WHERE  F.GLAEUBIGERNR=A.GLAEUBIGERNR(+)
                       AND    F.FORDNR=A.FORDNR(+)
                       AND    F.FORDERGNR=A.FORDERGNR(+)
                       AND    NVL(F.INDIVIDUALFLAG,0)=0
                       AND    A.RANGMM=1
    SELECT HD.DATUM DATUM
          ,HA2.GELDEINGAENGE_INSG-NVL(HA3.VERWERTUNGSERLOESE,0) GELDEINGANG
          ,HA3.VERWERTUNGSERLOESE
    FROM  (SELECT DISTINCT(TO_CHAR(ERFASSDATUM,'YYYY/MM')) DATUM
           FROM   HIST_VIEW H1
                 ,BUCHUNGSSCHL B1
           WHERE  B1.STORNOMM=0
           AND    H1.BUCHUNGSGRUPPE = B1.BUCHUNGSGRUPPE
           AND    H1.LFDNR = B1.LFDNR
           AND   (  H1.BUCHUNGSGRUPPE = '8888'
                OR (H1.BUCHUNGSGRUPPE > 5999 AND H1.BUCHUNGSGRUPPE < 7100 AND B1.SICHERHEITBEZUG = 1)
          ) HD,
          (SELECT TO_CHAR(ERFASSDATUM,'YYYY/MM') DATUM
                 ,SUM(BETRAG) GELDEINGAENGE_INSG
           FROM   HIST_VIEW H2
                 ,FORD_VIEW F1
           WHERE (
                   (    F1.GLAEUBIGERNR= H2.GLAEUBIGERNR
                    AND F1.FORDNR=H2.FORDNR
                    AND F1.FORDERGNR=H2.FORDERGNR
                 OR
                    F1.MAHN_NUM = H2.MAHN_NUM
           AND   H2.BUCHUNGSGRUPPE = '8888'
           GROUP BY TO_CHAR(ERFASSDATUM,'YYYY/MM')
          ) HA2,
          (SELECT TO_CHAR(ERFASSDATUM,'YYYY/MM') DATUM
                 ,SUM(BETRAG) VERWERTUNGSERLOESE
           FROM   HIST_VIEW H3
                 ,BUCHUNGSSCHL B3
                 ,FORD_VIEW F2
           WHERE (
                   (    F2.GLAEUBIGERNR=H3.GLAEUBIGERNR
                    AND F2.FORDNR=H3.FORDNR
                    AND F2.FORDERGNR=H3.FORDERGNR
                 OR
                   F2.MAHN_NUM = H3.MAHN_NUM
           AND B3.STORNOMM=0
           AND H3.BUCHUNGSGRUPPE = B3.BUCHUNGSGRUPPE
           AND H3.LFDNR = B3.LFDNR
           AND H3.BUCHUNGSGRUPPE > 5999
           AND H3.BUCHUNGSGRUPPE < 7100
           AND (B3.SICHERHEITBEZUG = 1 OR B3.NACHMIETVERTRAGE =1)
           GROUP BY TO_CHAR(ERFASSDATUM,'YYYY/MM')
          ) HA3
    WHERE HD.DATUM=HA2.DATUM (+)
    AND   HD.DATUM=HA3.DATUM (+)
    ORDER BY DATUM ASC
    ) <--- What's this doing on the end?Remove that last bracket and you should be ok.
    I took the liberty of putting the subquery factoring at the beginning, so see if that works.

  • OPEN CURSOR using a WITH clause in the select query

    Hi,
    I am using Oracle 9i. I have a requirement where I have a REFCURSOR as an OUT parameter for my procedure. I have declared the TYPE and created the procedure.
    In the procedure, I am using OPEN <cursor_name> FOR <query>;
    Ideally this works in most of the cases that I have tried earlier. However, in the current case I am using a WITH clause in my query to get the results.
    I need help in understanding if the above mentioned syntax would not allow me to use the WITH clause in the query.

    What error do you get , seems to work ok for me on 10g
    SQL> begin
      2  open :cv for 'with x as (select * from emp)  select * from x';
      3  end;
      4  /
    PL/SQL procedure successfully completed.
    SQL> print :cv
         EMPNO
    ENAME
    JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7521
    WARD
    SALESMAN        7698 22-FEB-81       1250        500         30
          7566
    JONES
    MANAGER         7839 02-APR-81       2975                    20
         EMPNO

  • Need help with INSERT and WITH clause

    I wrote sql statement which correctly work, but how i use this statment with INSERT query? NEED HELP. when i wrote insert i see error "ORA 32034: unsupported use of with clause"
    with t1 as(
    select a.budat,a.monat as period,b.vtweg,
    c.gjahr,c.buzei,c.shkzg,c.hkont, c.prctr,
    c.wrbtr,
    c.matnr,
    c.menge,
    a.monat,
    c.zuonr
    from ldw_v1.BKPF a,ldw_v1.vbrk b, ldw_v1.bseg c
    where a.AWTYP='VBRK' and a.BLART='RV' and a.BUKRS='8431' and a.awkey=b.vbeln
    and a.bukrs=c.bukrs and a.belnr=c.belnr and a.gjahr=c.gjahr and c.koart='D'
    and c.ktosl is null and c.gsber='4466' and a.gjahr>='2011' and b.vtweg='01'
    ,t2 as(
    select a.BUKRS,a.BELNR, a.GJAHR,t1.vtweg,t1.budat,t1.monat from t1, ldw_v1.bkpf a
    where t1.zuonr=a.xblnr and a.blart='WL' and bukrs='8431'
    ,tcogs as (
    select t2.budat,t2.monat,t2.vtweg, bseg.gjahr,bseg.hkont,bseg.prctr,
    sum(bseg.wrbtr) as COGS,bseg.matnr,bseg.kunnr,sum(bseg.menge) as QUANTITY
    from t2, ldw_v1.bseg
    where t2.bukrs=bseg.bukrs and t2.belnr=bseg.BELNR and t2.gjahr=bseg.gjahr and BSEG.KOART='S'
    group by t2.budat,t2.monat,t2.vtweg, bseg.gjahr,bseg.hkont,bseg.prctr,
    bseg.matnr,bseg.kunnr
    ,t3 as
    select a.budat,a.monat,b.vtweg,
    c.gjahr,c.buzei,c.shkzg,c.hkont, c.prctr,
    case when c.shkzg='S' then c.wrbtr*(-1)
    else c.wrbtr end as NTS,
    c.matnr,c.kunnr,
    c.menge*(-1) as Quantity
    from ldw_v1.BKPF a,ldw_v1.vbrk b, ldw_v1.bseg c
    where a.AWTYP='VBRK' and a.BLART='RV' and a.BUKRS='8431' and a.awkey=b.vbeln
    and a.bukrs=c.bukrs and a.belnr=c.belnr and a.gjahr=c.gjahr and c.koart='S'
    and c.ktosl is null and c.gsber='4466' and a.gjahr>='2011' and b.vtweg='01'
    ,trevenue as (
    select t3.budat,t3.monat,t3.vtweg, t3.gjahr,t3.hkont,t3.prctr,
    sum(t3.NTS) as NTS,t3.matnr,t3.kunnr,sum(t3.QUANTITY) as QUANTITY
    from t3
    group by t3.budat,t3.monat,t3.vtweg, t3.gjahr,t3.hkont,t3.prctr,t3.matnr,t3.kunnr
    select NVL(tr.budat,tc.budat) as budat,
    NVL(tr.monat,tc.monat) as monat,
    NVL(tr.vtweg,tc.vtweg) as vtweg,
    NVL(tr.gjahr, tc.gjahr) as gjahr,
    tr.hkont as NTS_hkont,
    tc.hkont as COGS_hkont,
    NVL(tr.prctr,tc.prctr) as prctr,
    NVL(tr.MATNR, tc.MATNR) as matnr,
    NVL(tr.kunnr, tc.kunnr) as kunnr,
    NVL(tr.Quantity, tc.Quantity) as Quantity,
    tr.NTS as NTS,
    tc.COGS as COGS
    from trevenue TR full outer join tcogs TC
    on TR.BUDAT=TC.BUDAT and TR.MONAT=TC.MONAT and TR.GJAHR=TC.GJAHR
    and TR.MATNR=TC.MATNR and TR.KUNNR=TC.KUNNR and TR.QUANTITY=TC.QUANTITY
    and TR.VTWEG=TC.VTWEG and TR.PRCTR=TC.PRCTR
    Edited by: user13566113 on 25.03.2011 5:26

    Without seeing what you tried it is hard to say what you did wrong, but this is how it would work
    SQL> create table t ( n number );
    Table created.
    SQL> insert into t
      2  with test_data as
      3    (select 1 x from dual union all
      4     select 2 x from dual union all
      5     select 3 x from dual union all
      6     select 4 x from dual)
      7  select x from test_data;
    4 rows created.
    SQL>

  • Error in writing WITH CLAUSE

    i am writing these SQL Lines in my stored procedure i am using with clause i am getting error when i perform
    inner join
    With  WardItemsDtl as ( SELECT WardItemDtl_ID,
    WardTransID,
    wdDtl.ItemID,
    SUM(ItemQty) ItemQty,
    ReceivedWardID as WardID
    FROM LL_WardItems_Details wdDtl
    WHERE isposted = 0
    GROUP BY wdDtl.ItemID,WardItemDtl_ID,ReceivedWardID,WardTransID
    ORDER BY WardItemDtl_ID )
    , PartyItemsDtl AS ( SELECT WardItemDtl_ID,
    ItemID,
    SUM(IssueItemQty) IssueItemQty
    FROM LL_PartyItems_Details
    GROUP BY WardItemDtl_ID,ItemID
    ORDER BY WardItemDtl_ID )
    SELECT wdDt.WardTransID,
    wdDt.ItemID,
    itmt.ItemCode,
    itmt.ItemDescription,
    wdDt.ItemQty as TotalItemQty,
    NVL(pDtl.IssueItemQty, 0) as IssueQtyToParty,
    wdDt.WardID,
    wdmt.Ward_Name
    from WardItemsDtl wdDt,PartyItemsDtl pDtl
    inner join LLItemMst itmt
    on itmt.ItemID=wdDt.ItemID -----error in this line
    inner join ward_mst wdmt -- error in this line
    on wdmt.Ward_ID=wdDt.WardID
    error
    Error report:
    SQL Error: ORA-00904: "WDDT"."ITEMID": invalid identifier
    00904. 00000 - "%s: invalid identifier"
    *Cause:   
    *Action:                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    WITH WARDITEMSDTL AS
      (SELECT WARDITEMDTL_ID,
        WARDTRANSID,
        WDDTL.ITEMID,
        SUM(ITEMQTY) ITEMQTY,
        RECEIVEDWARDID AS WARDID
      FROM LL_WARDITEMS_DETAILS WDDTL
      WHERE ISPOSTED = 0
      GROUP BY WDDTL.ITEMID,
        WARDITEMDTL_ID,
        RECEIVEDWARDID,
        WARDTRANSID
      ORDER BY WARDITEMDTL_ID
      PARTYITEMSDTL AS
      (SELECT WARDITEMDTL_ID,
        ITEMID,
        SUM(ISSUEITEMQTY) ISSUEITEMQTY
      FROM LL_PARTYITEMS_DETAILS
      GROUP BY WARDITEMDTL_ID,
        ITEMID
      ORDER BY WARDITEMDTL_ID
    SELECT WDDT.WARDTRANSID,
      WDDT.ITEMID,
      ITMT.ITEMCODE,
      ITMT.ITEMDESCRIPTION,
      WDDT.ITEMQTY              AS TOTALITEMQTY,
      NVL(PDTL.ISSUEITEMQTY, 0) AS ISSUEQTYTOPARTY,
      WDDT.WARDID,
      WDMT.WARD_NAME
    FROM WARDITEMSDTL WDDT,
      PARTYITEMSDTL PDTL,
    LLITEMMST ITMT,
    WARD_MST WDMT     
    WHERE ITMT.ITEMID=WDDT.ITEMID
    AND  WDMT.WARD_ID=WDDT.WARDID ;AND WHERE YOUR JOIN PARTYITEMSDTL PDTL

  • Unable to use the with clause in oracle 9.0.2

    Hi,
    I need to use oracle SQL with clause in oracle 9.0.2 database. Its a 9i feature but i am unable to use it.
    It is giving internal error, when i try to execute it.
    Even for simple query:
    WITH acct_summary as ( select TOT_COLL_AMT from tdc_acct)
    select TOT_COLL_AMT from acct_summary WHERE TOT_COLL_AMT>100;
    Error message while using 8.0.5 sql plus client:
    SP2-0642: SQL*Plus internal error state 2091, context 0:0:0
    Unsafe to proceed
    Please help to find out why i am not able to use the sql with clause in oracle 9.0.2 database.
    Thanks and regards,
    Raajkathir

    Hi Jens Petersen,
    Yes, You are correct. Thank you very much.
    Regards,
    Raja

Maybe you are looking for