Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy tables with data to another database in SQL Server 2008

I have to copy the tables with data from one database to another using Query. I know how to copy tables with data within a database. But I was not sure about how to do the same for copying between two databases.

I have to copy huge number of tables, so I need any fast method using query...

Anybody please help out...Thanks in advance...

like image 316
prabu R Avatar asked Dec 28 '12 06:12

prabu R


People also ask

How do I copy a table data from one database to another in SQL Server?

Right-click on the database name, then select "Tasks" > "Export data..." from the object explorer. The SQL Server Import/Export wizard opens; click on "Next". Provide authentication and select the source from which you want to copy the data; click "Next". Specify where to copy the data to; click on "Next".

How do I copy a table to another database?

Right-click the table you want to copy in Database Explorer and select Duplicate Object.

How do you duplicate a table with data in SQL?

Use SQL Server Management StudioIn Object Explorer, right-click Tables and select New Table. In Object Explorer right-click the table you want to copy and select Design. Select the columns in the existing table and, from the Edit menu, select Copy.


3 Answers

You can use the same way to copy the tables within one database, the SELECT INTO but use a fully qualified tables names database.schema.object_name instead like so:

USE TheOtherDB;

SELECT *
INTO NewTable
FROM TheFirstDB.Schemaname.OldTable

This will create a new table Newtable in the database TheOtherDB from the table OldTable whih belongs to the databaseTheFirstDB

like image 57
Mahmoud Gamal Avatar answered Oct 29 '22 21:10

Mahmoud Gamal


  1. Right click on the database, select tasks and click on Generate Scripts.
  2. In the resultant pop-up, choose options as required (click advanced), to drop and create table, drop if exists, etc.
  3. Scroll down and choose "Schema and Data" or "Data Only" or "Types of data to script (2008 R2)"as required.
  4. Save to file and execute on the destination DB.

Advantages -

  • Can be executed against the destination DB, even if it is on another server / instance
  • Quickly script multiple tables, with data as needed

Warning - Might take quite a while to script, if the tables contain a large amount of data.

Rajan

like image 23
Raj Avatar answered Oct 29 '22 23:10

Raj


INSERT INTO DB2.dbo.MyOtherTable (Col0, Col1)
SELECT Col0, Col1 FROM DB1.dbo.MyTable

Both table column's must have same data types..

like image 40
Adeel Ahmed Avatar answered Oct 29 '22 21:10

Adeel Ahmed