Recreate table and contents with T-SQL

Posted on 2011-10-04
Last Modified: 2012-05-12
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.
Question by:Blowfelt82
    LVL 39

    Accepted Solution

    try the procedure like this

    CREATE PROCEDURE Copy_data_Drop
    @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)
    LVL 19

    Assisted Solution

    by:Bhavesh Shah

    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
    LVL 9

    Expert Comment

    Try this.

    RecrateTable store procedure which takes table name as input
    and uses CreatTable function to create table with constraints

    Author Closing Comment


    Featured Post

    PRTG Network Monitor: Intuitive Network Monitoring

    Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

    Join & Write a Comment

    Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
    For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
    Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
    Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

    734 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    21 Experts available now in Live!

    Get 1:1 Help Now