5

I have a temp table which aggregates columns from multiple tables.

I would like to convert this temp table into a permanent table without explicit specifying the column names and their types.

Don't know if i have explained this well enough

Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
Jay Jay Jay
  • 1,970
  • 2
  • 25
  • 47
  • 1
    Seems similar to http://stackoverflow.com/questions/16683758/how-to-create-a-table-from-select-query-result-in-sql-server-2008 or http://stackoverflow.com/questions/11114441/how-to-create-table-using-select-query-in-sql-server – xQbert Dec 23 '15 at 19:12

1 Answers1

14

You can use SELECT ... INTO:

SELECT *
INTO dbo.normal_table
FROM #temp_table
-- WHERE 1 = 2;   --add if you only want table structure and not actual data

Things to check after table creation:

  • IDENTITY column and current value (may need reseeding)
  • DEFAULT values of column(if temp table has defaults, normal table needs to be ALTERed)
  • COLLATION tempdb may have different collation than your database
  • size of columns, precision and scale (VARCHAR,NVARCHAR,CHAR, DECIMAL..) if SELECT contains expressions

If temp table does not contain IDENTITY column you can add one using:

SELECT ID  = IDENTITY(INT,1,1)
     ,col1 = NULL   -- NULL by default are treated as INT so you may need casting
     ,col2 = CAST(NULL AS DECIMAL(38,10))
     ,t.*
INTO dbo.table_name
FROM #temp t
Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275