338

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?

C R
  • 2,182
  • 5
  • 32
  • 41
RyanKeeter
  • 5,939
  • 7
  • 32
  • 40

8 Answers8

544

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.

Sunil D.
  • 17,983
  • 6
  • 53
  • 65
David
  • 5,651
  • 2
  • 16
  • 4
  • 1
    i can't seem to find this option. is there something version specific here? – Abbas Gadhia Apr 20 '12 at 11:24
  • 37
    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 ;). – grizzly Nov 05 '12 at 09:35
  • 3
    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. – unubar Jan 06 '14 at 22:02
  • Is it possible to specify a `WHERE` condition using the Import Data task? I was unable to find a way to do so. – crush Jan 27 '14 at 18:45
  • I didn't have the option from within SQL Server Management Studio. I had to run the separate application named "SQL Server Import/Export Wizard" which allowed me to create a package and define origin and destination. – Justin Skiles Mar 09 '15 at 03:39
  • This is very old, but in response to @grizzly, the import can be saved off as an SSIS file for repeat usage. That may help people with workflows that support SSIS. – GregB Apr 20 '15 at 02:27
  • 1
    yes this is correct way as mentioned [here](http://www.codeproject.com/Tips/664327/Copy-Table-Schema-and-Data-From-One-Database-to-An) too, but `identity` and `foreign key` references are removed in the destination database, any solution ? – Shaiju T Nov 16 '15 at 18:35
  • This is the better answer for me as the SQL statement needlessly ran out of disk space (with what must be a fairly bone-headed implementation by SQL Server). This solution uses only enough disk space to create the new table, nothing more. – karfus Feb 14 '16 at 01:04
  • I would prefer to create the table definition that matches the source first, this is because in the event of automatically creating the table, stuff such as computed columns, default values, primary key, identity column, etc are not created. – Irawan Soetomo Aug 09 '16 at 09:15
  • 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. – Tom Jun 14 '17 at 21:50
  • Note: Ryan's "Oct 11 '11 at 23:41" 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. – Tom Jun 16 '17 at 17:42
219

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.

Sam Saffron
  • 128,308
  • 78
  • 326
  • 506
Amy B
  • 108,202
  • 21
  • 135
  • 185
  • You will also have to separately set table permissions, I believe. – Ken Ray Oct 09 '08 at 15:31
  • 1
    If you need to do identity inserts too, the Data Import Wizard has an option for that ^^ - referring to the other answer – Clarence Liu Aug 30 '13 at 04:07
  • 13
    @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 :) – Maarten Kieft Apr 11 '14 at 06:52
  • Could this be used with a WHERE statement? For example, if I only wanted to insert rows that fall within a certain date range and not the entire table. – Ryan B Jan 30 '15 at 16:29
  • 1
    @RyanB yes, that is allowed. – Amy B Jan 30 '15 at 22:33
  • This answer would be better if it showed how to copy the table definition, too. – Ahmed Dec 25 '15 at 19:36
  • My rookie mistake: Using Oracle, I get a "missing right parenthesis" error if I use parenthesis around the 2nd grouping of fields, on that `SELECT` statement. Word to the wise, don't make my mistake! Leave out the parenthesis on that 2nd grouping! :) – vapcguy Jul 19 '16 at 13:52
  • How did this get 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. – Tom Jun 14 '17 at 21:51
  • 2
    @Tom OP and many people that come to this question are looking for a "SQL statement", not a tool. – Amy B Jun 14 '17 at 22:28
  • Note: Ryan's "Oct 11 '11 at 23:41" 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. – Tom Jun 16 '17 at 17:41
  • How does this work when the 2 databases are on different servers/require different connection strings? – Alexander Ryan Baggett Aug 25 '17 at 20:06
  • Tip: In SMSS, it's possible to drag and drop the Columns "Folder" from the Object Explorer into the Query window. This avoids needing to type the field list by hand. – Brian Jan 10 '18 at 18:29
  • On Azure DB it fails with "Reference to database and/or server name is not supported in this version of SQL Server" – pqnet Aug 24 '23 at 13:09
115

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.

kometen
  • 6,536
  • 6
  • 41
  • 51
leoinfo
  • 7,860
  • 8
  • 36
  • 48
  • 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 ? – leoinfo Oct 09 '08 at 16:13
  • 4
    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 Wilson-Richter Oct 23 '12 at 04:30
  • @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. – leoinfo Oct 23 '12 at 14:43
  • The second version (`INSERT INTO...`) worked for me in Oracle. – vapcguy Jul 19 '16 at 13:48
  • Does this work if the 2 databases are on totally different servers with different connection strings? If not how do you handle that? – Alexander Ryan Baggett Aug 25 '17 at 20:07
  • Why two dots in the answer? – ABCD Jun 20 '22 at 16:32
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.

Igor Voplov
  • 973
  • 9
  • 7
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

Michał Powaga
  • 22,561
  • 8
  • 51
  • 62
ScottStonehouse
  • 24,155
  • 7
  • 32
  • 34
  • 1
    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. – JeremyWeir Jun 05 '12 at 20:36
16

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.

ryan
  • 841
  • 8
  • 12
  • 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.". – Tom Jun 14 '17 at 21:54
  • 1
    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. – Tom Jun 16 '17 at 17:45
  • 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" – Daniel Barnes Jan 05 '23 at 03:13
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.

kometen
  • 6,536
  • 6
  • 41
  • 51
NeverHopeless
  • 11,077
  • 4
  • 35
  • 56
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');
Francesco Mantovani
  • 10,216
  • 13
  • 73
  • 113