Wednesday, December 26, 2007

How to copy bulk data from any data source to SQL Server

You can use System.Data.SqlClient.SqlBulkCopy .NET component to load data from any data source to sql server directly without using any intermediate file or in memory object. However, there should be a datareader .NET component supporting data source. Here is an example to load data from oracle (from table TABLEORA) to sql server (into table TABLESQL):

OracleConnection myConn;
SqlConnection dest = new SqlConnection("Data Source...");
myConn = new OracleConnection("...");
try
{
myConn.Open();
dest.Open();
OracleCommand sourceCommand = new OracleCommand(
"select ... from TABLEORA ... ", myConn);

// Use bulk copy to copy data to sql server
SqlBulkCopy s = new SqlBulkCopy(dest);
s.BulkCopyTimeout = 3600;
using (OracleDataReader dr = sourceCommand.ExecuteReader())
{
using (s)
{
s.DestinationTableName = "TABLESQL";
s.WriteToServer(dr);
s.Close();
}
}
myConn.Close();
}
catch (Exception e)
{
....
}

No comments: