Skip to content Skip to sidebar Skip to footer

Sql Server Copying Tables From One Database To Another

I have two databases, one is called Natalie_playground and one is called LiveDB. Since I want to practice insert, update things, I want to copy some of the tables from the LiveDB t

Solution 1:

Assuming that you have two databases, for example A and B:

  • If target table not exists, the following script will create (I do not recommend this way):

    SELECT table_A.FIELD_1, table_A.FIELD_2,......, table_A.FIELD_N 
    INTO COPY_TABLE_HERE 
    FROM  A.dbo.table_from_A table_A
    
  • If target table exists, then:

    INSERTINTO TABLE_TARGET 
     SELECT table_A.FIELD_1, table_A.FIELD_2,......, table_A.FIELD_N 
     FROM  A.dbo.table_from_A table_A
    

Note: if you want learn and practice this, you can use previous scripts, but if you want copy the complete structure and data from database to another, you should use, "Backup and restore Database" or, "Generate Script Database with data" and run this into another database.

Solution 2:

Right click on your database -> under Tasks choose Generate scripts, follow the wizard, choose your tables and check the check box that says 'script table data' (or similar) generate it to an SQL script and execute it on your other DB.

Solution 3:

You can also try SQL Server Import/Export wizard. If target tables do not exist already they will be created when you run the wizard.

Check out MSDN for more details http://msdn.microsoft.com/en-us/library/ms141209.aspx

Solution 4:

I found an easy way from other blog. Hope this might be helpful.

Select*into DestinationDB.dbo.tableName from SourceDB.dbo.SourceTable  

http://www.codeproject.com/Tips/664327/Copy-Table-Schema-and-Data-From-One-Database-to-An

Solution 5:

Try this:

If target table is exists :

SELECT SourceTableAlias.*INTO TargetDB.dbo.TargetTable
FROM  SourceDB.dbo.SourceTable SourceTableAlias

And if target table is not exists :

INSERTINTO TargetDB.dbo.TargetTable 
 SELECT SourceTableAlias.*FROM SourceDB.dbo.SourceTable SourceTableAlias

Good Luck!

Post a Comment for "Sql Server Copying Tables From One Database To Another"