355

I have a database called foo and a database called bar. I have a table in foo called tblFoobar that I want to move (data and all) to database bar from database foo. What is the SQL statement to do this?

8 Answers 8

550

SQL Server Management Studio's "Import Data" task (right-click on the DB name, then tasks) will do most of this for you. Run it from the database you want to copy the data into.

If the tables don't exist it will create them for you, but you'll probably have to recreate any indexes and such. If the tables do exist, it will append the new data by default but you can adjust that (edit mappings) so it will delete all existing data.

I use this all the time and it works fairly well.

Sign up to request clarification or add additional context in comments.

11 Comments

i can't seem to find this option. is there something version specific here?
You can't really say it's a better answer generally. It's unusable for automation to be called from within a script for instance. BTW the author asked specifically for an "..SQL statement..". But of course it's a great answer, but not a better one ;).
The author asked to move "(data and all)"; so I hoped that this answer did that. It creates the table but does not create any keys or indexes; so not much of an improvement over the SQL answer.
yes this is correct way as mentioned here too, but identity and foreign key references are removed in the destination database, any solution ?
How did this get 508 Votes and Ryan's "Oct 11 '11 at 23:41" Answer only get 13 to date?!? Ryan's is the only answer that answer's the o.p.'s q. completely. Because it handles these scenarios (which, btw, the O.P. did NOT exclude from his q.): a) Identity (very common), b) Constraints, c) Triggers, d) Indexes, e) Permissions, d) copying Schema AND Data (Hint: the "and all" part of o.p.'s "(data and all)" implies Schema also.) and e) generates "SQL statement"'s which the o.p. specified which even if he didn't mean it literally is better to have than not.
|
228

On SQL Server? and on the same database server? Use three part naming.

INSERT INTO bar..tblFoobar( *fieldlist* ) SELECT *fieldlist* FROM foo..tblFoobar 

This just moves the data. If you want to move the table definition (and other attributes such as permissions and indexes), you'll have to do something else.

13 Comments

You will also have to separately set table permissions, I believe.
If you need to do identity inserts too, the Data Import Wizard has an option for that ^^ - referring to the other answer
@TahaRehmanSiddiqui: Because it answers the question ;) He didn't ask how to copy it between database servers. But most people looking for that answer end up here, because google gives it as first result :)
@RyanB yes, that is allowed.
@Tom OP and many people that come to this question are looking for a "SQL statement", not a tool.
|
126

This should work:

SELECT * INTO DestinationDB..MyDestinationTable FROM SourceDB..MySourceTable 

It will not copy constraints, defaults or indexes. The table created will not have a clustered index.

Alternatively you could:

INSERT INTO DestinationDB..MyDestinationTable SELECT * FROM SourceDB..MySourceTable 

If your destination table exists and is empty.

6 Comments

Is there any problem if you first copy the base table structure (fields and data) and then apply a patch script to create permissions, indexes, constraints and extended properties ?
This won't insert values for identity columns in SQL Server 2008. That's only allowed when you use a column list and IDENTITY_INSERT is ON for the destination table.
@Lucas - You are "half" right :). However, the first SQL statement copies ALL the data, including the values within the identity columns. As I said, the constraints are not created. But they can be easily scripted on the source DB and applied to destination DB once all the data is moved.
The second version (INSERT INTO...) worked for me in Oracle.
Does this work if the 2 databases are on totally different servers with different connection strings? If not how do you handle that?
|
47

If it’s one table only then all you need to do is

  • Script table definition
  • Create new table in another database
  • Update rules, indexes, permissions and such
  • Import data (several insert into examples are already shown above)

One thing you’ll have to consider is other updates such as migrating other objects in the future. Note that your source and destination tables do not have the same name. This means that you’ll also have to make changes if you dependent objects such as views, stored procedures and other.

Whit one or several objects you can go manually w/o any issues. However, when there are more than just a few updates 3rd party comparison tools come in very handy. Right now I’m using ApexSQL Diff for schema migrations but you can’t go wrong with any other tool out there.

Comments

23
  1. Script the create table in management studio, run that script in bar to create the table. (Right click table in object explorer, script table as, create to...)

  2. INSERT bar.[schema].table SELECT * FROM foo.[schema].table

1 Comment

I like this approach. Select * won't work if there is an identity column though, you'll need to explicitly list the column names. You'll also need to do SET IDENTITY_INSERT TblName ON in that case.
19

You can also use the Generate SQL Server Scripts Wizard to help guide the creation of SQL script's that can do the following:

  • copy the table schema
  • any constraints (identity, default values, etc)
  • data within the table
  • and many other options if needed

Good example workflow for SQL Server 2008 with screen shots shown here.

3 Comments

See my comments above: "How did this get 508 / 171 Votes and Ryan's "Oct 11 '11 at 23:41" Answer only get 13 to date?!? Ryan's is the only answer that answer's the o.p.'s q. completely. Because it handles these scenarios (which, btw, the O.P. did NOT exclude from his q.): a) Identity (very common), b) Constraints, c) Triggers, d) Indexes, e) Permissions, d) copying Schema AND Data (Hint: the "and all" part of o.p.'s "(data and all)" implies Schema also.) and e) generates "SQL statement"'s which the o.p. specified which even if he didn't mean it literally is better to have than not.".
Note: This Answer is only practical when # of Rows are not "excessive" (i.e. lookup / small transaction Tables) and no "large" Column values. For those, I would use Ryan's Answer just to generate the Script for the Table (incl. Column Attributes and sub-Objects) Creation, and then use David B's "Insert Into Select" Answer. For single Tables (instead of Ryan's A), you can also use SSMS, Object Explorer, Right-Click Table, Script Table as, CREATE To, but you have to 1st make sure Tools, Options, SQL Server Object Explorer, Scripting options are set as desired.
I couldn't find the Script Data option, eventually I figured out in the "Set Scripting Options" step you need to Click the Advanced Button up the top right, then at the very bottom of the General Options, there is one called "Types of data to script". Set this to "Schema and data"
9

You may go with this way: ( a general example )

insert into QualityAssuranceDB.dbo.Customers (columnA, ColumnB) Select columnA, columnB from DeveloperDB.dbo.Customers 

Also if you need to generate the column names as well to put in insert clause, use:

 select (name + ',') as TableColumns from sys.columns where object_id = object_id('YourTableName') 

Copy the result and paste into query window to represent your table column names and even this will exclude the identity column as well:

 select (name + ',') as TableColumns from sys.columns where object_id = object_id('YourTableName') and is_identity = 0 

Remember the script to copy rows will work if the databases belongs to the same location.


You can Try This.

select * into <Destination_table> from <Servername>.<DatabaseName>.dbo.<sourceTable> 

Server name is optional if both DB is in same server.

Comments

0

I give you three options:

If they are two databases on the same instance do:

SELECT * INTO My_New_Table FROM [HumanResources].[Department]; 

If they are two databases on different servers and you have linked servers do:

SELECT * INTO My_New_Table FROM [ServerName].[AdventureWorks2012].[HumanResources].[Department]; 

If they are two databases on different servers and you don't have linked servers do:

SELECT * INTO My_New_Table FROM OPENROWSET('SQLNCLI', 'Server=My_Remote_Server;Trusted_Connection=yes;', 'SELECT * FROM AdventureWorks2012.HumanResources.Department'); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.