title: Temp Tables need Unique Index Names
body: <p>I'm working on updating a legacy stored procedure (which calls several other child stored procedures.)  Within a transaction, it manipulates data in about a dozen or so tables and performs lots of calculations in the process, sometimes triggering lock escalation up to a table lock.  This process could take 20 minutes or more to complete in some cases. Obviously, locking tables for that long is a big no no.  So I'm working on a 2-stage plan to the reduce the blocking caused by this sproc in phase 1 and completely rewrite it to be more efficient and not take an inordinate amount of time in phase 2.</p>
  
  <p>In order to reduce the blocking, wherever there is manipulation on the database tables, I plan to move that manipulation into a temporary table.  By doing all of the work in temporary table and then updating the real tables with the final results at the very end of the process, I should be able to reduce the time spent blocking other users, significantly.  (That's the "quick fix" for phase 1.)</p>
  
  <p>Here's my issue:  some of these temp table might have 100,000 rows or more in them while I use them for various calculations.  Because of this I would like to generate indexes on the temp tables to keep performance up.  And since these are temp tables that are created within a stored procedure, they need to have unique names to avoid errors if multiple users execute the sproc at the same time.  I know that I can manually declare the temp tables using CREATE TABLE statements, and if I do that I can specify an index without a name and let SQL Server create the name for me.  What I'm hoping to be able to do is use SELECT * INTO to generate the temp table and find another way to get SQL Server to auto-generate index names.  I'm sure you're asking "Why?"  My company has several changes in store for the system that I'm working with.  If I can manage to use the SELECT INTO method, then, if a column gets added or resized or whatever, then there won't be an issue with the developers needing to know that they have to go back into these stored procedures and change their temp table definitions to match.  Using SELECT INTO will automatically keep the temp tables matching the layout of the "real" tables.</p>
  
  <p>So, does anyone know of a way to get SQL Server to auto-generate the name for an index on a temp table (aside from doing it as part of the CREATE TABLE syntax)?</p>
  
  <p>Thank you!</p>