SQL Server の一括コピー操作を実行する最も簡単な方法は、データベースに対して単一操作を実行することです。 既定では、一括コピー操作は分離された操作として実行されます。このコピー操作は非トランザクション方式で処理され、ロールバックできません。
Note
エラーの発生時に、バルク コピー処理の全部または一部をロールバックする必要がある場合は、SqlBulkCopy が管理するトランザクションを使用するか、または既存のトランザクション内でバルク コピー操作を実行できます。 SqlBulkCopy は、System.Transactions トランザクションに (明示的または暗黙的に) 接続が参加している場合は も使用します。
詳細については、「トランザクションと一括コピー操作」を参照してください。
通常、バルク コピー操作の実行手順は次のようになります。
コピー元のサーバーに接続し、コピーするデータを取得します。 IDataReader オブジェクトまたは DataTable オブジェクトからデータを取得できる場合は、他のソースから取得する場合もあります。
コピー先のサーバーに接続します (SqlBulkCopy を使用して接続を確立しない場合)。
SqlBulkCopy オブジェクトを作成し、必要なプロパティを設定します。
バルク挿入操作の対象となるテーブルが示されるように DestinationTableName プロパティを設定します。
WriteToServer メソッドのいずれかを呼び出します。
オプションとして、プロパティを更新したり、必要に応じて WriteToServer をもう一度呼び出したりします。
Close を呼び出すか、一括コピー操作を
Usingステートメント内にラップします。
注意事項
コピー元とコピー先の列のデータ型を一致させることをお勧めします。 データ型が一致していない場合、SqlBulkCopy は、Value によって採用されている規則を使用して、コピー元の値をコピー先のデータ型にそれぞれ変換しようとします。 この変換はパフォーマンスに影響を及ぼし、予期しないエラーが発生することもあります。 たとえば、Double データ型は、多くの場合 Decimal データ型に変換されますが、常にというわけではありません。
例
次のコンソール アプリケーションは、SqlBulkCopy クラスを使用してデータを読み込む方法を示しています。 この例では、SqlDataReader を使用し、SQL Server の AdventureWorks データベースに格納された Production.Product テーブルのデータを、同じデータベース内の同等のテーブルにコピーします。
重要
このサンプルは、「一括コピーのセットアップ例」で説明しているように作業テーブルを作成して取得してからでないと動作しません。 このコードでは、SqlBulkCopy だけを使用した構文について説明します。 コピー元およびコピー先のテーブルが同一の SQL Server インスタンス内に存在する場合、Transact-SQL INSERT ... SELECT ステートメントを使用すれば簡単かつ高速にデータをコピーすることができます。
using Microsoft.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = GetConnectionString();
// Open a sourceConnection to the AdventureWorks database.
using (SqlConnection sourceConnection =
new SqlConnection(connectionString))
{
sourceConnection.Open();
// Perform an initial count on the destination table.
SqlCommand commandRowCount = new SqlCommand(
"SELECT COUNT(*) FROM " +
"dbo.BulkCopyDemoMatchingColumns;",
sourceConnection);
long countStart = System.Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count = {0}", countStart);
// Get data from the source table as a SqlDataReader.
SqlCommand commandSourceData = new SqlCommand(
"SELECT ProductID, Name, " +
"ProductNumber " +
"FROM Production.Product;", sourceConnection);
SqlDataReader reader =
commandSourceData.ExecuteReader();
// Open the destination connection. In the real world you would
// not use SqlBulkCopy to move data from one table to the other
// in the same database. This is for demonstration purposes only.
using (SqlConnection destinationConnection =
new SqlConnection(connectionString))
{
destinationConnection.Open();
// Set up the bulk copy object.
// Note that the column positions in the source
// data reader match the column positions in
// the destination table so there is no need to
// map columns.
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(destinationConnection))
{
bulkCopy.DestinationTableName =
"dbo.BulkCopyDemoMatchingColumns";
try
{
// Write from the source to the destination.
bulkCopy.WriteToServer(reader);
// Print the number of rows processed using the
// RowsCopied property.
Console.WriteLine("{0} rows were processed.",
bulkCopy.RowsCopied);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
// Close the SqlDataReader. The SqlBulkCopy
// object is automatically closed at the end
// of the using block.
reader.Close();
}
}
// Perform a final count on the destination
// table to see how many rows were added.
long countEnd = System.Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine("Ending row count = {0}", countEnd);
Console.WriteLine("{0} rows were added.", countEnd - countStart);
Console.WriteLine("Press Enter to finish.");
Console.ReadLine();
}
}
}
private static string GetConnectionString()
// To avoid storing the sourceConnection string in your code,
// you can retrieve it from a configuration file.
{
return "Data Source=(local); " +
" Integrated Security=true;" +
"Initial Catalog=AdventureWorks;";
}
}
transact-SQL とコマンド クラスを使用した一括コピー操作の実行
次の例では、BULK INSERT ステートメントを実行する ExecuteNonQuery メソッドの使用方法を説明します。
Note
データ ソースのファイル パスはサーバーに対する相対パスです。 サーバー プロセスがこのパスにアクセスできないと、バルク コピー操作は失敗します。
using (SqlConnection connection = New SqlConnection(connectionString))
{
string queryString = "BULK INSERT Northwind.dbo.[Order Details] " +
"FROM 'f:\mydata\data.tbl' " +
"WITH ( FORMATFILE='f:\mydata\data.fmt' )";
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
command.ExecuteNonQuery();
}