With Clause in a function

Hi All,
I'm using oracle 10gr2.
I have a sql query which starts with a "WITH Clause".... Can is use this directly in a function?
I tried copy pasting in the new function after the BEGIN.....but it errors out saying INTO clause expected in select...when I try including INTO clause...it gives different error...
Appreciate your sugessions
Thanks in advance
H

>
pls put an additional select ,as shown below
>
Why???
CREATE OR REPLACE FUNCTION with_test (p_empNo NUMBER)
RETURN VARCHAR2 IS
l_eName VARCHAR2(10);
  BEGIN
    WITH l_empTab AS
     SELECT *
     FROM   emp
    SELECT ename
    INTO   l_eName
    FROM   l_empTab
    WHERE  empno = p_empNo;
    RETURN l_eName;
  END;
SELECT with_test(7369) ename
FROM   dual;    Cheers
Ben

Similar Messages

  • 12c - plsql function in with clause

    Hi all
    I'm mucking around with 12c:
    SQL> select *
      2    from v$version;
    BANNER                                                                               CON_ID
    Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 - 64bit Production              0
    PL/SQL Release 12.1.0.1.0 - Production                                                    0
    CORE    12.1.0.1.0      Production                                                                0
    TNS for Linux: Version 12.1.0.1.0 - Production                                            0
    NLSRTL Version 12.1.0.1.0 - Production                                                    0
    5 rows selected.
    specifically I'm trying to use the new functionality of putting a pl/sql function in the WITH clause of an SQL statement:
    docco here:
    http://docs.oracle.com/cd/E16655_01/server.121/e17209/statements_10002.htm#BABJFIDC
    the example they give is:
    WITH
    FUNCTION get_domain(url VARCHAR2) RETURN VARCHAR2 IS
      pos BINARY_INTEGER;
      len BINARY_INTEGER;
    BEGIN
      pos := INSTR(url, 'www.');
      len := INSTR(SUBSTR(url, pos + 4), '.') - 1;
      RETURN SUBSTR(url, pos + 4, len);
    END;
    SELECT DISTINCT get_domain(catalog_url)
      FROM product_information;
    and so I produced my own hello world version:
    with function add_number(num1 number, num2 number) return number is
    begin
       return num1 + num2;
    end;
    select add_number(1,2) from dual;
    but this just doesn't compile in SQL developer or SQLPlus.   do I need to get an updated version or something perhaps?
    output is:
    SQL> with function add_number(num1 number, num2 number) return number is
      2  begin
      3     return num1 + num2;
    with function add_number(num1 number, num2 number) return number is
    ERROR at line 1:
    ORA-06553: PLS-103: Encountered the symbol "end-of-file" when expecting one of the following:
    . ( * @ % & = - + ; < / > at in is mod remainder not rem
    <an exponent (**)> <> or != or ~= >= <= <> and or like like2
    like4 likec between || member submultiset
    SQL> end;
    SP2-0042: unknown command "end" - rest of line ignored.
    SQL> select add_number(1,2) from dual;
    select add_number from dual
    ERROR at line 1:
    ORA-00904: "ADD_NUMBER": invalid identifier
    SQL> /
    select add_number from dual
    ERROR at line 1:
    ORA-00904: "ADD_NUMBER": invalid identifier

    Hi,
    does that mean that you still have the problem, even after fixing this? Because I don't:
    SQL*Plus: Release 12.1.0.1.0 Production on Wed Jul 3 11:32:54 2013
    Copyright (c) 1982, 2013, Oracle.  All rights reserved.
    SQL> with function add_number(num1 number, num2 number) return number is
      2  begin
      3    return num1+num2;
      4  end;
      5  select add_number(1,2) from dual;
      6  /
    SP2-0640: Not connected
    SQL> connect / as sysdba
    Connected to an idle instance.
    SQL> startup
    ORACLE instance started.
    Total System Global Area  263090176 bytes
    Fixed Size                  2359904 bytes
    Variable Size             205524384 bytes
    Database Buffers           50331648 bytes
    Redo Buffers                4874240 bytes
    Database mounted.
    Database opened.
    SQL> with function add_number( num1 number, num2 number) return number is
      2  begin
      3    return num1+num2;
      4  end;
      5  select add_number(1,2) from dual;
      6  /
    ADD_NUMBER(1,2)
                  3
    SQL>
    Best regards,
    Nikolay

  • 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

  • Using WITH clause in Pro*Cobol

    Hi!
    I am trying to improve the performance of a query by introducing WITH clause.
    The query is in Pro*Cobol Release 9.2.0.6.0 - Production.
    I got compilation error
    WITH DPTCOST AS (
    ...............1
    PCB-S-00400, Encountered the symbol "DPTCOST" when expecting one of the following:
    END-EXEC
    ....continued
    So I wonder if we could use that clause at all with Pro*Cobol
    Here is the excerp of the code
    EXEC SQL
    DECLARE INPUT_ACTUAL CURSOR FOR
    WITH DPTCOST AS (
    SELECT /*+ rule */
    A.CODE_COMBINATION_ID,
    A.SEGMENT1, A.SEGMENT2, A.SEGMENT3,
    A.SEGMENT6,
    D.COSTING, D.PROCESS,
    D.MTL_CODE, D.FACTOR
    FROM
    GL_CODE_COMBINATION A,
    ALCGL_DEPARTMENT_COSTINGS D
    WHERE
    A.TEMPLATE_ID IS NULL
    AND A.SUMMARY_FLAG <> 'Y'
    AND A.SEGMENT1 = D.PLANT_NUMBER
    AND A.SEGMENT3 <> '6999001'
    AND A.SEGMENT3 <> '6999002'
    AND SUBSTR(A.SEGMENT2,4,3) = D.DEPARTMENT
    AND D.ACTUAL_FLAG = 'A'
    ) ... continued

    Materialized views are basically stored query results. They offer advanced functionality like query rewrite, refresh on commit, and more;
    http://download-west.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_6002.htm
    Unlike a view, they actually store the results of the query - not just the query;
    SQL> create table t (cid number primary key)
    Table created.
    SQL> insert into t select object_id from dba_objects where object_id is not null
    12791 rows created.
    SQL> create materialized view mv
       as select * from t
    Snapshot created.
    SQL> select object_name, object_type from user_objects where object_name ='MV'
    OBJECT_NAME                    OBJECT_TYPE       
    MV                             TABLE             
    MV                             MATERIALIZED VIEW 
    2 rows selected.
    SQL> select segment_name, bytes from user_segments where segment_name in ('T', 'MV')
    SEGMENT_NAME                        BYTES
    T                                  196608
    MV                                 196608
    2 rows selected.Temporary tables are simply tables that are created then dropped. GLOBAL TEMPORARY TABLES have the advantage (or disadvantage) of only existing until commit or the end of the session. They results are visible to the user that inserted the data - but only temporarily;
    http://download-west.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_7002.htm#sthref7483

  • WITH CLAUSE in SPARQL - Running SPARQL query using JENA

    Hi,
    Can anybody help me how to use WITH Clause in SPARQL. Below is my Query. I am using Jena 2.6.3 to Run my Query.
    "PREFIX assc: <http://www./.../> " +
    "WITH " +
         "( " +
                        " select ?associate" +
                        " where {?associate assc:belongsTo <http://www./../Relationship>} " +
                        " AS :associateList" +
         " )" +
                   " select ?client ?associate " +
                   " where { ?client assc:Sees ?associate . ?associate assc:belongsTo <http://www./../Relationship> ." +
                   " :associateList(?associate) }" ;
    Thanks and Regards,
    Manish Hardasmalani

    Hi Zhe,
    Actually i am looking for example say,
    I have a select query where i get id , name and mark this output as a relationshipName
    And then use this relationshipName as a function in second select query.
    Example:
    WITH
    SELECT ... WHERE {...} AS relationName
    SELECT ... FROM <graph> where {... :relationName(...) [FILTER(...)]}
    In the above pseudo code relationName is populated in first select and used in second select. I am searching something similar to this.

  • WITH Clause query doesn't work in Oracle Reports.

    Hi Gurus,
    I'm using a WITH clause query and need to build a report using the same query.
    But when i'm trying to build a report, query is giving error as "WITH clause table or view doesn't exists".
    But the same query perfectly works in sql prompt.
    Oracle Reports doesn't supports WITH clause query?
    Please suggest.
    Thanks,
    Onkar

    I ran into a similar problem before and worked around it by moving the query to a pipelined function in the database as described at WITH clause unexpectedly causes ORA-00942 in Reports Builder
    Hope this helps.

  • ORA-32036 unsupported case for inlining of query name in WITH clause

    I have a query with a WITH clause. In the WITH clause I am using the TABLE command to pull multiple records from a PL/SQL function in the FROM clause:
    WITH select_a AS
    (select x.col1,
    x.col2
    from A,
    TABLE(schema1.function1) x
    where ...)
    select ...
    from ...;
    The query is returning 32036 oracle error. Any thoughts on why I get this error? Is it valid to use the TABLE command with a function in the WITH clause?

    Is it valid to use the TABLE command with a function in the WITH clause?Something else must be going on: Even on my old 9i I can use WITH together with TABLE:
    SQL> select * from v$version where rownum = 1
    BANNER                                                         
    Oracle9i Enterprise Edition Release 9.2.0.8.0 - 64bit Production
    1 row selected.
    SQL> create or replace function f1 (deptno int) return sys.dbms_debug_vc2coll
    as
    begin
    return sys.dbms_debug_vc2coll(deptno);
    end;
    Function created.
    SQL> with t as (
    select dept.* from dept, table (f1(deptno)) where column_value = deptno
    select * from t
        DEPTNO DNAME          LOC         
            10 ACCOUNTING     NEW YORK    
            20 RESEARCH       DALLAS      
            30 SALES          CHICAGO     
            40 OPERATIONS     BOSTON      
    4 rows selected.

  • 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

  • How to use subquery factoring ("with" clause) in OWB?

    Hi,
    Is it possible to use subquery factoring (popularly known as "with" clause) in OWB 10gR2? I have a mapping with a splitter and union-all, which generates a query that has repeated scans of the same table. Subquery Factoring would be very useful here. I think this is a very common situation, so, I hope there's a way to achieve this. (If not in this version, this would be my wishlist item for the next version.)
    Appreciate your help.
    Regards,
    Rahul

    Hi Rahul,
    I'm afraid you have to put this on your wishlist. You may put the query with the "with"-clause into a view (or table function if you need parameters) if performance is too bad. But that is somehow against the idea (and benefits) of owb.
    Another possibility is to use a temporary table and spilt the mappings into two parts: first fill the temp table, then the target table.
    Regards,
    Carsten.

  • Need complex query  with joins and AGGREGATE  functions.

    Hello Everyone ;
    Good Morning to all ;
    I have 3 tables with 2 lakhs record. I need to check query performance.. How CBO rewrites my query in materialized view ?
    I want to make complex join with AGGREGATE FUNCTION.
    my table details
    SQL> select from tab;*
    TNAME TABTYPE CLUSTERID
    DEPT TABLE
    PAYROLL TABLE
    EMP TABLE
    SQL> desc emp
    Name
    EID
    ENAME
    EDOB
    EGENDER
    EQUAL
    EGRADUATION
    EDESIGNATION
    ELEVEL
    EDOMAIN_ID
    EMOB_NO
    SQL> desc dept
    Name
    EID
    DNAME
    DMANAGER
    DCONTACT_NO
    DPROJ_NAME
    SQL> desc payroll
    Name
    EID
    PF_NO
    SAL_ACC_NO
    SALARY
    BONUS
    I want to make  complex query  with joins and AGGREGATE  functions.
    Dept names are : IT , ITES , Accounts , Mgmt , Hr
    GRADUATIONS are : Engineering , Arts , Accounts , business_applications
    I want to select records who are working in IT and ITES and graduation should be "Engineering"
    salary > 20000 and < = 22800 and bonus > 1000 and <= 1999 with count for males and females Separately ;
    Please help me to make a such complex query with joins ..
    Thanks in advance ..
    Edited by: 969352 on May 25, 2013 11:34 AM

    969352 wrote:
    why do you avoid providing requested & NEEDED details?I do NOT understand what do you expect ?
    My Goal is :
    1. When executing my own query i need to check expalin plan.please proceed to do so
    http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_9010.htm#SQLRF01601
    2. IF i enable query rewrite option .. i want to check explain plan ( how optimizer rewrites my query ) ? please proceed to do so
    http://docs.oracle.com/cd/E11882_01/server.112/e16638/ex_plan.htm#PFGRF009
    3. My only aim is QUERY PERFORMANCE with QUERY REWRITE clause in materialized view.It is an admirable goal.
    Best Wishes on your quest for performance improvements.

  • WITH clause unexpectedly causes ORA-00942 in Reports Builder

    I'm posting this in the hope that:
    a) My workaround might help someone if they ever run into the same problem, and/or,
    b) Someone might have a better workaround.
    The problem is that I get unexpected ORA-00942 (table or view does not exist) errors when I try to set the SQL Query Statement property of a Query object in Reports Builder to certain SELECT statements that contain a WITH clause (aka subquery factoring clause).
    For example, the following SELECT statement executes as expected in SQL*Plus...
    SQL> WITH
      2      SUB_QUERY AS
      3      (
      4          SELECT
      5              1 AS X
      6          FROM
      7              DUAL
      8      )
      9  SELECT
    10      INLINE_VIEW.X
    11  FROM   
    12      (
    13          SELECT
    14              NESTED_INLINE_VIEW.X
    15          FROM
    16              (
    17                  SELECT
    18                      SUB_QUERY.X
    19                  FROM
    20                      SUB_QUERY
    21              ) NESTED_INLINE_VIEW
    22      ) INLINE_VIEW;
             X
             1...but when I try to use it as the SQL Query Statement for a Query object in Reports Builder, I get the following error:
    ORA-00942: table or view does not exist
    ==>SUB_QUERY
    My Reports Builder version is 10.1.2.0.2 version and my database version is 10.2.0.3.0.
    The "real" query I have been trying to use is much more complex than this -- this is just the simplest statement I have been able to come up with that causes the problem. In fact, I have some queries that have a similar structure (a WITH clause subquery referenced inside a nested inline view, along with some other things), but strangely do not cause the problem.
    I spent some time researching the problem on Google and Metalink but did not come up with any satisfactory answers. The problem sounds similar to bug 3896963, but bug 3896963 involved UNION ALL, and is supposedly fixed in my version(s).
    I tried various ways of restructuring my "real" query, but with no success -- it's going to be hard to get rid of the WITH clauses. As a "wild guess", I tried various hints (MATERIALIZE, NO_PUSH_PRED, NO_MERGE), again with no success.
    I ended up working around the problem by creating a database package with a function that returns a REF CURSOR based on the query, and then used that in a REF CURSOR query in Reports Builder. It might not be a very elegant workaround, but it works. I just wish I had "given up" and tried it sooner -- I might have saved myself some grief.

    Well, for what it's worth, I didn't end up using a REF CURSOR query after all because...
    If I ran a REP file based on a REF CURSOR query against a different database, or if I ran the REP file after the database package had been dropped and re-created, it failed with the following error:
    REP-8: Run time error in the PL/SQL development environment (DE).
    PDE-PSD001 Could not resolve reference to <Unknown Program Unit> while loading <Unknown> <Unknown>.
    REP-0008: Unexpected memory error while initializing preferences.
    It seems that Reports "binds" the REP file to the timestamp of the database package that defines the REF CURSOR type in order to validate the package at run time. If the timestamp is different, running the REP file will fail with this error. This is apparently bug 1275333 and is described in Metalink Note 272936.1.
    The bug reference and Metalink Note offerred the following workarounds:
    1. Export the database schema that contains the package from one database and import it into the other.
    In some versions, import and export preserve the timestamp, so this would avoid the problem. I didn't try this because it would not be a practical workaround in my situation (upgrade vs. new install).
    2. Recompile the package and manually set the timestamp using the seemingly undocumented ALTER PACKAGE...COMPILE BODY REUSE SETTINGS TIMESTAMP... syntax.
    I didn't try this because I didn't like the idea of having to: a) rely on an undocumented feature, and, b) manually keep track and maintain the timestamps of all the affected packages across several databases (e.g., development, test, and production).
    3. Put the package into a Reports library or into the report itself.
    This didn't work for me because Reports does not understand WITH clauses in PL/SQL. For example, with the example query in my previous post, I get an error like this:
    Error 103 at line {line defining name of factored subquery}, column {first column in line defining name of factored subquery}
    Encountered the symbol "SUB_QUERY" when expecting one of the following:
    &lt;a SQL statement&gt;
    4. Use an RDF file instead of a REP file.
    I didn't use this workaround because I wanted to protect the design of the report by using a REP file instead of an RDF file.
    So instead, I:
    1. Created a database package containing a pipelined function that returned the results of the WITH clause query that Reports did not "understand".
    2. Used an SQL query in my report of the form
    SELECT * FROM TABLE(MY_PACKAGE.MY_PIPELINED_FUNCTION(arg1, arg2, ...))
    I can drop and re-create the package and run the REP file against another database both without leading to the REP-8 error.

  • 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

  • ANy other option for WITH Clause

    Do we have any other clause in SQL which has similar functionality as WITH clause?
    Message was edited by:
    DEV

    Something like that one --
    SQL>
    SQL>
    SQL> set serveroutput on
    SQL>
    SQL>
    SQL> with tt as (select empno,ename from emp)
      2  select empno,ename from tt
      3  union
      4  select empno,null from tt
      5  where empno>2314
      6  /
         EMPNO ENAME
          7369 SMITH
          7369
          7499 ALLEN
          7499
          7521 WARD
          7521
          7566 JONES
          7566
          7654 MARTIN
          7654
          7698 BLAKE
         EMPNO ENAME
          7698
          7782 CLARK
          7782
          7788 SCOTT
          7788
          7839 KING
          7839
          7844 TURNER
          7844
          7876 ADAMS
          7876
         EMPNO ENAME
          7900 JAMES
          7900
          7902 FORD
          7902
          7934 MILLER
          7934
    28 rows selected.
    SQL>
    SQL>
    SQL> ed
    Wrote file afiedt.buf
      1  select empno,ename
      2  from (select empno,ename
      3       from emp)
      4  union
      5  select empno,null
      6  from (select empno,ename
      7        from emp)
      8* where empno>2314
    SQL> /
         EMPNO ENAME
          7369 SMITH
          7369
          7499 ALLEN
          7499
          7521 WARD
          7521
          7566 JONES
          7566
          7654 MARTIN
          7654
          7698 BLAKE
         EMPNO ENAME
          7698
          7782 CLARK
          7782
          7788 SCOTT
          7788
          7839 KING
          7839
          7844 TURNER
          7844
          7876 ADAMS
          7876
         EMPNO ENAME
          7900 JAMES
          7900
          7902 FORD
          7902
          7934 MILLER
          7934
    28 rows selected.Hope you will get some idea.
    Regards.
    Satyaki De.

  • Difference between WITH CLAUSE and INLINNE VIEW.

    Hi experts.
    Can anyone explain me the diff. between WITH CLAUSE and INLINNE VIEW with some example.
    Thanks in advance.

    user10314274 wrote:
    Hi experts.
    Can anyone explain me the diff. between WITH CLAUSE and INLINNE VIEW with some example.Generally, they are the same thing with a few minor differences.
    The WITH clause gives you a little more control on how the sub-queries are to be set up and used and allows the same subquery to be used multiple times without re-reading the data. Both simulate the functionality of views.
    I feel the WITH clause provides better strucure and maintainablility.
    The WITH clause aslo offesr two hints, INLINE and MATERIALIZE that can affect performance - both are used with the query in the IN clause. INLINE causes the subquery to be used as a subquery (inline view) while MATERIALIZE requests that the data be copied to a temporary table first. These hints are undocumented but are recognized by the user community.
    Edited by: riedelme on Jan 20, 2010 6:32 AM

  • 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.

Maybe you are looking for

  • How to extend field ANLA-XAFABCH in BAPI_FIXEDASSET_CREATE?

    Hi, I am creating an Fixed Assets upload program using BAPI. In transaction AS01, under tab Origin there is a checkbox "Purchased Used". If checked, this gets updated in ANLA-XAFABCH. In the BAPI BAPI_FIXEDASSET_CREATE, this field does not exist. Fol

  • How do I making a photo slideshow then subsequently buring to DVD?

    I have just purchased PSE Premier 12 thinking I could make a photo slideshow then burn it to DVD. However it appears that I can only make a video/movie type presentation which results in terribel graphics (blurs what are actually very sharp photos) a

  • Cursor in post-query

    Hello, in a post-query trigger i'm populating a non-database text item (with Items displayed=7) with the code DECLARE   CURSOR crElev IS     SELECT name ||' '|| surname       FROM elevi      WHERE ID=:vw_angajati_note.id_elev order by nume; BEGIN   O

  • Vlan stopped working after Solaris 11.1 upgrade

    Sorry for the long post. I upgraded a test server to Solaris 11.1 from 11/11 a few days ago. After I did the upgrade my one VLAN-based network connection stopped working. I've been messing with it for days and am a bit baffled. Note that everything w

  • Two audio tracks

    I used imovie to create hd project. Looks great played through a blue ray player and regular dvd player. Looks great on 720p and 1080p televisions. The issue is now with sound and two audio tracks. When played through built-in television speakers, th