Temp Table in Package returning Ref_Cursor?

I'm new to Oracle. Here is what I'm trying to do.
I need to lookup all records with a certain ID. The IDs are stored by quarter and year. I'm trying to compare records with the previous 3 quarters.
so record with ID = 1 also has Qtr = 1, Year = 2008.
I would also need to find all ID's for the previous 3 quarters ( Q 4 of 2007, Q 3 of 2007, and Q 2 of 2007).
I'm trying to write a package that will return a ref cursor with all 4 ids so the output would look like a table with 4 rows and 1 column.
In SQL Server I could create a temp table, insert these 4 values in and return a Select * From TempTable.
How can I accomplish this in Oracle 10g?

Something like this ?
test@ORA10G>
test@ORA10G> drop table tblyearquarter;
Table dropped.
test@ORA10G>
test@ORA10G> create table tblyearquarter (id, qtr, yr, createdate) as
  2  select
  3    round(dbms_random.value(1,10000)),
  4    t1.qtr,
  5    t2.yr,
  6    (sysdate - t3.indx)
  7  from
  8  (select level+2003 as yr from dual connect by level<=5) t2,
  9  (select level as qtr from dual connect by level<=4) t1,
10  (select level as indx from dual connect by level<=round(dbms_random.value(1,4))) t3;
Table created.
test@ORA10G>
test@ORA10G> select * from tblyearquarter;
        ID        QTR         YR CREATEDAT
      5059          1       2004 09-MAR-08
      6619          1       2004 08-MAR-08
      5776          1       2004 07-MAR-08
      6943          2       2004 09-MAR-08
      4338          2       2004 08-MAR-08
      8568          2       2004 07-MAR-08
      5878          3       2004 09-MAR-08
      2675          3       2004 08-MAR-08
      4667          3       2004 07-MAR-08
        40          4       2004 09-MAR-08
      1400          4       2004 08-MAR-08
      9509          4       2004 07-MAR-08
      6628          1       2005 09-MAR-08
      4356          1       2005 08-MAR-08
      2439          1       2005 07-MAR-08
      7094          2       2005 09-MAR-08
       482          2       2005 08-MAR-08
      8596          2       2005 07-MAR-08
      4855          3       2005 09-MAR-08
      4447          3       2005 08-MAR-08
      3341          3       2005 07-MAR-08
      5220          4       2005 09-MAR-08
      8461          4       2005 08-MAR-08
      2746          4       2005 07-MAR-08
      3561          1       2006 09-MAR-08
       241          1       2006 08-MAR-08
       108          1       2006 07-MAR-08
      3605          2       2006 09-MAR-08
       310          2       2006 08-MAR-08
       939          2       2006 07-MAR-08
      6611          3       2006 09-MAR-08
      5679          3       2006 08-MAR-08
      3975          3       2006 07-MAR-08
      2238          4       2006 09-MAR-08
      7323          4       2006 08-MAR-08
      8104          4       2006 07-MAR-08
      3206          1       2007 09-MAR-08
      7420          1       2007 08-MAR-08
      7386          1       2007 07-MAR-08
      4237          2       2007 09-MAR-08
      9329          2       2007 08-MAR-08
      6105          2       2007 07-MAR-08
      3800          3       2007 09-MAR-08
      3967          3       2007 08-MAR-08
      8200          3       2007 07-MAR-08
       463          4       2007 09-MAR-08
      9518          4       2007 08-MAR-08
      1451          4       2007 07-MAR-08
      9541          1       2008 09-MAR-08
      1380          1       2008 08-MAR-08
      9320          1       2008 07-MAR-08
      9720          2       2008 09-MAR-08
      4681          2       2008 08-MAR-08
      6431          2       2008 07-MAR-08
      9586          3       2008 09-MAR-08
      8620          3       2008 08-MAR-08
      6859          3       2008 07-MAR-08
      5883          4       2008 09-MAR-08
       548          4       2008 08-MAR-08
      4647          4       2008 07-MAR-08
60 rows selected.
test@ORA10G>
test@ORA10G> select id, qtr, yr
  2    from (select id, qtr, yr, rownum as rnum
  3            from (select id, qtr, yr, createdate
  4                    from (select id,
  5                                 qtr,
  6                                 yr,
  7                                 createdate,
  8                                 row_number() over(partition by yr, qtr order by createdate desc) as seq
  9                            from tblyearquarter)
10                   where seq = 1
11                   order by yr desc, qtr desc)
12           where yr || qtr <= &year || &quarter)
13   where rnum <= 4;
Enter value for year: 2008
Enter value for quarter: 1
old  12:          where yr || qtr <= &year || &quarter)
new  12:          where yr || qtr <= 2008 || 1)
        ID        QTR         YR
      9541          1       2008
       463          4       2007
      3800          3       2007
      4237          2       2007
test@ORA10G>
test@ORA10G> /
Enter value for year: 2007
Enter value for quarter: 3
old  12:          where yr || qtr <= &year || &quarter)
new  12:          where yr || qtr <= 2007 || 3)
        ID        QTR         YR
      3800          3       2007
      4237          2       2007
      3206          1       2007
      2238          4       2006
test@ORA10G>
test@ORA10G> /
Enter value for year: 2006
Enter value for quarter: 2
old  12:          where yr || qtr <= &year || &quarter)
new  12:          where yr || qtr <= 2006 || 2)
        ID        QTR         YR
      3605          2       2006
      3561          1       2006
      5220          4       2005
      4855          3       2005
test@ORA10G>
test@ORA10G>pratz

Similar Messages

  • How to don't remove global temp table after package complete.

    how to don't remove global temp table after package complete.

    any solution ?
    see this example
    http://sqlage.blogspot.in/2014/04/ssis-how-to-create-use-temp-table-in.html
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Creating WS from a pl/sql package (return ref_cursor) on a 9i database

    Howdy,
    I can create and deploy a ws built from pl/sql package on a 9i database that returns a ref_cursor. When I test it via my app server it throws the following:
    ERROR>oracle.xml.sql.OracleXMLSQLException: Character '#' is not allowed in an XML tag name.</ERROR>
    If I run a similar ws built on a 10g database there is no error. What am I missing?
    Jdeveloper: 10.1.3.3
    9i Database: 9.2.0.6
    10g Database: 10.2.0.2.0
    Oracle AS Control: 10.1.3.1.0

    Ok so I played around with this some more. I created the same process in bpel using oracle bpel designer and here are the results.
    1. Against 10g database running a synch process data is retutned without error.
    2. Against 9i database running an asynch process data is retutned without error.
    3. Against 9i database running a synch process data is retutned with error.
    I'm definilty missing something.

  • Global temp table vs. package variables

    hi all,
    i need to know which is a better approach to store session based values in terms of security and performance.
    option one
    create global temporary table my_session_tbl ( code varchar2(30), value varchar2(1000) );option two
    create or replace package my_session
    as
      type session_tab_type is table of varchar2(1000) index by varchar2(30);
      session_tab session_tab_type;
    end;thanks
    allen

    That depends entirely on your requirements.
    For example, if you are using that temp values primarily in SQL, storing it in PL requires (expensive) context switching from SQL to PL to access the values. If the temp values are primarily used in PL code, the reverse is true.
    PL code requires PGA memory - private and expensive process memory. So there is a limit on just how much temporary values you can pump into a PL data segment before it becomes very expensive.
    It depends on how you want to use that temp values. A GTT supports indexing, and via SQL can be filtered, sorted, aggregated, and analysed far easier that any data structure in PL code.
    So you need to look at:
    a) how you are going to use the data
    b) from what language
    c) what the data volumes are
    I fail to see how security will play an issue - as a GTT and PL data structure are both local to the current process. Exposing that would in both cases be a coding flaw and not a problem or issue associated with the GTT or PL data structure itself.

  • Global Temp Table, always return  zero records

    I call the procedure which uses glbal temp Table, after executing the Proc which populates the Global temp table, i then run select query retrieve the result, but it alway return zero record. I am using transaction in order to avoid deletion of records in global temp table.
    whereas if i do the same thing in SQL navigator, it works
    Cn.ConnectionString = Constr
    Cn.Open()
    If FGC Is Nothing Then
    Multiple = True
    'Search by desc
    'packaging.pkg_msds.processavfg(null, ActiveInActive, BrandCode, Desc, Itemtype)
    SQL = "BEGIN packaging.pkg_msds.processavfg(null,'" & _
    ActiveInActive & "','" & _
    BrandCode & "','" & _
    Desc & "','" & _
    Itemtype & "'); end;"
    'Here it will return multiple FGC
    'need to combine them
    Else
    'search by FGC
    SQL = "BEGIN packaging.pkg_msds.processavfg('" & FGC & "','" & _
    ActiveInActive & "','" & _
    BrandCode & "',null,null); end;"
    'will alway return one FGC
    End If
    ' SQL = " DECLARE BEGIN rguo.pkg_msds.processAvedaFG('" & FGC & "'); end;"
    Stepp = 1
    Cmd.Connection = Cn
    Cmd.CommandType = Data.CommandType.Text
    Cmd.CommandText = SQL
    Dim Trans As System.Data.OracleClient.OracleTransaction
    Trans = Cn.BeginTransaction()
    Cmd.Transaction = Trans
    Dim Cnt As Integer
    Cnt = Cmd.ExecuteNonQuery
    'SQL = "SELECT rguo.pkg_msds.getPDSFGMass FROM dual"
    SQL = "select * from packaging.aveda_mass_XML"
    Cmd.CommandType = Data.CommandType.Text
    Cmd.CommandText = SQL
    Adp.SelectCommand = Cmd
    Stepp = 2
    Adp.Fill(Ds)
    If Ds.Tables(0).Rows.Count = 0 Then
    blError = True
    BlComposeXml = True
    Throw New Exception("No Record found for FGC(Finished Good Code=)" & FGC)
    End If
    'First Row, First Column contains Data as XML
    Stepp = 0
    Trans.Commit()

    Hi,
    This forum is for Oracle's Data Provider and you're using Microsoft's, but I was curious so I went ahead and tried it. It works fine for me. Here's the complete code I used, could you point out what are you doing differently?
    Cheers,
    Greg
    create global temporary table abc_tab(col1 varchar2(10));
    create or replace procedure ins_abc_tab(v1 varchar2) as
    begin
    insert into abc_tab values(v1);
    end;
    using System;
    using System.Data;
    using System.Data.OracleClient;
    class Program
        static void Main(string[] args)
            OracleConnection con = new OracleConnection("data source=orcl;user id=scott;password=tiger");
            con.Open();
            OracleTransaction txn = con.BeginTransaction();
            OracleCommand cmd = new OracleCommand("begin ins_abc_tab('foo');end;", con);
            cmd.Transaction = txn;
            cmd.ExecuteNonQuery();
            cmd.CommandText = "select * from abc_tab";
            OracleDataAdapter da = new OracleDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            Console.WriteLine("rows found: {0}", ds.Tables[0].Rows.Count);
            // commit, cleanup, etc ommitted for clarity
    }

  • SSIS package takes longer time when inserting data into temp tables

    querying records from one  server  and  inserting them into temp tables is taking longer time.
    are there any setting in package which  enhance the performance .

    will local temp table (#temp ) enhance the performance  ..
    If you're planning to use # tables in ssis make sure you read this
    http://consultingblogs.emc.com/jamiethomson/archive/2006/11/19/SSIS_3A00_-Using-temporary-tables.aspx
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Visual Basic, DAO, Temp tables in stored procedures

    Client code currently uses DAO with SQLPassthrough option in VB to connect to SQl 6.5 db.
    I migrated all stored procedures with default options except Oracle 8i temp tables. For every procedure a package and a procedure was created. We use SQL server temporary tables extensively in a few hundred stored procedures. The ref cursor created refers to the temporary table. While migratiing, Create table statement is commented. How are SQL6.5 equivalent of temp tables handled in Oracle? Is there an alternative to temp tables?
    I also migrated to another oracle db using the INOUT type for stored procedures. This time only procedures were created. Can these procedures return a record set in DAO with SQLPAssthrough?
    How do you call a procedure using DAO in VB to get recordsets?
    What is the best way to migrate to Oracle with minimal client code changes?
    Thank you in advance.
    Umesh
    null

    Karthick_Arp wrote:
    BluShadow wrote:
    I agree with Karthick, there's no need for a temporary table in this situation.
    And to add, temporary tables should not be created at runtime, they should be part of the initial design of the database, created once and used as needed. Creating them at runtime is just wrong.The problem is the name oracle has given to GTT. The word Temporary mislead lot of SQL Server developers and they think its something same as the temporary table used in SQL Server :)Yeah, Ingres does something similar to SQL Server too, in that you can create a temporary table (Ingres assigned it a unique name and tells you what it is), and you set an expiry time on it (i.e. set it to expire in 1 days time), and then a background process is supposed to clean up the tables that have expired. Unlike Oracle, they are not session specific, but become visible to all once created.
    I think there's room for both types of temporary table, but Oracle's does the job (except when you want to use them from a stateless application front end).

  • Stored procedure with temp table creation inside and using it

    I want to create a temp table inside a stred procedure and make use of it . I want perform some delete statements based on select statemets .An I want to drop the table at the end .
    When I tried to create a table inside the stored procedure using exxecute immediate statement ,.
    sql_stmt := 'CREATE GLOBAL TEMPORARY TABLE pattern_str_temp as select * from pattern_structure';
         EXECUTE IMMEDIATE 'CREATE GLOBAL TEMPORARY TABLE pattern_str_temp as select * from woc_pattern_structure' ;
    Then my select statements that contain this table do not identify the table name.
    I got compilor error when I use it in hte stored procedure in the select statement .Then I did like this-
    WHENEVER SQLERROR CONTINUE
    DROP TABLE pattern_str_temp;
    CREATE TABLE pattern_str_temp AS SELECT * FROM pattern_structure ;
    COMMIT;
    CREATE OR REPLACE PACKAGE BODY Woc_Delete_Model_Data
    AS
    NAME: Woc_Delete_Model_Data
    PURPOSE:
    REVISIONS:
    Ver Date Author Description
    1.0 11/01/2008 gtutika 1. Deletes given Product Model
    PROCEDURE deleteCategory(p_product_model IN varchar2,
                   p_request_status OUT VARCHAR2,
                   p_err_mesg OUT VARCHAR2
    IS
    l_category VARCHAR2(200);
    l_count NUMBER;
    CURSOR getAttribute IS
         SELECT Category_Name
         FROM
    Woc_Attribute_Category
    WHERE Attribute_Name in
    (SELECT Child_Name FROM pattern_structure
    WHERE Child_Type = 'Attribute' and product_Model_Name = p_product_model)
    FOR UPDATE;
    BEGIN
         DBMS_OUTPUT.ENABLE(1000000);
         --dbms_output.put_line('START-Inside DeleteCategory Procedure .........');
         --sql_stmt := 'CREATE GLOBAL TEMPORARY TABLE pattern_str_temp as select * from pattern_structure';
         --EXECUTE IMMEDIATE 'CREATE GLOBAL TEMPORARY TABLE pattern_str_temp as select * from pattern_structure' ;
         OPEN getAttribute ;
    LOOP
         FETCH getAttribute INTO l_category ;
         EXIT WHEN getAttribute%NOTFOUND;
         l_count := Is_Category_Used(p_product_model , l_category);
    IF (l_count=0) THEN
         DELETE FROM WOC_ATTRIBUTE_CATEGORY where CATEGORY_NAME = l_category;
         DELETE from woc_item_category
         where CATEGORY_NAME = l_category;
         DELETE FROM WOC_CATEGORY WHERE CATEGORY_NAME = l_category;
    END IF;
         END LOOP;
         --(getAttribute%ROWCOUNT);
         CLOSE getAttribute;
         --dbms_output.put_line('END-Inside DeleteCategory Procedure .........');
    EXCEPTION
         WHEN OTHERS THEN
         dbms_output.put_line(SQLERRM);
              p_err_mesg := 'ERROR IN CUSOR';
              --dbms_output.put_line('ERROR in CUSOR');
              ROLLBACK;
    END;
    FUNCTION Is_Category_Used(p_product_model IN varchar2 , p_category IN Varchar2)
         RETURN NUMBER IS
         l_count NUMBER;
         l_attribute VARCHAR2(40);
         l_pattern varchar2(30);
         CURSOR getAttribute IS
         SELECT attribute_Name from
         WOC_ATTRIBUTE_CATEGORY WHERE category_name = p_category and Attribute_Name in
         (Select Child_Name from pattern_str_temp
         where child_type = 'Attribute' and product_Model_Name = p_product_model);
    BEGIN
    DBMS_OUTPUT.ENABLE(1000000);
         SELECT count(*) into l_count from
         WOC_ATTRIBUTE_CATEGORY WHERE category_name = p_category and Attribute_Name in
         (Select Child_Name from pattern_str_temp
    where child_type = 'Attribute' and product_Model_Name <> p_product_model);
         OPEN getAttribute;
    LOOP
         FETCH getAttribute INTO l_attribute;
         EXIT WHEN getAttribute%NOTFOUND;
         DELETE FROM pattern_str_temp WHERE Product_Model_Name=p_product_model
         and child_type = 'Attribute' and child_Name= l_attribute;
         END LOOP;
         CLOSE getAttribute;
         RETURN l_count;
    EXCEPTION
    WHEN OTHERS THEN
    dbms_output.put_line(SQLERRM);
              --dbms_output.put_line('ERROR in CUSOR');
              ROLLBACK;
    END;
    PROCEDURE delete_batch_woc_model(p_product_model IN VARCHAR2,p_flag IN VARCHAR2,
    p_err_mesg OUT VARCHAR2)
         IS
         p_request_status VARCHAR2(30);
    BEGIN
         deleteCategory(p_product_model,p_request_status ,p_err_mesg );
    EXCEPTION WHEN OTHERS THEN
         dbms_output.put_line(SQLERRM);
              p_err_mesg := 'ERROR IN CUSOR';
              dbms_output.put_line('ERROR in CUSOR');
              ROLLBACK;
    END;
    END Woc_Delete_Model_Data;
    --drop table pattern_str_temp ;
    SHOW ERRORS;
    But once the data is deleted , the data in the temp table is deleted when I load the data and try to delete it agian since I have no data in temp table ,the data is not deleted .So I need to create the temp table every time the stored procedure is called ,delete accordingly and drop the table at the end .
    Please suggest how to do it.
    Thanks.

    I'm not sure I understand what you're attempting to do...
    What is the benefit of a temporary table that stores the same set of data that is in the master table? Why not just
    DELETE FROM child_table1
    WHERE foreign_key IN (
        SELECT primary_key
          FROM master_table
         WHERE some_condition);
    DELETE FROM child_table2
    WHERE foreign_key IN (
        SELECT primary_key
          FROM master_table
         WHERE some_condition);
    DELETE FROM child_table30
    WHERE foreign_key IN (
        SELECT primary_key
          FROM master_table
         WHERE some_condition);
    DELETE FROM master_table
    WHERE some_condition;or
    FOR x IN (SELECT * FROM master_table WHERE some_condition)
    LOOP
      DELETE FROM child_table1 WHERE foreign_key = x.primary_key;
      DELETE FROM child_table2 WHERE foreign_key = x.primary_key;
      DELETE FROM child_table30 WHERE foreign_key = x.primary_key;
      DELETE FROM master_table WHERE primary_key = x.primary_key;
    END LOOP;Justin

  • Data storage in temp tables

    Question 1: I have created a global temporary table tt_groups(grp_ids number) on commit preserve rows; and I was wondering - if I have multiple users accessing this temp table at the same time, do I need to differenciate between the users, or will Oracle put a userid on them?
    Question 2: I am attempting to enter data into these temp tables within a function that will actually use the data. This function contains and returns a cursor. So far, I have been having great difficulties with this - to the point that I am ready to write an addition function just to store the data in the temp table. Does any one have any suggestions? Here is a sample of my code in case that would help. btw - str2tbl is a home grown conversion tool that parses a string and puts the data into rows of number. We have used it in many functions and so far don't have any issues associated with it.
    in_groupid IN VARCHAR2
    IS
    BEGIN
    INSERT INTO tt_groups(grp_ids)
    VALUES (
    SELECT Column_Value
    FROM THE (
    select cast(STR2TBL(in_groupid) as mytableType)
    from dual
    COMMIT;
    END;
    I am new to the whole sp/function coding, so any advice would be appreciated.
    Thanks,
    Susan

    Thanks, Justin, for your reply.
    I am pleased to hear that the temp table is session-specific.
    I attempted to update my statement to match what you suggested, but I am still getting "invalid" whenever I try to compile the function through schema mgr. Do you see anything that I might be missing? I incorporated the BEGIN; COMMIT; and END;, but is there something else that I am supposed to have? I downloaded a couple of Oracle handbooks and I have one book, Oracle8i - the complete reference, (we are using 9i) that I am referring to all the time, but I can't seem to get it to work! Here is more of my code:
    in_groupid IN VARCHAR2
    RETURN Types.ref_cursor
    AS
         resource_cursor types.ref_cursor;
    BEGIN
         OPEN resource_cursor FOR
    SELECT DISTINCT
    CATEGORY.CATID, SUBCATEGORY.SUBCATID
    FROM SUBCATEGORY, CATSUBCAT, CATEGORY, SUBRES
    WHERE SUBCATEGORY.SUBCATID = CATSUBCAT.SUBCATID AND
    CATSUBCAT.CATID = CATEGORY.CATID AND
    (CATSUBCAT.GROUPID IN (select grp_ids from tt_groups)) AND
    (SUBRES.GROUPID IN (select grp_ids from tt_groups))
    I want to insert this code into the function above:
    INSERT INTO dtra_tt_groups(grp_ids)
    SELECT Column_Value
    FROM THE (
    select cast(STR2TBL(in_groupid) as mytableType)
    from dual
    COMMIT;
    Where would I insert this statement?
    Thanks,
    Susan

  • CURSOR on a temp table?

    hello
    *okay this following is WORKING and CORRECT:*
    CREATE OR REPLACE FUNCTION fnGetParents
    ObjectId number,
    ObjectClassifier varchar2
    RETURN typescursorType
    IS
    fnGetParents_cursor types.cursorType;
    BEGIN
    EXECUTE IMMEDIATE (''CREATE GLOBAL TEMPORARY TABLE TMP_HierarchyMap
    Id numeric(19,0) NOT NULL,
    ParentId numeric(19,0) NOT NULL,
    ChildId numeric(19,0) NOT NULL,
    ) on commit delete rows'');
    EXECUTE IMMEDIATE (''CREATE GLOBAL TEMPORARY TABLE TEMP_ID
    Id numeric(19,0) NOT NULL,
    bDone NUMERIC(1,0) NOT NULL
    ) on commit delete rows'');
    /* recursive call: spRecursiveGetParents(ObjectId, ObjectClassifier); */
    OPEN fnGetParents_cursor FOR
    SELECT
    Id,
    ParentId,
    ChildId,
    FROM TMP_HierarchyMap;
    RETURN fnGetParents_cursor;
    END fnGetParents;
    My question is, how can I do something like this:
    EXECUTE IMMEDIATE 'CREATE OR REPLACE TYPE TmpHierarchyMapObjType AS OBJECT
    Id numeric(19,0) ,
    ParentId numeric(19,0),
    ChildId numeric(19,0),
    EXECUTE IMMEDIATE 'CREATE OR REPLACE TYPE TmpHierarchyMapTableType AS TABLE OF TmpHierarchyMapObjType;';
    EXECUTE IMMEDIATE 'CREATE OR REPLACE PACKAGE types AS
    TYPE cursorType IS REF CURSOR;
    END; ';
    CREATE OR REPLACE FUNCTION fnGetParents
    ObjectId number,
    ObjectClassifier varchar2
    RETURN typescursorType
    IS
    TmpHierarchyMap TmpHierarchyMapTableType := TmpHierarchyMapTableType();
    fnGetParents_cursor types.cursorType;
    BEGIN
    EXECUTE IMMEDIATE (''CREATE GLOBAL TEMPORARY TABLE TMP_HierarchyMap
    Id numeric(19,0) NOT NULL,
    ParentId numeric(19,0) NOT NULL,
    ChildId numeric(19,0) NOT NULL,
    ) on commit delete rows'');
    EXECUTE IMMEDIATE (''CREATE GLOBAL TEMPORARY TABLE TEMP_ID
    Id numeric(19,0) NOT NULL,
    bDone NUMERIC(1,0) NOT NULL
    ) on commit delete rows'');
    /* recursive call: spRecursiveGetParents(ObjectId, ObjectClassifier); */
    OPEN fnGetParents_cursor FOR
    SELECT
    Id,
    ParentId,
    ChildId,
    FROM TMP_HierarchyMap;
    -- I want to learn how to enumerate a temp table and put it in a nested table but keep getting error on loop
    FOR oMap in spGetChildren_cursor LOOP
                             TmpHierarchyMap.Extend();
                             TmpHierarchyMap(TmpHierarchyMap.Count) := TmpHierarchyMapObjType( oMap.Id                                                                                               ,oMap.ParentId                                                                                               , oMap.ChildId
                        END LOOP;
    RETURN fnGetParents_cursor;
    END fnGetParents;
    I just want to know how for sake of learning.
    Thanks

    As mentioned yesterday, if you create database objects dynamically, you have to query them dynamically.
    For example, you could use the DBMS_SQL package, which offers one of the most flexible ways of dyanamic queries..
    [DBMS_SQL Package|http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_sql.htm#sthref6136]
    CREATE OR REPLACE PROCEDURE run_query(p_sql IN VARCHAR2) IS
      v_finaltxt  VARCHAR2(4000);
      v_v_val     VARCHAR2(4000);
      v_n_val     NUMBER;
      v_d_val     DATE;
      v_ret       NUMBER;
      c           NUMBER;
      d           NUMBER;
      col_cnt     INTEGER;
      f           BOOLEAN;
      rec_tab     DBMS_SQL.DESC_TAB;
      col_num     NUMBER;
    BEGIN
      c := DBMS_SQL.OPEN_CURSOR;
      DBMS_SQL.PARSE(c, p_sql, DBMS_SQL.NATIVE);
      d := DBMS_SQL.EXECUTE(c);
      DBMS_SQL.DESCRIBE_COLUMNS(c, col_cnt, rec_tab);
      FOR j in 1..col_cnt
      LOOP
        CASE rec_tab(j).col_type
          WHEN 1 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000);
          WHEN 2 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_n_val);
          WHEN 12 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_d_val);
        ELSE
          DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000);
        END CASE;
      END LOOP;
      FOR j in 1..col_cnt
      LOOP
        v_finaltxt := ltrim(v_finaltxt||','||lower(rec_tab(j).col_name),',');
      END LOOP;
      DBMS_OUTPUT.PUT_LINE(v_finaltxt);
      LOOP
        v_ret := DBMS_SQL.FETCH_ROWS(c);
        EXIT WHEN v_ret = 0;
        v_finaltxt := NULL;
        FOR j in 1..col_cnt
        LOOP
          CASE rec_tab(j).col_type
            WHEN 1 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_v_val);
                        v_finaltxt := ltrim(v_finaltxt||',"'||v_v_val||'"',',');
            WHEN 2 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_n_val);
                        v_finaltxt := ltrim(v_finaltxt||','||v_n_val,',');
            WHEN 12 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_d_val);
                        v_finaltxt := ltrim(v_finaltxt||','||to_char(v_d_val,'DD/MM/YYYY HH24:MI:SS'),',');
          ELSE
            v_finaltxt := ltrim(v_finaltxt||',"'||v_v_val||'"',',');
          END CASE;
        END LOOP;
        DBMS_OUTPUT.PUT_LINE(v_finaltxt);
      END LOOP;
      DBMS_SQL.CLOSE_CURSOR(c);
    END;
    SQL> exec run_query('select * from emp');
    empno,ename,job,mgr,hiredate,sal,comm,deptno
    7369,"SMITH","CLERK",7902,17/12/1980 00:00:00,800,,20
    7499,"ALLEN","SALESMAN",7698,20/02/1981 00:00:00,1600,300,30
    7521,"WARD","SALESMAN",7698,22/02/1981 00:00:00,1250,500,30
    7566,"JONES","MANAGER",7839,02/04/1981 00:00:00,2975,,20
    7654,"MARTIN","SALESMAN",7698,28/09/1981 00:00:00,1250,1400,30
    7698,"BLAKE","MANAGER",7839,01/05/1981 00:00:00,2850,,30
    7782,"CLARK","MANAGER",7839,09/06/1981 00:00:00,2450,,10
    7788,"SCOTT","ANALYST",7566,19/04/1987 00:00:00,3000,,20
    7839,"KING","PRESIDENT",,17/11/1981 00:00:00,5000,,10
    7844,"TURNER","SALESMAN",7698,08/09/1981 00:00:00,1500,0,30
    7876,"ADAMS","CLERK",7788,23/05/1987 00:00:00,1100,,20
    7900,"JAMES","CLERK",7698,03/12/1981 00:00:00,950,,30
    7902,"FORD","ANALYST",7566,03/12/1981 00:00:00,3000,,20
    7934,"MILLER","CLERK",7782,23/01/1982 00:00:00,1300,,10
    PL/SQL procedure successfully completed.
    SQL> exec run_query('select * from dept');
    deptno,dname,loc
    10,"ACCOUNTING","NEW YORK"
    20,"RESEARCH","DALLAS"
    30,"SALES","CHICAGO"
    40,"OPERATIONS","BOSTON"
    PL/SQL procedure successfully completed.Or you could build up a query to use with execute immediate, but then you will need to ensure you know what columns you expect as output.

  • PLSQL script not collecting temp table fields - variables problem?

    I've 'written' a script to extract data from a temp table and load it directly into the associated Oracle tables via HRMS's
    API packages.. but when I put the DBMS_OUTPUT.PUT_LINE's in I see that although it seems to read first API OK it doesn't collect the information from their relevant fields in the temp table.. Can anyone help please please..?
    ======================== code ==========================
    SET serveroutput ON SIZE 1000000
    SET verify OFF
    SET feedback OFF
    DECLARE
    -- Debugging/error handling
    v_err_seq NUMBER := 0;
    v_err_num VARCHAR2 (30);
    v_err_msg VARCHAR2 (250);
    v_err_line VARCHAR2 (350);
    -- Work variables
    p_hire_date DATE;
    p_business_group_id NUMBER := 0;
    p_person_id NUMBER := 0;
    p_address_line1 VARCHAR2 (240);
    p_date_of_birth VARCHAR2 (35);
    p_address_line2 VARCHAR2 (240);
    employee_number VARCHAR2 (14);
    p_employee_number VARCHAR2 (14);
    emp_number VARCHAR2 (14);
    p_email_address VARCHAR2 (240);
    p_address_line3 VARCHAR2 (240);
    p_first_name VARCHAR2 (150);
    p_address_line4 VARCHAR2 (240);
    p_middle_names VARCHAR2 (30);
    p_post_code VARCHAR2 (30);
    p_last_name VARCHAR2 (150);
    p_nationality VARCHAR2 (30);
    p_sex VARCHAR2 (30);
    p_national_identifier VARCHAR2 (30);
    p_title VARCHAR2 (30);
    v_rec_cnt NUMBER := 0;
    insert_flag VARCHAR2 (8);
    -- ip_p_address_id NUMBER;
    ip_p_address_id per_addresses.address_id%TYPE;
    ip_p_object_version_number NUMBER;
    ip_p_party_id per_addresses.party_id%TYPE;
    l_person_id per_all_people_f.person_id%TYPE;
    l_employee_number VARCHAR2 (35);
    l_validate BOOLEAN DEFAULT FALSE;
    l_assignment_id NUMBER;
    l_per_object_version_number NUMBER;
    l_asg_object_version_number NUMBER;
    l_per_effective_start_date DATE;
    l_per_effective_end_date DATE;
    l_full_name VARCHAR2 (240);
    l_per_comment_id NUMBER;
    l_assignment_sequence NUMBER;
    l_assignment_number VARCHAR2 (100);
    l_name_combination_warning BOOLEAN;
    l_assign_payroll_warning BOOLEAN;
    l_address_id NUMBER;
    l_object_version_number NUMBER;
    return_code NUMBER;
    return_message VARCHAR2 (2000);
    command_prin VARCHAR2 (4000);
    -- Get employee details info from work table
    CURSOR get_employee_details
    IS
    SELECT p_person_id, p_validate, p_hire_date, p_business_group_id,
    p_last_name, p_sex, p_date_of_birth, p_email_address,
    p_employee_number, p_first_name, p_marital_status,
    p_middle_names, p_nationality, p_title, p_national_identifier,
    p_address_line1, p_address_line2, p_address_line3,
    p_address_line4, p_post_code
    FROM SU_TEMPLOYEE_DETAILS;
    -- checks employee details info from PER_ALL_PEOPLE_F table
    -- v_err_seq := 1;
    CURSOR c_check_employee (emp_number VARCHAR2)
    IS
    SELECT per.person_id, per.business_group_id, per.last_name,
    per.start_date, per.date_of_birth, per.email_address,
    per.employee_number, per.first_name, per.marital_status,
    per.middle_names, per.nationality, per.national_identifier,
    per.sex, per.title, padd.address_id, padd.primary_flag,
    padd.address_line1, padd.address_line2, padd.address_line3,
    padd.town_or_city, padd.postal_code, padd.telephone_number_1,
    padd.object_version_number
    FROM per_all_people_f per, per_addresses padd
    WHERE per.employee_number = emp_number
    AND per.person_id = padd.person_id;
    emp_rec c_check_employee%ROWTYPE;
    BEGIN
    --v_err_seq := 2;
    command_prin := SQLERRM;
    LOOP
    -- Process each record in the work table
    FOR v_emp IN get_employee_details
    LOOP
    v_rec_cnt := v_rec_cnt + 1;
    -- determine whether customer already exists
    OPEN c_check_employee (v_emp.p_employee_number);
    FETCH c_check_employee
    INTO emp_rec;
    IF c_check_employee%NOTFOUND
    THEN
    insert_flag := 'I';
    ELSE
    insert_flag := 'X';
    END IF;
    IF insert_flag = 'I'
    THEN
    -- RETURN 'Employee does not exist, continue import..';
    DBMS_OUTPUT.PUT_LINE ('Employee does not exist, continue import..');
    ELSE
    DBMS_OUTPUT.PUT_LINE ('Employee found - record cannot be imported.');
    END IF;
    CLOSE c_check_employee;
    -- v_err_seq := 3;
    -- Create new PER_ALL_PEOPLE_F and PER_ADDRESSES record from
    -- info in table record
    IF insert_flag = 'I'
    THEN
    BEGIN -- Importing Employee Procedure --
    DBMS_OUTPUT.PUT_LINE ('          ');
    DBMS_OUTPUT.PUT_LINE ('Importing employees....Hold On.......!     ');
         DBMS_OUTPUT.PUT_LINE ('          ');
    BEGIN
    Hr_Employee_Api.create_gb_employee
    (p_validate => l_validate, --FALSE,
    p_hire_date => p_hire_date,
    p_business_group_id => p_business_group_id,
    p_date_of_birth => p_date_of_birth,
    p_email_address => p_email_address,
    p_first_name => p_first_name,
    p_middle_names => p_middle_names,
    p_last_name => p_last_name,
    p_sex => p_sex,
    p_ni_number => p_national_identifier,
    p_employee_number => l_employee_number,
    p_person_id => l_person_id,
    p_title => p_title,
    p_assignment_id => l_assignment_id,
    p_per_object_version_number => l_per_object_version_number,
    p_asg_object_version_number => l_asg_object_version_number,
    p_per_effective_start_date => l_per_effective_start_date,
    p_per_effective_end_date => l_per_effective_end_date,
    p_full_name => l_full_name,
    p_per_comment_id => l_per_comment_id,
    p_assignment_sequence => l_assignment_sequence,
    p_assignment_number => l_assignment_number,
    p_name_combination_warning => l_name_combination_warning,
    p_assign_payroll_warning => l_assign_payroll_warning
    DBMS_OUTPUT.PUT_LINE
    ('..employee record updated succesfully..');
    DBMS_OUTPUT.PUT_LINE ('          ');
    DBMS_OUTPUT.PUT_LINE ('          ');
    EXCEPTION
    WHEN OTHERS
    THEN
    DBMS_OUTPUT.PUT_LINE ('..SQLCodeErrors:- ' || SQLCODE);
         DBMS_OUTPUT.PUT_LINE (' ');
    DBMS_OUTPUT.PUT_LINE ('Person ID:-' || p_person_id || l_person_id);
    DBMS_OUTPUT.PUT_LINE ('Assignmnt Seq - '|| l_assignment_sequence);
    DBMS_OUTPUT.PUT_LINE ('l_ass_no - ' ||l_assignment_number);
    -- DBMS_OUTPUT.PUT_LINE ('Record failed to load.. ' || SQLERRM);
    DBMS_OUTPUT.PUT_LINE (SUBSTR (command_prin, 1, 250));
    END;
    BEGIN -- Importing Associated Address Procedure --
    DBMS_OUTPUT.PUT_LINE ('          ');
    -- ('..and the associated employee address....');
    Hr_Person_Address_Api.create_person_address
    (p_validate => l_validate,
    -- p_effective_date => p_hire_date,
    p_effective_date => SYSDATE,
    p_pradd_ovlapval_override => NULL,
    p_validate_county => NULL,
    p_person_id => l_person_id,
    p_primary_flag => 'Y',
    p_style => 'GB_GLB',
    -- p_date_from => p_hire_date,
    p_date_from => SYSDATE,
    p_date_to => NULL,
    p_address_type => NULL,
    p_comments => NULL,
    p_address_line1 => p_address_line1,
    p_address_line2 => p_address_line2,
    p_address_line3 => p_address_line3,
    p_town_or_city => p_address_line4,
    p_region_1 => NULL,
    p_region_2 => NULL,
    p_region_3 => NULL,
    p_postal_code => p_post_code,
    p_country => p_nationality,
    p_telephone_number_1 => NULL,
    p_telephone_number_2 => NULL,
    p_telephone_number_3 => NULL,
    p_addr_attribute_category => NULL,
    p_addr_attribute1 => NULL,
    p_addr_attribute2 => NULL,
    p_addr_attribute3 => NULL,
    p_addr_attribute4 => NULL,
    p_addr_attribute5 => NULL,
    p_addr_attribute6 => NULL,
    p_addr_attribute7 => NULL,
    p_addr_attribute8 => NULL,
    p_addr_attribute9 => NULL,
    p_addr_attribute10 => NULL,
    p_addr_attribute11 => NULL,
    p_addr_attribute12 => NULL,
    p_addr_attribute13 => NULL,
    p_addr_attribute14 => NULL,
    p_addr_attribute15 => NULL,
    p_addr_attribute16 => NULL,
    p_addr_attribute17 => NULL,
    p_addr_attribute18 => NULL,
    p_addr_attribute19 => NULL,
    p_addr_attribute20 => NULL,
    p_add_information13 => NULL,
    p_add_information14 => NULL,
    p_add_information15 => NULL,
    p_add_information16 => NULL,
    p_add_information17 => NULL,
    p_add_information18 => NULL,
    p_add_information19 => NULL,
    p_add_information20 => NULL,
    -- p_party_id => NULL,
    p_party_id => ip_p_party_id,
    p_address_id => ip_p_address_id,
    p_object_version_number => ip_p_object_version_number
    DBMS_OUTPUT.PUT_LINE ('Address Updation/Insertion has been successful!');
    EXIT WHEN command_prin IS NULL;
    command_prin := SUBSTR (command_prin, 251);
    END;
    END;
    -- v_err_seq := 4;
    -- End of customer related details
    END IF;
    END LOOP;
    -- DBMS_OUTPUT.PUT_LINE ('Records read : ' || v_rec_cnt);
    -- v_err_seq := 5;
    --EXCEPTION
    -- WHEN OTHERS THEN
    -- ROLLBACK;
    -- Output Error Message
    -- v_err_num := TO_CHAR(SQLCODE);
    -- v_err_msg := SUBSTR(SQLERRM,1,250);
    -- v_err_line := 'Oracle error (seqno=' || v_err_seq || ') ' ||
    -- v_err_num ||' occurred processing record '||
    -- TO_CHAR(v_rec_cnt + 1) ||' : '||v_err_msg;
    -- DBMS_OUTPUT.PUT_LINE(v_err_line);
    END LOOP;
    COMMIT;
    END;
    --END;
    EXIT;
    ======================================================
    many thanks to all...
    Steven

    Ive just sussed it - I had'nt put the 'v_emp' at the front of the fields from the temp table to pick then up! we continue..

  • Temp Tables - Best Practice

    Hello,
    I have a customer who uses temp tables all over their application.
    This customer is a novice and the app has its roots in VB6. We are converting it to .net
    I would really like to know the best practice for using temp tables.
    I have seen code like this in the app.
    CR2.Database.Tables.Item(1).Location = "tempdb.dbo.[##Scott_xwPaySheetDtlForN]"
    That seems to work, though i do not know why the full tempdb.dbo.[## is required.
    However, when i use this in the new report I am doing I get runtime errors.
    i also tried this
    CR2.Database.Tables.Item(1).Location = "##Scott_xwPaySheetDtlForN"
    I did not get errors, but I was returned data i did not expect.
    Before i delve into different ways to do this, i could use some help with a good pattern to use.
    thanks

    Hi Scott,
    Are you using the RDC still? It's not clear but looks like it.
    We had an API that could piggy back the HDBC handle in the RDC ( craxdrt.dll ) but that API is no longer available in .NET. Also, the RDC is not supported in .NET since .NET uses the framework and RDC is COM.
    Work around is to copy the temp data into a data set and then set location to the data set. There is no way that I know of to get to the tempdb from .NET. Reason being is there is no CR API to set the owner of the table to the user, MS SQL Server locks the tempdb to that user has exclusinve rights on it.
    Thank you
    Don

  • Global temp table and edit

    Hi all,
    Can someone tell me why when I create a GTT and insert the data like the followijng ,I get insert 14 rows msg. But when I do a select statement from sqlwork shop , sometimes i get the data sometimes I don't. my understanding is this data is supposed to stay during my logon session then got cleaned out when I exit session.
    I am developing a screen in apex and will use this temp table for user to do some editing work. Once ithe editing is done then I save the data into a static table. Can this be done ? So far my every attempt to update the temp table always result to 0 rows updated and the temp table reversed back to 0 rows. CAn you help me ?
    CREATE GLOBAL TEMPORARY TABLE "EMP_SESSION"
    (     "EMPNO" NUMBER NOT NULL ENABLE,
         "ENAME" VARCHAR2(10),
         "JOB" VARCHAR2(9),
         "MGR" NUMBER,
         "HIREDATE" DATE,
         "SAL" NUMBER,
         "COMM" NUMBER,
         "DEPTNO" NUMBER
    ) ON COMMIT PRESERVE ROWS
    insert into emp_session( EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
    select * from emp
    select * from emp_session
    -- sometimes I get 14 rows, sometimes 0 rows
    Thanks.
    Tai

    Tai,
    To say that Apex doesn't support GTT's is not quite correct. In order to understand why it is not working for you and how they may be of use in an Apex application, you have to understand the concept of a session in Apex as opposed to a conventional database session.
    In a conventional database session, as when you are connected with sqlplus then you have what is known as a dedicated session, or a synchronous connection. Temporary objects such as GTTs and packaged variables can persist across calls to the database. A session in Apex however is asynchronous by nature and a connection to the database is done through some sort of a server such as the Oracle HTTP server or the Apex Listener, which in effect maintains a pool of connections to the database and calls by your application aren't guaranteed to get the same connection for each call.
    To get over this, the guys who developed Apex came up with various methods to maintain session state and global objects that are persistent within the context of an Apex session. One of these is Apex collections, which are a device for maintaining collection like (array like) data that is persistent within an Apex session. These are Apex session specific objects in that they are local to the session that creates and maintains them.
    With this knowledge, you can then see why the GTT is not working for you and also how a GTT may be of use in an Apex application, provided you don't expect the data to persist across a call, as in a PL/SQL procedure. You should note though, that unless you are dealing with very large datasets, then a regular Oracle collection is preferable.
    I hope this explains your issue.
    Regards
    Andre

  • Global Temp Table or PL/SQL Table

    I am trying to determine if this can be done only using PL/SQL table. If not, will the usage of the global temp table affects the performance.
    Here is the situation,
    I have a data block that is based on a stored procedure. This stored procedure will return table of records from different database tables with join conditions. Some of the fields within the table of records will not have data returned from database tables. They will be the fields displayed on the form and the data will be entered by user.
    For example:
    Records will look like:
    Id          (will be populated by procedure)
    Hist_avg     (will be populated by procedure)
    My_avg     (will be used as field on the form so that user can enter their own avg)
    Cheked     (will be populated by procedure)
    My questions are:
    1.     Is this doable in form using a data block based on PL/SQL table?
    2.     Will users be able to manipulate (update) the data that based on the PL/SQL table in the memory as they wish and invoke the procedure to update the underlying table when clicking on a button (Update Avg)?
    3.     What is the advantage of using PL/SQL table and global temp table from database and form point of views?
    Any info is appreciated.

    Hi there...
    Here is the Reference...
    http://asktom.oracle.com/pls/ask/f?p=4950:8:2939484874961025998::NO::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:604830985638
    Best Regards...
    Muhammad Waseem Haroon

  • Global Temp Table Not found - SSIS

    I am facing below error while using global temp table in SSIS.
    [OLE DB Destination [78]] Error: SSIS Error Code DTS_E_OLEDBERROR.  An OLE DB error has occurred. Error code: 0x80040E37.
    An OLE DB record is available.  Source: "Microsoft SQL Server Native Client 10.0"  Hresult: 0x80040E37  Description: "Table/view either does not exist or contains errors.".
    [OLE DB Destination [78]] Error: Failed to open a fastload rowset for " ##AGENTDTLS". Check that the object exists in the database.
    [SSIS.Pipeline] Error: component "OLE DB Destination" (78) failed the pre-execute phase and returned error code 0xC0202040.
    1) For data connection manager - Retain same connection is set to True
    2) Data Flow task - Delay Validation is set to True
    3) Destination Task - Using Temp Table - ValidateExternalMetadata is set to false.
    4) I am just using one data connection.
    5) before using the temp file I am checking if its exits and if yes drp it first and create it.
    Not able to understand the reason for failure.

    Why don't you use permanent table in tempdb?
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

Maybe you are looking for

  • POST is not working in IE11, GET works.

    Hi, There is a problem while execution of POST function using XMLHttpRequest, the same code works fine in IE8, here is the code. if (window.XMLHttpRequest !== undefined) {// code for IE7+, Firefox, Chrome, Opera, Safari var httpOb=new XMLHttpRequest(

  • I added PS CC 2014 and it consistently crashes.

    I have updated all video drivers. Win 8.1 - 64 bit, Dell Inspiron 15R, Intel i7-4500, 16 GB RAM I am unable to get into Photoshop CC 2014.  Every time I try to open it, I get a message that Adobe Photoshop CC 2014 has quit working and that Windows is

  • Query users by login name

    Hello, is it posssible, with the EDK 5.1, to search a user just with his login name ? Thanks

  • WD passport not found on MBA but on windows

    Hey, I've had a MBA and a 750gb WD my passport since august. the harddrive has worked fine till this morning when it wouldnt show up on my MBA or my brothers macbookpro, yet shows up on a windows unit?? this happened just after a software update to 1

  • Attribute SID Table  of  MD that filled by ABAP

    Hi expert ! i filled the value of the master data by ABAP code . (the MD include 2 navigation objects). Actually, i filled the p_table. (master data table). the problem is that ' the X_Table (Sid attr. table) didn't updated.  Do you know what should