views:

1004

answers:

2

I am working with MSSQL (I am a MSSQL noob) and trying to alter a table. I want to CREATE TABLE LIKE to safely store data while I drop keys and constraints and all the other rigamorole that MSSQL seems to require when altering on the original table but I have not been able to find a match to that command...

+4  A: 

You can do

SELECT * INTO #MyTable_tmp FROM MyTable

Then modify your MyTable, and copy your data back in. Other approaches I've seen is to create a new table call it Mytable_Tmp (Not a temp table), which will be your new table.

Then copy your data doing any migrations you need. Then you will drop the original table and do a rename on Mytable.

Or you can get one of the many excellant tools that compare databases and generate difference scripts or VSTS DB Edition (Comes with developer) and you can do a diff script from a project file to a DB.

Edit

When you run SELECT * INTO #MyTable FROM MyTable, SQL Server creates a new temporary table called #MyTable that matches each column and data type from your select clause. In this case we are selecting * so it will match MyTable. This only creates the columns it doesn't copy defaults, constraints indexes or anything else.

JoshBerke
My question isn't how to put data into an already existing temp table. I am more concerned about creating a temp table that matches the existing table. I have dozens of tables I need to alter and I don't want to have to create the temp tables by hand.
Ichorus
Ahh! Very good! Thank you!
Ichorus
A: 

you want to recreate the same structure?

how about this

 SELECT *
 into test
 FROM myRealTable
 where 0=1

no data will be inserted into the new table

Fredou
SELECT top 0 * into test FROM myRealTable, will also achieve the same result
Kev Riley