Question

I am working with SQL Server (I am a SQL Server 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 SQL Server seems to require when altering on the original table but I have not been able to find a match to that command...

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top