一括コピー操作の順序のヒント
適用対象: .NET Framework .NET .NET Standard
一括コピー操作を使用すると、SQL Server テーブルにデータを読み込む他の方法よりも、パフォーマンスが大幅に向上します。 順序のヒントを使用すると、パフォーマンスをさらに向上させることができます。 一括コピー操作に順序のヒントを指定すると、並べ替えられたデータをクラスター化インデックスを持つテーブルに挿入する時間を短縮することができます。
既定では、一括挿入操作では、受信データが並べ替えられていないことを前提に実行されます。 SQL Server では、このデータを一括読み込みする前に、データが強制的に並べ替えられます。 受信データが既に並べ替えられていることがわかっている場合は、順序のヒントを使用して、クラスター化インデックスの一部である任意のターゲット列の並べ替え順序について、一括コピー操作に指示できます。
一括コピー操作への順序のヒントの追加
次の例では、AdventureWorks サンプル データベースのソース テーブルから、同じデータベース内のコピー先テーブルにデータを一括コピーします。
コピー先テーブルの ProductNumber 列の並べ替え順序を定義するための SqlBulkCopyColumnOrderHint オブジェクトが作成されます。 次に、順序のヒントが SqlBulkCopy インスタンスに追加されます。これにより、結果の INSERT BULK
クエリに適切な順序のヒント引数が追加されます。
using System;
using System.Data;
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();
// Set up the bulk copy object.
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(connectionString))
{
bulkCopy.DestinationTableName =
"dbo.BulkCopyDemoMatchingColumns";
// Setup an order hint for the ProductNumber column.
SqlBulkCopyColumnOrderHint hintNumber =
new SqlBulkCopyColumnOrderHint("ProductNumber", SortOrder.Ascending);
bulkCopy.ColumnOrderHints.Add(hintNumber);
// Write from the source to the destination.
try
{
bulkCopy.WriteToServer(reader);
}
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;";
}
}