Calling an  pipeline function in a Select query

Hello gurus ,
i have a query calling pipeline function
WITH t AS
     (SELECT dep_code, emp_id
        FROM test1
       WHERE dep_code = 'C1' AND emp_id = '123')
SELECT *
  FROM TABLE
          (CAST
              ((pk_get_emp_dtls.fn_t_get_emp_dtls (t.dep_code,
                                                   t.empid,
                                                   TRUNC (SYSDATE)
               ) AS ps_ot_emp_dtls
       t;in this above query i want to use the emp id ,dept code from the with clause as parameters in the function pk_get_emp_dtls.fn_t_get_emp_dtls
but error occures SQL command not ended properly
Regards,
Friend
Edited by: most wanted!!!! on Nov 14, 2012 6:17 AM

I see Solomon beat me to it...
SQL> create or replace type o_emp as object (empno number, ename varchar2(10))
  2  /
Type created.
SQL>
SQL> create or replace type t_emp as table of o_emp
  2  /
Type created.
SQL>
SQL> create or replace function get_emp(p_deptno in number) return t_emp pipelined as
  2    v_emp o_emp := o_emp(null,null);
  3    cursor cur_emp is
  4      select empno, ename
  5      from   emp
  6      where  deptno = p_deptno;
  7  begin
  8    for i in cur_emp
  9    loop
10      v_emp.empno := i.empno;
11      v_emp.ename := i.ename;
12      pipe row (v_emp);
13    end loop;
14    return;
15  end;
16  /
Function created.
SQL>
SQL>
SQL> with t as (select deptno from dept where dname = 'SALES')
  2  select x.*
  3  from   t, table(get_emp(t.deptno)) x
  4  /
     EMPNO ENAME
      7499 ALLEN
      7521 WARD
      7654 MARTIN
      7698 BLAKE
      7844 TURNER
      7900 JAMES
6 rows selected.
SQL> with t as (select deptno from dept where dname = 'SALES')
  2  select x.*
  3  from   table(get_emp(t.deptno)) x, t
  4  /
from   table(get_emp(t.deptno)) x, t
ERROR at line 3:
ORA-00904: "T"."DEPTNO": invalid identifier

Similar Messages

  • Trouble using pipelined function in an select list lov query

    I'm trying to use a pipelined function in a select list lov query but i cet the error
    "LOV query is invalid, a display and a return value are needed, the column names need to be different. If your query contains an in-line query, the first FROM clause in the SQL statement must not belong to the in-line query."
    my query is as follows :
    SELECT gt.navn d, gt.GEOGRAPHY_TYPE_ID r
    FROM GEOGRAPHY_TYPE gt
    WHERE gt.kode NOT IN (1)
    and gt.kode in (select lov_value from table(RAPPORT_FILTER_PKG.GET_RAPPORT_FILTER_VALUE_PIP (
    SYS_CONTEXT ('rapport_filter_ctx','filter_id'),'GEOGRAPHY_TYPES')) )
    ORDER BY gt.navn DESC
    if i use a discrete values '80' instead of the call to
    SYS_CONTEXT ('rapport_filter_ctx','filter_id')
    i don't get eny errors, but then the LOV isn't as dynamic as i has to be
    any idears???
    Edited by: [email protected] on Dec 1, 2008 8:50 AM
    Edited by: [email protected] on Dec 1, 2008 11:17 AM

    nope that doesn't do it either
    contains a syntax errror at
    SYS_CONTEXT (('rapport_filter_ctx',:P500_RAPPORT_FILTER_ID),'GEOGRAPHY_TYPES'))
    my theory is that it's got something to do with the way APEX binds values because
    the query
    SELECT gt.navn d, gt.GEOGRAPHY_TYPE_ID r
    FROM GEOGRAPHY_TYPE gt
    WHERE gt.kode NOT IN (1)
    and gt.kode in (select r from table(RAPPORT_FILTER_PKG.GET_RAPPORT_FILTER_VALUE_PIP ('80','GEOGRAPHY_TYPES')) )
    ORDER BY gt.navn DESC
    works fine in both TOAD and in APEX but as soon as i replace th '80' with :P500_RAPPORT_FILTER_ID then, apex won't accept the code??????
    Edited by: [email protected] on Dec 3, 2008 7:54 AM

  • Call the Function against a select query in 500 procedures...

    Hello Gurus,
    I have a scenario, where i had made one function(UDF Function) to calculate something and in every procedure i call that function and calculate my requirement.
    Yesterday, i made a select query using reg exp for the same calculation..
    So my question is, what should be the proper approach..
    I need to implement this on 500 procedures...
    And the UDF function is
    CREATE OR REPLACE FUNCTION "UDF_TEXTSPLIT" (
    p_list VARCHAR2,
    p_del VARCHAR2 := ','
    ) RETURN split_tbl pipelined
    IS
    l_idx PLS_INTEGER;
    l_list VARCHAR2(7999) ;
    l_value VARCHAR2(7999);
    BEGIN
    l_list := p_list;
    LOOP
    l_idx := INSTR(l_list,p_del);
    IF l_idx > 0 THEN
    pipe ROW(SUBSTR(l_list,1,l_idx-1));
    l_list := SUBSTR(l_list,l_idx+LENGTH(p_del));
    ELSE
    pipe ROW(l_list);
    EXIT;
    END IF;
    END LOOP;
    RETURN;
    END Udf_Textsplit;
    I have made this query:
    SELECT a.b,z. b1 FROM
    (SELECT ROWNUM d,REGEXP_SUBSTR(str1, '[^> ]+', 1, LEVEL) b
    FROM (SELECT 'xxx>zzz>gg' str1 FROM dual)
    CONNECT BY REGEXP_SUBSTR(str1, '[^> ]+', 1, LEVEL) IS NOT NULL)a,
    (SELECT ROWNUM d,REGEXP_SUBSTR(str1, '[^> ]+', 1, LEVEL) b1
    FROM (SELECT '100>500>20' str1 FROM dual)
    CONNECT BY REGEXP_SUBSTR(str1, '[^> ]+', 1, LEVEL) IS NOT NULL)z
    WHERE a.d=z.d
    Do i use the same select query in all 500 procedures or call the (UDF Function) in every procedure..
    So which will be faster...
    Your approach would be very much appreciated...
    Thanks,
    Haraprasad...

    Hmm, do I edit 500 procedures to replace a function call with a SQL statement, or edit 1 function to use a sql statement instead of the current algorithm?
    This is why we use code modules that do one thing and do it well. As long as the new version of the function takes the same arguments and returns the same results as the old, then the callers will never know that the way the function works has changed.
    Whenther you put the select statement in 500 procedures, or 1 function, there will still be a context switch every time you use it. The tiny additional overhead of calling a function before the context switch would be unnoticeable.
    John

  • How to reduce functions with simple select query?

    I have a function to identify the root parent of a particular id. I use this in function in select query,which invokes function for every row in table.I need to merge the function inside the query itself.Please suggest  me.
    Function
    CREATE OR REPLACE FUNCTION fnroot(v_id int ) return int as
    v_left int;
    v_right int;
    v-result int;
    begin
    select left,right into v_left,v_right from sam where id=v_id;
    select id into v_result from sam
    where id in (select id from mst m where m.depth=2 )
    and left < v_left and right > v_right;
    return v_result;
    end
    query:
    select fnroot(s.id) from master s;

    Hi,
    Ramin's idea is very good. You must use joins in function as below
    CREATE OR REPLACE FUNCTION fnroot(v_id int ) return int as
        v_result int;
    Begin
    select  s.id into v_result
      from sam s on s.id = v_id
               left join sam s2 on (s2.id in (select id from mst m where m.depth = 2) and s2.left < s.left and s2.right > s.right)
    return v_result;
    End;
    Regards
    Mahir M. Quluzade

  • How to execute an sql function containing a SELECT query as paramete

    Hi
    I want to execute this sql query using JDBC methods , but could not be able to find any appropriate method to execute this query.
    select dbms_xmlgen.getxml(select * from departments) from dual
    please some one help with appropriate java code to execute it.
    Thank you

    >
    I want to execute this sql query using JDBC methods , but could not be able to find any appropriate method to execute this query.
    select dbms_xmlgen.getxml(select * from departments) from dual
    please some one help with appropriate java code to execute it.
    >
    Java code? You can't execute that query at all since it is invalid. The parameter needs to be a query string NOT a query.
    select dbms_xmlgen.getxml('select * from departments') from dual See the DBMS_XMLGEN package in the docs
    http://docs.oracle.com/cd/B28359_01/appdev.111/b28419/d_xmlgen.htm#i1013206
    >
    Converts the results from the SQL query string to XML format, and returns the XML as a temporary CLOB, which must be subsequently freed using the DBMS_LOB.FREETEMPORARY call:
    DBMS_XMLGEN.GETXML (
    sqlQuery IN VARCHAR2,
    dtdOrSchema IN number := NONE)
    RETURN CLOB;
    >
    Then you execute that query like any other query that returns a result set. The result set will consist of one row and one column of CLOB datatype.
    See the JDBC Developer's Guide - it has examples of how to execute queries that return result sets.
    And this section shows how tow read/write CLOBs
    http://docs.oracle.com/cd/B28359_01/java.111/b31224/oralob.htm#sthref755

  • Getting NULL with function in the select Query

    Hi all,
    SELECT
    ,a.TRANSACTIONAL_CURR_CODE     
    --,gl.CONVERSION_RATE
    ,get_rate(a.transactional_curr_code,NVL(gsob.attribute1,gsob.currency_code),a.conversion_type_code,TRUNC(a.ordered_date)) CONVERSION_RATE
    FROM               
    oe_order_headers_all a,               
    oe_order_lines_all b,                 
    gl_sets_of_books gsob
    --gl_daily_rates gl
    WHERE 1=1
    and a.header_id         = b.header_id
    --and  from_currency = 'USD' --a.transactional_curr_code
    --and conversion_type = 'Corporate' --a.CONVERSION_TYPE_CODE
    --and conversion_date = '23-APR-12' --a.ORDERED_DATE
    and a.header_id =1234;
    With commented above Line
    0.749400479616307
    NULL                                        ---->Why i am getting NULL , i have a Value (0.07809)
    18.521
    Without comment above Code(Hardcoded Code or Commented Line)
    18.521
    0.749400479616307
    0.07809
    select transactional_curr_code,ORDERED_DATE from oe_order_headers_all
    where header_id=1234
    o/p:-
    USD      '23-APR-12'
    select CONVERSION_RATE from gl_daily_rates
    where from_currency = 'USD' --transactional_curr_code
    and conversion_type = 'Corporate' --CONVERSION_TYPE_CODE
    and conversion_date = '23-APR-12' --ORDERED_DATE
    --and to_currency = 'USD'
    CONVERSION_RATE
    18.521
    0.749400479616307
    0.07809
    select gsob.attribute1,gsob.currency_code from gl_sets_of_books
    where SET_OF_BOOKS_ID=1
    gsob.attribute1  gsob.currency_code
    USD                   USD

    Hi ,
    Same as below code in the Function
    select CONVERSION_RATE from gl_daily_rates
    where from_currency = 'USD' --transactional_curr_code
    and conversion_type = 'Corporate' --CONVERSION_TYPE_CODE
    and conversion_date = '23-APR-12' --ORDERED_DATE
    and to_currency = 'USD'

  • BULK COLLECT in select query inside a function

    Hi All,
    My query is :
    SELECT col1,col2,col3 FROM table_a; --( consider this is a long running query with lot of joins)
    Need to know how can i get the output of the above query from a function using BULK COLLECT.
    and i tried this:
    CREATE OR REPLACE TYPE tab_a_row
    AS OBJECT (
    col1 number(20),
    col2 number(20),
    col2 number(20)) ;
    create or replace type tab_a_nt as table of tab_a_row;
    create or replace function get_table_a
    return sys_refcursor
    is
    tab_a_recs tab_a_nt;
    rv sys_refcursor;
    begin
    SELECT tab_a_row(col1,col2,col3) BULK COLLECT INTO tab_a_recs FROM table_a;
    open rv for select * from table(tab_a_recs);
    return rv;
    end;
    Function created successfully. and i exec this from sql plus using
    SQL> var rc refcursor;
    SQL> exec :rc := get_table_a;
    BEGIN :rc := get_table_a; END;
    ERROR at line 1:
    ORA-22905: cannot access rows from a non-nested table item
    ORA-06512: at "GET_TABLE_A", line 12
    ORA-06512: at line 1
    Kindly share your ideas on how to use bulk collect and get set of outputs from a function.
    Edited by: 887268 on Apr 18, 2013 3:10 AM

    >
    If i use refcursor , then the JAVA code needs to be changed accordinglyto get the refcursor output.
    >
    Well, of course. Java has to know what the sql projection is. How else will it know how many columns there are and their datatypes.
    But that is true no matter what method you use.
    >
    But if i use a PLSQL COLLECTION TYPE (nested tables ) , then i can get output as ,
    select * from table(function_name(input1,input2));
    >
    No - using the 'table' function mean you are calling a PIPELINED function.
    This is a sample of a PIPELINED procedure.
    -- type to match emp record
    create or replace type emp_scalar_type as object
      (EMPNO NUMBER(4) ,
       ENAME VARCHAR2(10),
       JOB VARCHAR2(9),
       MGR NUMBER(4),
       HIREDATE DATE,
       SAL NUMBER(7, 2),
       COMM NUMBER(7, 2),
       DEPTNO NUMBER(2)
    -- table of emp records
    create or replace type emp_table_type as table of emp_scalar_type
    -- pipelined function
    create or replace function get_emp( p_deptno in number )
      return emp_table_type
      PIPELINED
      as
       TYPE EmpCurTyp IS REF CURSOR RETURN emp%ROWTYPE;
        emp_cv EmpCurTyp;
        l_rec  emp%rowtype;
      begin
        open emp_cv for select * from emp where deptno = p_deptno;
        loop
          fetch emp_cv into l_rec;
          exit when (emp_cv%notfound);
          pipe row( emp_scalar_type( l_rec.empno, LOWER(l_rec.ename),
              l_rec.job, l_rec.mgr, l_rec.hiredate, l_rec.sal, l_rec.comm, l_rec.deptno ) );
        end loop;
        return;
      end;
    select * from table(get_emp(20))Or your function could return a collection like the example from this thread this morning.
    Example of Collection as datatype of a function’s return value
    CREATE OR REPLACE TYPE enamelist as VARRAY(20) of VARCHAR2(20)
    /* Formatted on 4/18/2013 4:06:47 PM (QP5 v5.126.903.23003) */
    CREATE OR REPLACE FUNCTION ename_fn
    RETURN enamelist
    AS
    v_cursor_main enamelist := enamelist ();
    BEGIN
    SELECT ename
    BULK COLLECT
    INTO v_cursor_main
    FROM emp;
    RETURN v_cursor_main;
    EXCEPTION
    WHEN OTHERS
    THEN
    RETURN v_cursor_main;
    END;
    select * from table(ename_fn()) from dual;
    COLUMN_VALUE
    SMITH
    ALLEN
    WARD
    JONES
    MARTIN
    BLAKE
    CLARK
    SCOTT
    KING
    TURNER
    ADAMS
    JAMES
    FORD
    MILLER

  • Pipeline functions - what happens under the hood?  (10g)

    Hi all,
    What happens when you call a pipelined function? (As opposed to a plain table-valued function.)
    From what I understand, a pipelined function will return rows as they are needed. Let's say I have a really silly example of a pipelined function,
    CREATE OR REPLACE PACKAGE BODY TEST_PACKAGE_1
    AS
        FUNCTION GET_DATA RETURN JUST_A_TABLE PIPELINED
        IS
        BEGIN
            PIPE ROW (JUST_A_TYPE('HELLO'));
            PIPE ROW (JUST_A_TYPE('WORLD'));
            RETURN;
        END;
    END TEST_PACKAGE_1;
    /Then let's say I were to SELECT * FROM TABLE(TEST_PACKAGE_1.GET_DATA) WHERE ROWNUM = 1, what happens to the second row? Does the code that returns the second row still get educated? (Obviously it's omitted from the query, but does it still get generated somewhere and just go nowhere?)
    If I have a cursor on a PL/SQL block that selects from GET_DATA, will each row only be returned as the cursor references it? In that case, what happens to the rows that don't get selected? If there some resource that need to be closed out (say, just before the return statement), would it still be safe to close it out?
    Thanks!
    Don

    Interesting question, lets try a simple test and see we'll just take your example function and toss in a few dbms_output statements like so:
    CREATE OR REPLACE PACKAGE BODY TEST_PACKAGE_1
    AS
        FUNCTION GET_DATA RETURN JUST_A_TABLE PIPELINED
        IS   
        BEGIN
            dbms_output.put_line('ONE');
            PIPE ROW (JUST_A_TYPE('HELLO'));       
            dbms_output.put_line('TWO');
            PIPE ROW (JUST_A_TYPE('WORLD'));       
            dbms_output.put_line('THREE');
            RETURN;   
        END;
    END TEST_PACKAGE_1;Now not forgetting to enable dbms_output call it three times like so:
    SELECT * FROM TABLE(TEST_PACKAGE_1.GET_DATA) WHERE ROWNUM = 1;
    SELECT * FROM TABLE(TEST_PACKAGE_1.GET_DATA) WHERE ROWNUM <= 2;
    SELECT * FROM TABLE(TEST_PACKAGE_1.GET_DATA) WHERE ROWNUM <= 3;What I saw from my test was that with the first call I got 1 row of data from the pipelined function and only the first dbms_output statement was processed. For the second statement I got 2 rows of data from the function and the first two dbms_output statements were processed. For the final call I again got 2 rows of data from the function and all 3 dbms_output statements were processed.
    My environment:
    Oracle Database 10g Express Edition Release 10.2.0.1.0 - Product
    PL/SQL Release 10.2.0.1.0 - Production
    "CORE     10.2.0.1.0     Production"
    TNS for 32-bit Windows: Version 10.2.0.1.0 - Production
    NLSRTL Version 10.2.0.1.0 - Production

  • Tabular forms based on pipelined functions - can it be done?

    Hi there,
    Pipelined functions are great, specially when you want to encapsulate the access to tables instead of just SELECTing from them (what I am doing a lot in my current project.)
    However Apex 4 does not like them, at least not for tabular forms...
    I want to handle myself the update/insert/delete process, so I don't need the MRU default functionality (all the access to the data is via APIs). But at the same time I want to just SELECT from my pipelined function and set the item types using the builder interface as with any tabular form (without having to use the apex_item API). Also I want to be able to use tabular form validation.
    To start with, you can only create a tabular form based on a table or view. To overcome this issue, I created a dummy view with the fields I wanted and created my tabular form on it. Then I changed the FROM clause to FROM TABLE(myfunction). It didn't work as it seems it tries to select the ROWID for each row... Of course my pipelined function doesn't return one but I don't need one anyway as I will be doing the data manipulation myself based on the PK.
    For this to work, I had to create a collection, populate it with the result of the pipelined function in a page process every time the page is loaded, create a view on that collection and base the tabular form on the view... A lot of work and overhead for something that should be very simple in principle.
    Then, I found out that if I remove the default MRU process that is automatically created, the tabular form validations stop working (as I posted in another thread). So I have to leave a "dummy" MRU process there with condition = never for it to work.
    The application I am working on is all based on API calls and pipelined functions so all this work has to be repeated for each tabular form that is needed.
    If it was possible to base a tabular form directly on a pipelined function it would be such an elegant solution.
    Is there a better way to implement this? Shouldn't Apex be more compatible with pipelined functions? (at least in regards to tabular forms, they work well with normal forms, reports, LOVs etc)
    Thanks
    Luis

    As I mentioned before, I don't handle inserts (well, I cheat).... On my page, there is a form to set up a request - prompts for a few things, and when submitted, calls a stored procedure:
    :P2_REQUEST_RESULT := Simon.Apex_Campus_Guest.Setup_Request(:P2_GROUP_NAME,
           :P2_COAS_ORGN, :P2_START_DATE, :P2_END_DATE, :P2_Quantity, :P2_Generic_Names);
    Which creates an APEX collection, which in turn is made visible via a pipelined function turned into a view:
    create or replace view Apex_Campus_Guest_Request_va as
    select seq_no,
            user_name,
           group_name,
            comments
      from table ( Apex_Campus_Guest.Request_Result )
    I have a second region which is tabular form on a query - conditional on select 1 from Simon.apex_campus_guest_request_va (the view defined above).
    When this submitted, I have standard MRU and MRD processes (Seq_No is the primary key). This then runs into the appropriate trigger - the update trigger is as follows:
    trigger Apex_Campus_Guest_Req_Upd
    instead of update on Apex_Campus_Guest_Request_va
    for each row
    declare
            cg_rec  campus_guest_maint.rec;
    begin
            cg_rec := Campus_Guest_Maint.Request(
                            name => :new.user_name,
                            group_name => :new.group_name,
                            comments => :new.comments);
    end;I don't know off hand why it isn't asking for a rowid - but may be that I specified a PKEY column. The insert case fails, as it tries to add a "Returning" statement in the original select. I actually find that annoying as a function is defined to allocate the PKEY from a sequence, so it doesn't need to ask for it that way.

  • Execute pipelined function within other function .

    Hi,
    I'm on 9.2.0.8 , and got GUI application which can accept select only statements but I need kind of insert functionality.
    So I've come up with clever idea and used pipelined functions with autonymous transaction to do inserts.
    All looks like:
    select * from table(opened_cursors_list)
    select * from table(pgastat_list)
    select * from table(sqlcosts_list)
    all I need now is running this 3 function 1 after other in such way I can use select run_all_three() from dual;
    or other way but called via select so my application gui can swallow it .
    I've tried:
    CREATE OR REPLACE Function gather_test_data
           RETURN number
        IS
            cnumber number := 1;
        BEGIN
         select * from table(opened_cursors_list);
         select * from table(pgastat_list);
         select * from table(sqlcosts_list);
        RETURN cnumber;
        EXCEPTION
        WHEN OTHERS THEN
              raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM);
        END;but got error 6/2 PLS-00428: an INTO clause is expected in this SELECT statement
    So look like I need some fake I dont know how its called 'collection' to deal with that .
    I know thats whole think is kind of workaround but its working with that gui application :).
    Any ideas how to call that pipelined functions ?
    Regards.
    GregG

    Well I did pipelined functions like that:
    CREATE OR REPLACE function opened_cursors_list
    return OPENED_CURSORS_table_type
    pipelined
    as
         PRAGMA AUTONOMOUS_TRANSACTION;
    begin
         for l_rec in (select sysdate datetime, st.value , se.program, se.MODULE , se.username
                      from v$sesstat st, v$session se
                      where
                        st.statistic# = 3
                        and st.sid = se.sid
                        and value > 100
                        order by value desc
         LOOP
              PIPE ROW (OPENED_CURSORS_scalar_type(l_rec.datetime,
                                     l_rec.VALUE     ,
                                l_rec.PROGRAM   ,
                                l_rec.MODULE    ,
                                l_rec.USERNAME  ));
            insert into opened_cursors values(l_rec.datetime,
                                   l_rec.VALUE     ,
                                l_rec.PROGRAM   ,
                                l_rec.MODULE    ,
                                l_rec.USERNAME);
        commit;
         END LOOP;
         RETURN;
    END;
    /And its working, but as You said I think I need some dummy record to select into it.
    It doesn't really matters what kind of dummy record. Just to fullfil pl/sql requirements .
    So how to define such dummy record to select into it from pipelined function ?
    Regards.
    Greg
    Edited by: GregG on Apr 5, 2011 12:40 PM

  • Is there any way to pass through PIPELINED function

    Hello,
    For clarity of my code I would like to move some part of my PIPELINED function out to sub-function. It there any way to call one PIPELINED function from other PIPELINED function a way to union their results?
    I can try to use temporary table to emulate such behavior, but it won't be exactly the same...
    Regards

    Yes, you can. The only thing you need to remember is pipelined function can be salled from SQL only. So your functions will look like:
    Pipelined function 1:
    create or replace
      function pipelined_function1(...)
        return ...
        pipelined
        is
        begin
            pipe row(...);
    end;
    /Pipelined function 2:
    create or replace
      function pipelined_function2(...)
        return ...
        pipelined
        is
        begin
            for v_rec in (select * from table(pipelined_function1(...))) loop
              pipe row(...);
            end loop;
            pipe row(...);
    end;
    /SY.

  • Pipelined function in package example 11g

    Hi all,
    could you please show me example of using pipelined function in package with my sample data?
    My need is to return the following data using pipelined function in package:
    select 1 as t, 2 as y, 'u' as j, trunc(sysdate-1) as k from dual union all
    select 3 as t, 4 as y, 'h' as j, trunc(sysdate-2) as k from dual Thanks ahead.

    p.s. if your problem is that you're not sure how to pipe multiple columns, take a look at this example (from my library of standard examples)...
    SQL> CREATE OR REPLACE TYPE myemp AS OBJECT
      2  ( empno    number,
      3    ename    varchar2(10),
      4    job      varchar2(10),
      5    mgr      number,
      6    hiredate date,
      7    sal      number,
      8    comm     number,
      9    deptno   number
    10  )
    11  /
    Type created.
    SQL> CREATE OR REPLACE TYPE myrectable AS TABLE OF myemp
      2  /
    Type created.
    SQL> CREATE OR REPLACE FUNCTION pipedata(p_min_row number, p_max_row number) RETURN myrectable PIPELINED IS
      2    v_obj myemp := myemp(NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
      3  BEGIN
      4    FOR e IN (select *
      5              from (
      6                    select e.*
      7                          ,rownum rn
      8                    from (select * from emp order by empno) e
      9                   )
    10              where rn between p_min_row and p_max_row)
    11    LOOP
    12      v_obj.empno    := e.empno;
    13      v_obj.ename    := e.ename;
    14      v_obj.job      := e.job;
    15      v_obj.mgr      := e.mgr;
    16      v_obj.hiredate := e.hiredate;
    17      v_obj.sal      := e.sal;
    18      v_obj.comm     := e.comm;
    19      v_obj.deptno   := e.deptno;
    20      PIPE ROW (v_obj);
    21    END LOOP;
    22    RETURN;
    23  END;
    24  /
    Function created.
    SQL> select * from table(pipedata(1,5));
         EMPNO ENAME      JOB               MGR HIREDATE                    SAL       COMM     DEPTNO
          7369 SMITH      CLERK            7902 17-DEC-1980 00:00:00        800                    20
          7499 ALLEN      SALESMAN         7698 20-FEB-1981 00:00:00       1600        300         30
          7521 WARD       SALESMAN         7698 22-FEB-1981 00:00:00       1250        500         30
          7566 JONES      MANAGER          7839 02-APR-1981 00:00:00       2975                    20
          7654 MARTIN     SALESMAN         7698 28-SEP-1981 00:00:00       1250       1400         30
    SQL> select * from table(pipedata(6,10));
         EMPNO ENAME      JOB               MGR HIREDATE                    SAL       COMM     DEPTNO
          7698 BLAKE      MANAGER          7839 01-MAY-1981 00:00:00       2850                    30
          7782 CLARK      MANAGER          7839 09-JUN-1981 00:00:00       2450                    10
          7788 SCOTT      ANALYST          7566 19-APR-1987 00:00:00       3000                    20
          7839 KING       PRESIDENT             17-NOV-1981 00:00:00       5000                    10
          7844 TURNER     SALESMAN         7698 08-SEP-1981 00:00:00       1500          0         30
    SQL> select * from table(pipedata(11,15));
         EMPNO ENAME      JOB               MGR HIREDATE                    SAL       COMM     DEPTNO
          7876 ADAMS      CLERK            7788 23-MAY-1987 00:00:00       1100                    20
          7900 JAMES      CLERK            7698 03-DEC-1981 00:00:00        950                    30
          7902 FORD       ANALYST          7566 03-DEC-1981 00:00:00       3000                    20
          7934 MILLER     CLERK            7782 23-JAN-1982 00:00:00       1300                    10
    SQL>

  • Calling a function in the select part of a query

    I am integrating Apex with E-Bus Suite 11.5.10.2.
    I have a function in a sql query. The function calls an apps view. When i run the sql query in TOAD, I get the correct data. When I run it in Apex, i get an error - it says "Invalid number"
    My apex report is registered in my 11i menu. Who is the user that is running this report? Is it apps?
    thanks

    When you run it in TOAD, you are passing through a value, correct? Maybe when your EBS call to your APEX report is done, it is passing through a character value as apposed to a number. You might want to convert your passed in value in your function to a number to be sure..
    Also, it is not always the best idea to call a function in a select statement.. Is there a reason you can't do in sql what your function is doing?
    Thank you,
    Tony Miller
    Webster, TX

  • Calling Function In a Select

    I have a function which returns the name of a client when given
    the id of the customer as an input parameter. I want to call the
    function inside a select with the customer id as the input
    parameter not the actual id and get the name something like
    select id_cust as "id", test_function(id_cust) as "surname"
    from customers
    where -----
    Please help because I have tried and I get an error message
    ora-14551 Cannot Perform DML Inside Query

    It would help if you would post your table structure and the code for creating your function.  It sounds like your function is doing something other than what you have described that you want it to do, like some unnecessary DML.  See if you can use the following example:
    SQL> CREATE TABLE customers
      2    (id_cust   NUMBER,
      3     last_name VARCHAR2 (30))
      4  /
    Table created.
    SQL> INSERT INTO customers
      2  VALUES (1, 'TEST1')
      3  /
    1 row created.
    SQL> INSERT INTO customers
      2  VALUES (2, 'TEST2')
      3  /
    1 row created.
    SQL> CREATE OR REPLACE FUNCTION test_function
      2    (p_id_cust IN NUMBER)
      3    RETURN        VARCHAR2
      4  AS
      5    v_surname        customers.last_name%TYPE := NULL;
      6  BEGIN
      7    SELECT    last_name
      8    INTO      v_surname
      9    FROM      customers
    10    WHERE     id_cust = p_id_cust;
    11    RETURN    v_surname;
    12  END test_function;
    13  /
    Function created.
    SQL> COLUMN "surname" FORMAT A30
    SQL> SELECT id_cust AS "id",
      2         test_function (id_cust) AS "surname"
      3  FROM   customers
      4  WHERE  1 = 1
      5  /
            id surname
             1 TEST1
             2 TEST2

  • Can call a function in the select statement?

    Is there any ways to call a function in the select statement?
    what I like to do is this:
    select deptno, totalEmployees(deptno), TotalSalary(deptno)
    from emp;
    I know it can be done by count(*) and join tables, but my case
    is much more complex and the where clauses are different from
    one function to another, and have many tables to join and many
    combinations
    Thanks

    Functions can be used in a select statement subject to certain
    restrictions, see
    http://otn.oracle.com/docs/products/oracle8i/doc_library/817_doc/
    server.817/a85397/statem9b.htm#2062024
    It's under "CREATE FUNCTION> Keywords and Parameters> function>
    Restrictions on User-Defined Functions"
    Here is an except...
    When a function is called from within a query or DML statement,
    the function cannot:
    a) Have OUT or IN OUT parameters
    b) Commit or roll back the current transaction, create or roll
    back to a savepoint, or alter the session or the system. DDL
    statements implicitly commit the current transaction, so a user-
    defined function cannot execute any DDL statements.
    c) Write to the database, if the function is being called from a
    SELECT statement. However, a function called from a subquery in
    a DML statement can write to the database.
    d) Write to the same table that is being modified by the
    statement from which the function is called, if the function is
    called from a DML statement.
    Except for the restriction on OUT and IN OUT parameters, Oracle
    enforces these restrictions not only for the function called
    directly from the SQL statement, but also for any functions that
    function calls, and on any functions called from the SQL
    statements executed by that function or any function it calls.

Maybe you are looking for