Using temporary tables with a ref. cursor

I want to use a temporary table to populate certain data and then return a ref cursor fetching data from the temporary table.
1. Will this approach work ?
2. Do I need to drop the temporary table ? Can I drop the table as a last statement in the stored proc (remember a ref cursor based on this table is to be returned as a out parameter).
Please help.

1. Will this approach work ?Sort of, just like it is possible to dig a trench with a spoon. It can be done, but why can't you just write a select that returns the data without storing intermediate versions of your processing somewhere.
2. Do I need to drop the temporary table ?No. and you shouldn't.
Can I drop the table as a last statement in the stored proc
(remember a ref cursor based on this table is to be returned as a out parameter).No.
If you really need to use a temporary table, it should be created one time when the application is installed, and should never be created in code.

Similar Messages

  • How can I implement the equivilent of a temporary table with "on commit delete rows"?

    hi,
    I have triggers on several tables. During a transaction, I need to gather information from all of them, and once one of the triggers has all the information, it creates some data. I Can't rely on the order of the triggers.
    In Oracle and DB2, I'm using temporary tables with "ON COMMIT DELETE ROWS" to gather the information - They fit perfectly to the situation since I don't want any information to be passed between different transactions.
    In SQL Server, there are local temporary tables and global.  Local temp tables don't work for me since apparently they get deleted at the end of the trigger. Global tables keep the data between transactions.
    I could use global tables and add some field that identifies the transaction, and in each access to these tables join by this field, but didn't find how to get some unique identifier for the transaction. @@SPID is the session, and sys.dm_tran_current_transaction
    is not accessible by the user I'm supposed to work with.
    Also with global tables, I can't just wipe data when "operation is done" since at the triggers level I cannot identify when the operation was done, transaction was committed and no other triggers are expected to fire.
    Any idea which construct I could use to acheive the above - passing information between different triggers in the same transaction, while keeping the data visible to the current transaction?
    (I saw similar questions but didn't see an adequate answer, sorry if posting something that was already asked).
    Thanks!

    This is the scenario: If changes (CRUD) happen to both TableA and TableB, then log some info to TableC. Logic looks something like this:
    Create Trigger TableA_C After Insert on TableA {
      If info in temp tables available from TableB
            Write info to TableC
       else
           Write to temp tables info from TableA
    Create Trigger TableB_C After Insert on TableB {
      If info in temp tables available from TableA
            Write info to TableC
       else
           Write to temp tables info from TableB
    So each trigger needs info from the other table, and once everything is available, info to TableC is written. Info is only from the current transaction.
    Order of the triggers is not defined. Also there's no gurantee that both triggers would fire - changes can happen only to TableA / B and in that case I don't want to write anything to TableC.
    The part that gets and sets info to temp table is implemented as temp tables with "on commit delete rows" in DB2 / Oracle.
    What do you think? As I've mentioned, I could use global temp tables with a field that would identify the transaction, but didn't find something like that in SQL Server. And, the lifespan of local temp tables is too short.

  • Getting different result while running Dashboard SP Using Temporary table?

    Hi Experts
    I am getting different result when I run my dashboard procedure I am using temporary table with "ON COMMIT PRESERVE ROWS", below is the information
    I am running my attendance dashboard procedure which will display the employee attendance status based IN and OUT punches the status like AA-full day absent, GG-Full day Present, AG-First half absent,GA-Second half absent. Now when I run the first time my procedure for first time I am getting status AA even though IN and OUT timings are correct and if run it again then it is displaying the status for same employee as GG
    I didn't understand the problem where it is effecting the status

    ChakravarthyDBA wrote:
    It is procedure which will display the employee status, back end I am storing the procedure result in Temporary table with "ON COMMIT PRESERVE ROWS", when I run the procedure first time it is showing wrong information when I run it again second time then it is showing correct information. I don't know why the status is changing.
    first time employee status is AA --Full day absent and Second time is GG--Full day present (in both cases IN and OUT timings are correct only)
    is it effecting due to temporary table?
    So, you have a GTT and you're doing "something" with it and that "something" isn't what you expect.
    I've about summed up what you've posted and given us to work with. If you have specific examples please do share. Without them we're going to be of very little use to you.
    If you aren't getting the results you expect, it stands to reason that
    1) you don't understand the outputs you are supposed to be getting
    2) you have a bug in the code developed
    Please stop and think about this, pretend you are the one trying to help out. You've been given little to no information about a system you've never seen before. You need to explain your situation as you would if you brought someone in to your shop to show them this problem you are having ... the rules don't change just because it's not face-face interaction.
    Cheers,

  • How to call a Stored Procedure with a REF CURSOR output parameter

    I am looking forward an example that call a stored function/procedure with a REF CURSOR output parameter and get the result.
    In other words, I have a stored function/procedure that execute a SELECT statement using the OCI library and then it could get the values of each column and each row.
    I put a code snippet, it have only the main thing to call a simple stored procedure and print the name of each column of the cursor, but I couldn´t to print out the values in the table that call the stored procedure.
    I understand that the next step, it is to call a OCIStmtFetch.
    How to associate the cursor with the OCIStmtFetch?
    If you need more information, only tell me.
    I am using ANSI C with HP-UX Operative System (C for HP-UX) and Oracle 10g.
    Regards.
    Antonio Garcia
    /* callOracleSP */
    #include <stdio.h>
    #include <string.h>
    #include <oci.h>
    #include <stdlib.h>
    char* pConnectChar ="server";
    char* pUsernameChar = "user";
    char* pPasswordChar = "passwd";
    char* sqlCharArray1 = "BEGIN SP_GETCITIES(:s, :c); END;";
    int retval;
    ub4 parmcnt=0;
    ub4 pos2=0;
    text *pcoln[20];
    ub4 namelen[20];
    char state_key[5];
    OCIStmt* pOciStatement;
    OCIStmt* pOciStatCursor;
    OCIError* pOciError;
    OCIEnv* pOciEnviron;
    OCIServer* pOciServer;
    OCISession* pOciSession;
    OCISvcCtx* pOciServiceContext;
    OCIBind* pOciBind[500];
    OCIParam* pOciParam;
    int main()
    retval = OCIEnvCreate(&pOciEnviron, OCI_DEFAULT, NULL, NULL, NULL, NULL,0,NULL);
    retval = OCIEnvInit(&pOciEnviron, OCI_DEFAULT, 0, NULL);
    retval = OCIHandleAlloc(pOciEnviron, (void **)&pOciError, OCI_HTYPE_ERROR, 0, NULL);
    retval = OCIHandleAlloc(pOciEnviron, (void **)&pOciServiceContext, OCI_HTYPE_SVCCTX, 0, NULL);
    retval = OCIHandleAlloc(pOciEnviron, (void **)&pOciStatement, OCI_HTYPE_STMT, 0, NULL);
    retval = OCILogon(pOciEnviron,pOciError,&pOciServiceContext,(unsigned char *)pUsernameChar,
         strlen(pUsernameChar), (unsigned char *)pPasswordChar, strlen(pPasswordChar),
                   (unsigned char *)pConnectChar,strlen(pConnectChar));
    printf("OCILogon retval=%d\n",retval);
    retval = OCIStmtPrepare(pOciStatement, pOciError, (unsigned char *)sqlCharArray1,strlen(sqlCharArray1),
         OCI_NTV_SYNTAX, OCI_DEFAULT);
    printf("StmtPrepare retval=%d\n",retval);
    retval = OCIHandleAlloc(pOciEnviron, (void **)&pOciStatCursor, OCI_HTYPE_STMT, 0, NULL);
    retval = OCIBindByPos(pOciStatement,&pOciBind[0], pOciError, (ub4) 1, (void *)&state_key,
         (sb4) sizeof(state_key), SQLT_STR, (void *) 0, (ub2 *) 0, (ub2 *)0,(ub4)0, (ub4 *)0, (ub4) OCI_DEFAULT);
    printf("BindByPos OCI_HTYPE_STMT retval=%d\n",retval);
    retval = OCIBindByPos(pOciStatement,&pOciBind[1], pOciError, (ub4) 2, (void *)&pOciStatCursor,
         (sb4) 0, SQLT_RSET, (void *) 0, (ub2 *) 0, (ub2 *)0,(ub4)0, (ub4 *)0, (ub4) OCI_DEFAULT);
    printf("BindByPos OCI_HTYPE_STMT retval=%d\n",retval);
    strcpy(state_key,"CA");
    retval = OCIStmtExecute(pOciServiceContext, pOciStatement, pOciError, (ub4)1, (ub4) 0,
         (OCISnapshot *)NULL, (OCISnapshot *)NULL, (ub4) OCI_DEFAULT);
    printf("StmtExecute retval=%d\n",retval);
    /* How to get the values of the cursor? */
    /* Get number of parameters of the Cursor */
    OCIAttrGet((void *) pOciStatCursor, (ub4)OCI_HTYPE_STMT, (void*) &parmcnt,(ub4 *) 0,
         (ub4)OCI_ATTR_PARAM_COUNT, pOciError);
    printf("\nNumber of parameters of the cursor = %d\n",parmcnt);
    for (int pos = 1; pos <= (int)parmcnt; pos++)
         OCIAttrGet((void *) pOciStatCursor, (ub4)OCI_HTYPE_STMT, (void*) &pos2,(ub4 *) 0,
              (ub4)OCI_ATTR_CURRENT_POSITION, pOciError);
         retval = OCIParamGet((void *)pOciStatCursor, (ub4)OCI_HTYPE_STMT, pOciError, (void **)&pOciParam,
              (ub4) pos );
         OCIAttrGet((void*) pOciParam, (ub4) OCI_DTYPE_PARAM,(void*) &pcoln[pos-1],(ub4 *) &namelen[pos-1],
              (ub4) OCI_ATTR_NAME,(OCIError *)pOciError );
    for (int i = 1; i <=(int)parmcnt; i++)
    printf("Column %i\tNAME = %.*s\n",i,namelen[i-1],pcoln[i-1]);
    return 0;
    This is the script that create the table, insert records and create the stored procedure
    CREATE TABLE CITIES (
         STATE_CODE     VARCHAR2(2) NULL,
         CITY_CODE      NUMBER(15,5) NULL,
         CITY_NAME      VARCHAR2(30) NULL
    INSERT INTO CITIES(STATE_CODE, CITY_CODE, CITY_NAME)
    VALUES('CA', 30, 'SAN DIEGO')
    INSERT INTO CITIES(STATE_CODE, CITY_CODE, CITY_NAME)
    VALUES('CA', 40, 'SACRAMENTO')
    INSERT INTO CITIES(STATE_CODE, CITY_CODE, CITY_NAME)
    VALUES('FL', 10, 'MIAMI')
    INSERT INTO CITIES(STATE_CODE, CITY_CODE, CITY_NAME)
    VALUES('FL', 20, 'ORLANDO')
    INSERT INTO CITIES(STATE_CODE, CITY_CODE, CITY_NAME)
    VALUES('NY', 10, 'NEW YORK')
    INSERT INTO CITIES(STATE_CODE, CITY_CODE, CITY_NAME)
    VALUES('NY', 20, 'ALBANY')
    INSERT INTO CITIES(STATE_CODE, CITY_CODE, CITY_NAME)
    VALUES('CA', 10, 'LOS ANGELES')
    INSERT INTO CITIES(STATE_CODE, CITY_CODE, CITY_NAME)
    VALUES('CA', 20, 'SAN FRANCISCO')
    CREATE OR REPLACE PACKAGE globalPkg AUTHID CURRENT_USER AS
    /* The following are T/SQL specific global variables. */
    TYPE RCT1 IS REF CURSOR;/*new weak cursor definition*/
    END globalPkg;
    CREATE OR REPLACE PROCEDURE SP_ADDCITY(
    P_STATE_CODE IN VARCHAR,
    P_CITY_CODE      IN NUMBER,
    P_CITY_NAME      IN VARCHAR2,
    P_RETURN IN OUT NUMBER)
    AS
    StoO_error INTEGER;
    StoO_selcnt INTEGER;
    StoO_rowcnt INTEGER;
    StoO_errmsg VARCHAR2(255);
         BEGIN
    StoO_rowcnt := 0;
    StoO_error := 0;
    StoO_selcnt := 0;
    P_RETURN := 0;
    INSERT INTO CITIES (STATE_CODE, CITY_CODE, CITY_NAME)
    VALUES (P_STATE_CODE, P_CITY_CODE, P_CITY_NAME);
    StoO_rowcnt := SQL%ROWCOUNT;
    EXCEPTION
    WHEN TOO_MANY_ROWS THEN
    StoO_rowcnt := 2;
    WHEN OTHERS THEN
    StoO_rowcnt := 0;
    StoO_selcnt := 0;
    StoO_error := SQLCODE;
    StoO_errmsg := SQLERRM;
              IF StoO_error != 0 THEN
    BEGIN
                   P_RETURN := 1;
         RETURN;
         END;
              END IF;
         END;
    CREATE OR REPLACE PROCEDURE SP_GETCITIES(
    STATE_KEY IN VARCHAR,
    RC1      IN OUT globalPkg.RCT1)
    AS
    StoO_error INTEGER;
    StoO_selcnt INTEGER;
    StoO_rowcnt INTEGER;
    StoO_errmsg VARCHAR2(255);
    BEGIN
    StoO_rowcnt := 0;
    StoO_error := 0;
    StoO_selcnt := 0;
    OPEN RC1 FOR
    SELECT STATE_CODE, CITY_CODE, CITY_NAME
    FROM CITIES
    WHERE STATE_CODE = STATE_KEY
    ORDER BY CITY_CODE;
    StoO_rowcnt := SQL%ROWCOUNT;
    EXCEPTION
    WHEN OTHERS THEN
    StoO_rowcnt := 0;
    StoO_error := SQLCODE;
    StoO_errmsg := SQLERRM;
         END;
    /

    Hi Mark,
    Thanks for your recommendations.
    I change the code with OCIDefineByPos, one for each parameter from cursor and then use the OCIStmtFetch.
    I don´t receive a error when call OCIDefineByPos, but when I call OCIStmtFetch receive a -1 error number.
    What is wrong with the code?
    The script is the same.
    I need your help!
    Best Regards!
    Antonio Garcia (Mexico)
    This the new code:
    #include <stdio.h>
    #include <string.h>
    #include <oci.h>
    #include <stdlib.h>
      char*   pConnectChar ="ORAC617";
      char*   pUsernameChar = "C617_005_DBO_01";
      char*   pPasswordChar = "Tempora1";
      char*   sqlCharArray1 = "BEGIN SP_GETCITIES(:s, :c); END;";
      int     retval;
      ub4 parmcnt=0;
      ub4 pos2=0;
      sb2   *c_indp;
      text *pcoln[20], *name,*name2;
      ub4 namelen[20],len;
      ub2 type,size;
      char state_key[5];
      OCIDefine        *pdef;
      OCIBind          *p_bnd;
      ub1          **c_buf;
      OCIStmt*     pOciStatement;      /* Statement handle */
      OCIStmt*     pOciStatCursor;     /* Statement handle */   
      OCIError*    pOciError;          /* Error handle */
      OCIEnv*      pOciEnviron;        /* Environment handle */
      OCIServer*   pOciServer;         /* Server handle */  
      OCISession*  pOciSession;        /* Session handle */
      OCISvcCtx*   pOciServiceContext; /* Service Context handle */
      OCIBind*     pOciBind[500];      /* Bind handle */
      OCIParam*    pOciParam;          /* Param handle */
      int OCI_Fetch(OCIStmt *p_select,OCIError *p_err, int *piOcc)
      int iOcc, rc; 
      rc=OCIStmtFetch(p_select,p_err,1,OCI_FETCH_NEXT,OCI_DEFAULT);
      printf("rc fetch %i",rc);
      if(rc==0&&piOcc!=NULL){
           printf("entro al if");
        iOcc=*piOcc;
        *piOcc=iOcc+1;
      return rc;
    int main()
    int pos,i=0,rc;
      retval = OCIEnvCreate(&pOciEnviron, OCI_DEFAULT, NULL, NULL, NULL, NULL,0,NULL);
      printf("EnvCreate retval=%d\n", retval);
      retval = OCIEnvInit(&pOciEnviron, OCI_DEFAULT, 0, NULL);
      printf("EnvInit retval=%d\n",retval);
      retval = OCIHandleAlloc(pOciEnviron, (void **)&pOciError, OCI_HTYPE_ERROR, 0, NULL);
      printf("HandleAlloc OCI_HTYPE_ERROR retval=%d\n",retval);
      retval = OCIHandleAlloc(pOciEnviron, (void **)&pOciServiceContext, OCI_HTYPE_SVCCTX, 0, NULL);
      printf("HandleAlloc OCI_HTYPE_SVCCTX retval=%d\n",retval);
      retval = OCIHandleAlloc(pOciEnviron, (void **)&pOciStatement, OCI_HTYPE_STMT, 0, NULL);
      printf("HandleAlloc OCI_HTYPE_STMT retval=%d\n",retval);
      retval = OCILogon(pOciEnviron,pOciError,&pOciServiceContext,(unsigned char *)pUsernameChar,
                  strlen(pUsernameChar), (unsigned char *)pPasswordChar, strlen(pPasswordChar),
                    (unsigned char *)pConnectChar,strlen(pConnectChar));
      printf("OCILogon retval=%d\n",retval);
      retval = OCIStmtPrepare(pOciStatement, pOciError, (unsigned char *)sqlCharArray1,strlen(sqlCharArray1),
                 OCI_NTV_SYNTAX, OCI_DEFAULT);
      printf("StmtPrepare retval=%d\n",retval);
      retval = OCIHandleAlloc(pOciEnviron, (void **)&pOciStatCursor, OCI_HTYPE_STMT, 0, NULL);
      printf("HandleAlloc OCI_HTYPE_STMT retval=%d\n",retval);
      retval = OCIBindByPos(pOciStatement,&pOciBind[0], pOciError, (ub4) 1, (void *)&state_key,
                 (sb4) sizeof(state_key), SQLT_STR, (void *) 0, (ub2 *) 0, (ub2 *)0,(ub4)0, (ub4 *)0, (ub4) OCI_DEFAULT);
      printf("BindByPos OCI_HTYPE_STMT retval=%d\n",retval);
      retval = OCIBindByPos(pOciStatement,&pOciBind[1], pOciError, (ub4) 2, (void *)&pOciStatCursor,
                 (sb4) 0, SQLT_RSET, (void *) 0, (ub2 *) 0, (ub2 *)0,(ub4)0, (ub4 *)0, (ub4) OCI_DEFAULT);
      printf("BindByPos OCI_HTYPE_STMT retval=%d\n",retval);
      strcpy(state_key,"CA");
      retval = OCIStmtExecute(pOciServiceContext, pOciStatement, pOciError, (ub4)1, (ub4) 0,
                   (OCISnapshot *)NULL, (OCISnapshot *)NULL, (ub4) OCI_DEFAULT);
      printf("StmtExecute retval=%d\n",retval);
      c_buf=(ub1 **)calloc(sizeof(ub1 *),3);
      c_indp=(sb2 *)calloc(sizeof(sb2 *),3);
      // Get number of parameters of the Cursor
      OCIAttrGet((void *) pOciStatCursor, (ub4)OCI_HTYPE_STMT, (void*) &parmcnt,(ub4 *) 0,
                  (ub4)OCI_ATTR_PARAM_COUNT, pOciError);
      printf("\nNumber of parameters of the cursor = %d\n",parmcnt);
      for (pos = 1; pos <= (int)parmcnt; pos++)
           OCIAttrGet((void *) pOciStatCursor, (ub4)OCI_HTYPE_STMT, (void*) &pos2,(ub4 *) 0,
                (ub4)OCI_ATTR_CURRENT_POSITION, pOciError);
           retval = OCIParamGet((void *)pOciStatCursor, (ub4)OCI_HTYPE_STMT, pOciError, (void **)&pOciParam,(ub4) pos );
           // Get the column name
           OCIAttrGet((void*) pOciParam, (ub4) OCI_DTYPE_PARAM,(void*) &name,(ub4 *) &len, (ub4) OCI_ATTR_NAME,(OCIError *)pOciError );
            // Get the column datatype
           OCIAttrGet((void*) pOciParam, (ub4) OCI_DTYPE_PARAM,(void*) &type,(ub4 *)0,(ub4)OCI_ATTR_DATA_TYPE,(OCIError *)pOciError);      
            // Get the column size
           OCIAttrGet((void*) pOciParam, (ub4) OCI_DTYPE_PARAM,(void*) &size,(ub4 *)0,(ub4)OCI_ATTR_DATA_SIZE,(OCIError *)pOciError);
           printf("Column %i\tNAME = %.*s \ttype %d \tsize %d\n",pos,len,name,type,size);
           // OCIDefine ByPos, one for each parameter
           // c_buf store the STATE_CODE, CITY_CODE and CITY_NAME columns from the cursor
           rc=OCIDefineByPos(pOciStatCursor,&pdef,(OCIError *)pOciError,pos,c_buf[pos-1],size+1,(ub2)type,(dvoid *)c_indp[pos-1],(ub2 *)0,(ub2 *)0,OCI_DEFAULT);     
          printf("OCIDefineByPos retval=%d\n,rc);
      // call OCIStmtFetch. In the next line, I receive the error
      rc=OCIStmtFetch(pOciStatCursor,pOciError,1,OCI_FETCH_NEXT,OCI_DEFAULT);
      printf("rc fetch %i",rc);
      return 0;
    {code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to use Temporary Table in PL-SQL

    In MySQL there is no Temporary table concept.
    So for intermediate calculation I have created a table as below
    create table SequenceTempTable
    SessionId VARCHAR(50),
    Sequence VARCHAR(500),
    CreatedDate DATE
    ) ENGINE=MEMORY;
    Whenever I invoke a SP, I load the data into SequenceTempTable using Session Id as below
    CREATE PROCEDURE `GetSequence`(
    IN Start_Date VARCHAR(25),
    IN End_Date VARCHAR(25)
    BEGIN
    SELECT UUID() INTO v_SessionId;
    INSERT INTO SequenceTempTable values (v_SessionId,'1,2,5,3',now());
    required code
    DELETE FROM SequenceTempTable WHERE SessionId = v_SessionId;
    COMMIT;
    END;
    i.e. I have created a table as temporary table (created once),
    and load the data using Session Id and once session specific intermediate computation done,
    I deleted the session specific data.
    Could you give me examples of How to use Temporary table in PL-SQL code with respect to my above example.
    Because I have gone through creating Temporary table but I stuck with use in PL-SQL. I mean to say Is there any need of creating table in advance before invoking SP.
    And one more thing as in MySQL temp table I created which is using MEMORY engine i.e. this table will always be in MEMORY so there is no need of writing data on disk.
    Regards
    Sanjeev

    Hi Sanjeev
    Read about GTT here
    http://www.oracle-base.com/articles/8i/TemporaryTables.php
    GTT always contains just session specific data. \
    In case you want to use the GTT in the same session again you can use option
    ON COMMIT PRESERVE ROWS;
    Or if it is used just once in the session use can use
    ON COMMIT DELETE ROWS;
    Do remember that for GTT the data of one session can not be accessed in other session.
    Also you can go away with Delete from GTT if not used again in same session.
    Regards
    Arun

  • Alternative way to create temporary table with better performace?

    Hi guys,
    Do you happen to a better alternative way for creating a global temporary table with better performance?
    I am creating a table and then using it in a big query but is taking a lot of time.
    Thanks for any help you can provide.

    I am not very familiar with explains plans, but I believe it is ok.
    The first query I had was repeating part of it in every subquery that is why I decided to create the temporary table. I have also tried using the WITH but it seems to take the same amount of time. I also thought of creating indexed but was told that it would work in this case.
    I have another discussion named "SQL Query Having performance issues" in this discussion I have included the query just in case you want to look at it.
    Thanks

  • Using temporary tables in stored procedures

    Suppose that I have created a temporary table in a stored procedure using an "EXECUTE IMMEDIATE" statement. When I compile the procedure, that table is not created yet, so the compiler says that the table does not exist.
    What is the way of using temporary tables in stored procedures?

    It's a good practice to avoid using DDL statements being executed from stored procedures. "Truncate Table" via dynamic SQL from stored procedure is a different story and is useful in DSS environments.
    But if you insist on "creating" tables using Dynamic SQL from Stored Procedures then you must also embed your DML statements in Dynamic SQL to avoid compilation errors.
    Example:
    Create or Replace Procedure Proc_TestDynamicSQL is
    Begin
    Execute Immediate 'Create table myTable as select * from user_tables' ;
    Execute Immediate 'Update myTable set table_name = ''Test'' ' ; --two single quotes before and after the string "Test"
    End;
    In this case, Oracle wouldn't care about the table references during compilation.

  • Using Temporary Table in SSIS

    I have a dataflow task which puts the result in a temporary table. I want to put the table result in a flat file but is not able to do that. Can anyone help?
    Here is the sql code
    use adventureworks2008r2
    declare @totalcount as float
    declare @addcount as float
    declare @citycount as float
    declare @addperct as float
    declare @cityperct as float
    declare @temp table (name varchar (40), percentage float)
    set @totalcount = (select count(*)from person.Address)
    set @addcount = (select COUNT (*)from person.Address where AddressLine2 = null)
    set @citycount = (select COUNT (*) from person.Address where City is not null )
    set @addperct = 100*(@addcount/@totalcount)
    set @cityperct = 100*(@citycount/@totalcount)
    insert into @temp
    select 'Addressline2',ROUND (@addperct,2)
    insert into @temp
    select 'City',ROUND (@CITYPERCT,2)
    SELECT * FROM @temp

    What you're using is table variable and not temporary table. It will be out of scope outside batch so you cant use it anywhere after code.
    I think if you want to use it in further tasks you should use temporary tables (# tables) after setting RetainSameConnection property to true.
    See
    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

  • Using Temporary table as a target

    when i used real target table the integration works fine but when i used temporary table i got "com.sunopsis.tools.core.exception.SnpsSimpleMessageException: CKM not selected."
    I don't know why inspite of being importing the CKM
    do any one has any idea about this?

    Hi
    I have the same problem, and uncheck the option of FLOW CONTROL = NO and still remains error "com.sunopsis.tools.core.exception.SnpsSimpleMessageException: CKM not selected" .. Do you have any idea because I still ticking wrong?
    Edited by: user2080320 on 06-oct-2008 11:44
    Edited by: user2080320 on 06-oct-2008 11:45

  • Importing function with multiple ref cursors in Stored Procedure of Oracle 12c database Using EF6

    Hi Good day!
    I can able to import function for stored procedure of oracle db and able to add the complex type and get the output but i tried to import the procedure which having two ref cursors and unable to retrieve the column information. Only able to retrieve the
    columns of first ref cursor.  Please help me to get the result of two ref cursors which acting as out parameters.

    Having to ref cursors return mutiple recordsets in an Oracle package is like haveng two resultsets return from a MS SQL Server sparc.
    The link may point you in the right direction.
    http://www.codeproject.com/Articles/675933/Returning-Multiple-Result-Sets-from-an-Entity-Fram

  • How to Use Temporary table on report builder

    Hi community!
    Well, i'm trying to build a temporary table based report in Oracle Report Builder. in "After Parameter Form Trigger" I've placed a stored procedure that populate a temporary table and I've based my report on it. The problem is Report shows no data. When i execute this procedure directly on database and i perform a select on my temporary table, it show all inserted data.
    I hope somebody can to help me because I tried many ways to build this report with my temporary table and always looks blank.

    Temporary tables are session specific.
    If particular session is closed then no data will be found on your temporary table in an another session.
    My suggestion is, on "After parameter form" trigger you directly populate the GTT without using procedure.
    Hope this will help.

  • How to Create a Temporary Table with SQL Server

    I know you can create a temporary table in SQL Server 2000, but not quite sure how to do it in CFMX 7, i.e., does the SQL go inside a <CFQUERY dbtype="query"> tag?
    I'm pulling the main set of records from an Oracle server (1st data source), but it does not contain employee names, only employee IDs.  Since I need to show the employee name along with the Emp ID, I'm then pulling a list of "current" employee names from a SQL Server (2nd data source), which is the main database on our CF server.
    I've got a QofQ that works fine, except it only matches EmpIDs that exist in both result sets.  Employees who are no longer employed, don't match, and don't display.  Since I can't do a LEFT OUTER JOIN with a QofQ, what I need to do is get the records from the Oracle server into the SQL Server.  Preferably in a temporary table.
    I was hoping if I could get those Oracle records written to a temp table on the main SQL Server, in same database as the Employee Name table, I could then write a normal <CFQUERY> that uses a LEFT OUTER JOIN.
    I think I could probably write a Stored Procedure that would execute the SQL to create the temporary table, but am trying to avoid having to write the SP, and do it the simplest way.
    This query will be a program that can be run hundreds of times per day, with a form that allows users to select date ranges, locations, and other options.  That starts the queries, which creates the report.  So I just need the temp table to exist only until all the SQL has run, and the <CFOUTPUT> has generated a report.
    If the premise is right, I just need some help with the syntax for creating a SQL Server temp table, when you want to write records to it from an external data source.  I'm trying the following, but getting an error:
    <CFQUERY name="ITE_Temp" datasource="SkynetSQL">
    CREATE TABLE #MyTemp
    (   INSERT INTO #MyTemp
    ITE2.TrueFile char (7) NOT NULL,
    ITE2.CountOfEmployee int NULL,
    ITE2.DTL_SUBTOT decimal NULL,
    ITE2.EMPTYPE char (3) NULL,
    ITE2.ARPT_CD char (3) NULL
    </CFQUERY>
    So I actually created a permanent table on the SQL Server, and wrote the below SQL, which does work, and does write the records to table.  I can then write another CFQUERY with a LEFT OUTER JOIN, and get all the records, including those that don't have matching employee name:
    <CFQUERY datasource="SkynetSQL">
    <CFLOOP index="i" from="1" to = "#ITE2.RecordCount#">
    INSERT INTO ITE_Temp
       (FullFile,
       EmployeeCount,
       DTL_Amount,
       EmployeeType,
       station)
    VALUES  ('#ITE2.TrueFile[i]#',
       #ITE2.CountOfEmployee[i]#,
       #ITE2.DTL_SUBTOT[i]#,
       '#ITE2.EMPTYPE[i]#',
       '#ITE2.ARPT_CD[i]#')
    </CFLOOP>
    </CFQUERY>
    But, I hate to have to create a table and physically write to it.  For one, it seems slower, and doing it in temp would be in memory, and probably much faster, correct?  Is there some way to code the above, so that it does something similar, but in a TEMPORARY TABLE?   If I can figure out how to do this, I can pull data from multiple data sources and servers, and using SQL Server temp tables, work with the data as if it was all on the same SQL Server, and do some cool reports.
    Everything I've done for the past few years, has all been from data from a single source, whether SQL Server, or another server.  Now I need to start writing reports where data can come from 3 or 4 different servers, and be able to do joins (inner and outer).  Thanks for any advice/help.  Much appreciated.
    Gary

    While waiting to hear back, I was able to write the query results from an outside Oracle server, to a table on the local SQL Server, and do the LEFT OUTER JOIN required for the final query and report to work.  That was with this syntax:
    <CFQUERY name="AddTableRecords" datasource="MyTable">
    TRUNCATE TABLE ITE_Temp
    <CFOUTPUT query="ITE2">
    INSERT INTO ITE_Temp
    (FullFile,EmployeeCount,DTL_Amount,EmployeeType,station)
    VALUES
    ('#TrueFile#', #CountOfEmployee#, #DTL_SUBTOT#, '#EMPTYPE#', '#ARPT_CD#')
    </CFOUTPUT>
    </CFQUERY>
    However, I was not able to write to a temporary table AND read the results. I got the syntax to run to write the above results to a temporary table.  But when I tried to read and output the results from the temp table, I got an error.  Also, it wouldn't take the single "#" (local) only the global "##" table var, using this syntax.  Note that if I didn't have the DROP TABLE in the beginning, the 2nd time you run this query, you get an error telling you the table already exists.
    <CFQUERY name="ITE_Temp2" datasource="MyTable">
    DROP TABLE ##MyTemp2
    CREATE TABLE ##MyTemp2
    FullFile char (7) NOT NULL,
    EmployeeCount int NULL,
    DTL_Amount decimal NULL,
    EmployeeType char (3) NULL,
    station char (3) NULL
    <CFOUTPUT query="ITE2">
    INSERT INTO ##MyTemp2 VALUES
    '#ITE2.TrueFile#',
    #ITE2.CountOfEmployee#,
    #ITE2.DTL_SUBTOT#,
    '#ITE2.EMPTYPE#',
    '#ITE2.ARPT_CD#'
    </CFOUTPUT>
    </CFQUERY>
    So even though the above works, I could use some help in reading/writing the output.  I've tried several things similar to below, but they don't work.  It't telling me ITE_Temp2 does not exist.  It's not easy to find good examples of creating temporary tables in SQL Server.
    <CFQUERY name="QueryTest2" datasource="SkynetSQL">
    SELECT *
    FROM ITE_Temp2
    </CFQUERY>
    <CFOUTPUT query="ITE_Temp2">
    Output from Temp Table<br>
    <p>FullFile: #FullFile#, EmployeeCount: #EmployeeCount#</p>
    </CFOUTPUT>
    Thanks for any help/advice.
    Gary.

  • How can I use external tables with directories not on Oracle host?

    Oracle 11.2.0.2
    We have developers using C# to populate global temporary tables (two one header and detail with 1 to many relationbship between these two tables). The process of using C# was blowing up memory on Windows.
    As an alternative I requested them to create two CSV files and I can use sqlldr to load the detail CSV file of over 1 million rows under 15 seconds. It came to my mind that I could use external tables for this purpose with getting read of header and trailer from the CSV files.
    The issue I have is that I am not a DBA so I do not have access to OS host that Oracle instance is running. sqlldr is a client side tool, whereas external tables are server side. I was wondering if there is an alternative in 11g to use external tables without creating directories on the OS host that Oracle runs on? Are there other alternatives?
    Thanks

    905989 wrote:
    Oracle 11.2.0.2
    We have developers using C# to populate global temporary tables (two one header and detail with 1 to many relationbship between these two tables). The process of using C# was blowing up memory on Windows.
    As an alternative I requested them to create two CSV files and I can use sqlldr to load the detail CSV file of over 1 million rows under 15 seconds. It came to my mind that I could use external tables for this purpose with getting read of header and trailer from the CSV files.
    The issue I have is that I am not a DBA so I do not have access to OS host that Oracle instance is running. sqlldr is a client side tool, whereas external tables are server side. I was wondering if there is an alternative in 11g to use external tables without creating directories on the OS host that Oracle runs on? Are there other alternatives?
    Thanks
    no other alternative

  • Creating temporary tables with JSTL

    I need to create temporary tables in my DB (MySQL), and later call it in a query.
    I try this:
    <sql:update var="temp1" dataSource="${conn}">
    CREATE TEMPORARY TABLE temp1
    SELECT data1 FROM table1 WHERE condition = 1
    </sql:update>
    <sql:query var="query1" dataSource="${conn}">
    SELECT * FROM temp1
    </sql:query>

    I haven't done enough with MySQL recently to know.
    Break your problem up into two parts.
    First there's the query portion. Create a permanent table and make sure that your query works fine with taht.
    Next is the creation of the temporary table. Once you KNOW the query is working, then you can concentrate on that.
    I'll assume that you've already GRANTed table creation permission to the user that your JSP app uses to log into the database.
    Are there any messages written to the servlet/JSP engine log file that might help you figure out what's wrong? Do you have a JSP error page that's displayed if any exceptions are thrown? - MOD

  • Filling temporary table with two other tables.

    Hi everyone,
    In an start routine, I would like to do the following :
    read values in an internal table, save it in temporary table tab1.
    read values in an internal table (the same with a different request) and save it in temporary table tab2.
    save with no duplicate keys and in a sorted table tab3 the result of the two tables.
    I have coded like this, but it doesn't work, since the final table is empty.
    Indeed, the system says it is tried to insert a duplicate key. How is it possible using instruction INSERT ?
        DATA : t_agence_1 TYPE SORTED TABLE OF ty_agence
                       WITH UNIQUE KEY /BIC/C_AGENCE2
                       WITH HEADER LINE.
        DATA : t_agence_2 TYPE SORTED TABLE OF ty_agence
                       WITH UNIQUE KEY /BIC/C_AGENCE2
                       WITH HEADER LINE.
        DATA : t_agence TYPE SORTED TABLE OF ty_agence
                       WITH UNIQUE KEY /BIC/C_AGENCE2
                       WITH HEADER LINE.
    SELECT * FROM /BIC/PC_AGENCE2
          INTO CORRESPONDING FIELDS OF TABLE t_agence_1
          FOR ALL ENTRIES IN DATA_PACKAGE
               WHERE CALMONTH = DATA_PACKAGE-CALMONTH
               AND /BIC/C_AGENCE2 = DATA_PACKAGE-/BIC/C_AG1
               AND objvers = 'A'.
         IF sy-subrc = 0.
           INSERT LINES OF t_agence_1 INTO TABLE t_agence.
         endif.
       SELECT * FROM /BIC/PC_AGENCE2
          INTO CORRESPONDING FIELDS OF TABLE t_agence_2
          FOR ALL ENTRIES IN DATA_PACKAGE
               WHERE CALMONTH = DATA_PACKAGE-CALMONTH
               AND /BIC/C_AGENCE2 = DATA_PACKAGE-/BIC/C_AG2
               AND objvers = 'A'.
       IF sy-subrc = 0.
              INSERT LINES OF t_agence_2 INTO TABLE t_agence.
       endif.
    Thanks if you can help !
    regards
    fred
    Edited by: Christophe BELIN on Dec 5, 2008 3:43 PM

    Shanon,
    You would handle the parent with two child tables exactly the same way you would a parent with one child.
    1) Bring in all 3 tables through the Database Expert.
    2) On the Links Tab, place the parent table on the left of the window and the two child tables to the right (yes there is a reason for doing this).
    3) Delete any CR generated links between the tables.
    4) "Draw" a link that starts from the parent table to the 1st child table and then again, from the parent to the 2nd child.
    a. I'm assuming that you know which fields to link on.
    b. No links between children.
    5) Once you have both links in place right click them and change the "Link Type" to "Left Outer Join"
    a. The reason for doing this: It allows ALL of the parent records to come through, even if they do not have any matching records in
    one or both of the child tables.
    Hope this helps,
    Jason

Maybe you are looking for