Recreate table and contents with T-SQL

I need to copy a tables contents to a temporary table and then drop, recreate and repopulate the original table. I need to do this for a lot of tables so a generic solution would be ideal i.e. one where I only have to edit the table name.
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Pratima PharandeCommented:
try the procedure like this

@TableName VarChar

DECLARE @sql varchar(2000)
DECLARE @temptable varchar(50)

Set @temptable = 'tmp' + @TableName

SET @sql = 'SELECT * INTO ' + @temptable + ' from ' + @TableName

EXEC (@sql)

SET @sql = 'Drop table '  + @TableName

EXEC (@sql)

SET @sql = 'SELECT * INTO ' + @TableName + ' from ' + @temptable

EXEC (@sql)

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Bhavesh ShahLead AnalysistCommented:

If you wanted to re-create same table with same table design then Pratima showed you right way.
but between, why you wanted to do that?
secondly, It wont create any keys (Primary & Foreign Keys)

whats your exact requirement?

- Bhavesh
Try this.

RecrateTable store procedure which takes table name as input
and uses CreatTable function to create table with constraints
Blowfelt82Author Commented:
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.