how to make temp tables usage in sql procedure

Proposed Answer how to make temp tables usage in sql procedure

  • Friday, February 22, 2013 8:08 PM
     
     

    Hello All,

    Could you please help me out, i am in a wierd situation,


    i have a sql store procedure (about 1350 lines in it), which quries data different tables and loads data to tables (about 11 tables)

    the reason, the above procedure is generating 11 tables, i am using only 4 tables in these 11, but these 11 tables were derived internally data connected,


    so the requirement is, after execute the procedure we want to generate only 4 tables(which i need, presently using) , i need to consolidate the proc to generate only 4 tables.



    the reason why it is generating 11 tables is,  

    step1 load data to table, scrub and then apply some additionl logic then prepare table 2, then some update and union and insert to table 3 (using table 2 and table 1 and some other tables... etc it will go till 11 tables)


    can i use temp tables ? here  in proc to replace these 11 tables, so that i will have only required 3 tables in db remain all for temporary calculation, but temp tables shoun't visible after proc exec completes in db, or any other ideas please, does temp tables stay till proc execution completes or only valid for single sql statement ......


    help me here, please assist me, guide me with all open ideas

    Thanks a ton in advance

    asitti

All Replies

  • Friday, February 22, 2013 8:19 PM
    Moderator
     
     Proposed Answer
    You can use CTEs to wrap the SELECT query without using temp tables. It will be easy to write and incorporate your logic within your stored procedure without these temporary objects.
  • Friday, February 22, 2013 8:43 PM
     
     

    Thank you Li,

    does this cte' capable of handling 7 millions of rows?

    also does this cte, can i use anywhere in prod, i.e., if i create a cte at begining and inserting data into that cte in the mid proc and updates several places mean while i will use several other cte at the end can i access the first created cte,,  i mean can i use like a table anywhere in proc or do i need to create and use only after one sql statement?

    please help me li

    i greatful to you

    Kind Regards

    asiiti

  • Friday, February 22, 2013 8:47 PM
    Moderator
     
     

    >does this cte' capable of handling 7 millions of rows?

    Yes.

    The scope of CTE is a single query. You need to put the CTE-s at the beginning. You can nest CTE-s and also use them recursively.

    http://msdn.microsoft.com/en-us/library/ms190766(v=sql.105).aspx


    Kalman Toth Database & OLAP Architect
    Paperback / Kindle: Pass SQL Exam 70-461 & Job Interview: Programming SQL Server 2012


  • Friday, February 22, 2013 10:25 PM
     
     

    hi toth,

    thank you for reply,

    thank you for you nice link

    how about the #temptables  please tell me

    thanks in advance

    asitti