views:

26537

answers:

7

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?

+5  A: 

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.

David B
You will also have to separately set table permissions, I believe.
Ken Ray
Yes, and indexes... etc.
David B
After setting indexes, this is the best answer.
RyanKeeter
+5  A: 

This should work:

SELECT * 
INTO DestinationDB..MyDestinationTable 
FROM SourceDB..MySourceTable
leoinfo
It will work, but note you will not copy constraints and extended properies.
ScottStonehouse
That's true ... but you know ... my solution is as complete as the question is :)
leoinfo
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
+1  A: 
  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

ScottStonehouse
+4  A: 

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.

David
i actually think this is the better answer
littlegreen
A: 

You should try this:

Select * into foo..tblFoobar from bar..tblFoobar

You just run that command. This will work and copy all the data of Foobar data from Foo to Bar database.

David B has already answered and the answer accepted on October 9, 2008...
Liao
A: 

What if we want to copy all the data of a particular table to another table of the different DB? (we are not copying table, just values of all the table fields). How we do that?

EG: Database1>db1Table1>db1tb1Fields copy to Database2>db2Table1>db2tb1Fields

Sonam
A: 

In that case you would just do:

INSERT INTO Database2..Table1 SELECT * FROM Database1..Table1

Richard Warr