tags:

views:

50

answers:

3

Hello, I want to get all records from a table1 & insert them into table2. Table1 & table2 are in different databases, table1 and table2 are same structure.

Normally, I will get all records from table1, and for each record (foreach), I will insert it into table2 by using "INSERT ...". I want to know a effect way to insert all records into table only one time without foreach.

I use C#, .NET 2.0 & WinForm.

Thanks.

A: 

If both databases are hosted on the same Microsoft SQL Server, you could do a cross-database select to copy the data across without needing much code at all ...

insert into database1.dbo.table1
select *
from database2.dbo.table2

permissions are the tricky bit ...

Bevan
+4  A: 

In SQL Code you can do a SELECT in the INSERT

INSERT INTO Table2 
(Id, Name, IsActive) 
SELECT Id, Name, IsActive 
FROM Table2

Or if you are doing in Code then check out the SqlBulkCopy class

            sqlConn.Open();
            using (var bulkCopy = new SqlBulkCopy(sqlConn))
            {
                bulkCopy.DestinationTableName = "Table2";
                bulkCopy.WriteToServer(dataTable);
            }
            sqlConn.Close();
willbt
'sql code' vs 'code', hey? =) oh well, +1
David Hedlund
+1 for 2 solutions, but you forgot about identity fields in first case. It is needed to swich off identity before inserting (check David Hedlund solution).
Yauheni Sivukha
Good point, but there was nothing in the question to indicate that he/she has identity columns on these tables.
willbt
Maybe I will use the traditional way: insert by each row. Thanks.
Lu Lu
A: 

Can the two databases talk to eachother? In that case, forget about C#, and create a query that looks something like this:

use db2

SET IDENTITY_INSERT Table2 ON

INSERT INTO Table2
    SELECT * FROM db1.dbo.Table1

SET IDENTITY_INSERT Table2 OFF
David Hedlund