DataTable.Merge メソッド

定義

指定した DataTable を現在の DataTableにマージします。

オーバーロード

名前 説明
Merge(DataTable, Boolean, MissingSchemaAction)

指定した DataTable を現在の DataTableにマージし、変更を保持するかどうか、および現在の DataTableで不足しているスキーマを処理する方法を示します。

Merge(DataTable, Boolean)

指定した DataTable を現在の DataTableにマージし、現在の DataTableの変更を保持するかどうかを示します。

Merge(DataTable)

指定した DataTable を現在の DataTableにマージします。

次のコンソール アプリケーションは、missingSchemaAction メソッドの Merge パラメーターの動作を示しています。 この例では、同じテーブルの 2 つのバージョンを作成し、2 番目のバージョンのスキーマを変更します。 その後、コードは 2 番目のテーブルを最初のテーブルにマージしようとします。

Note

この例では、オーバーロードされたバージョンの Merge の 1 つを使用する方法を示します。 使用可能なその他の例については、個々のオーバーロードに関するトピックを参照してください。

private static void DemonstrateMergeTable()
{
    DataTable table1 = new DataTable("Items");

    // Add columns
    DataColumn idColumn = new DataColumn("id", typeof(System.Int32));
    DataColumn itemColumn = new DataColumn("item", typeof(System.Int32));
    table1.Columns.Add(idColumn);
    table1.Columns.Add(itemColumn);

    // Set the primary key column.
    table1.PrimaryKey = new DataColumn[] { idColumn };

    // Add RowChanged event handler for the table.
    table1.RowChanged += new
        System.Data.DataRowChangeEventHandler(Row_Changed);

    // Add ten rows.
    DataRow row;
    for (int i = 0; i <= 9; i++)
    {
        row = table1.NewRow();
        row["id"] = i;
        row["item"] = i;
        table1.Rows.Add(row);
    }

    // Accept changes.
    table1.AcceptChanges();
    PrintValues(table1, "Original values");

    // Create a second DataTable identical to the first.
    DataTable table2 = table1.Clone();

    // Add column to the second column, so that the
    // schemas no longer match.
    table2.Columns.Add("newColumn", typeof(System.String));

    // Add three rows. Note that the id column can't be the
    // same as existing rows in the original table.
    row = table2.NewRow();
    row["id"] = 14;
    row["item"] = 774;
    row["newColumn"] = "new column 1";
    table2.Rows.Add(row);

    row = table2.NewRow();
    row["id"] = 12;
    row["item"] = 555;
    row["newColumn"] = "new column 2";
    table2.Rows.Add(row);

    row = table2.NewRow();
    row["id"] = 13;
    row["item"] = 665;
    row["newColumn"] = "new column 3";
    table2.Rows.Add(row);

    // Merge table2 into the table1.
    Console.WriteLine("Merging");
    table1.Merge(table2, false, MissingSchemaAction.Add);
    PrintValues(table1, "Merged With table1, schema added");
}

private static void Row_Changed(object sender,
    DataRowChangeEventArgs e)
{
    Console.WriteLine("Row changed {0}\t{1}", e.Action,
        e.Row.ItemArray[0]);
}

private static void PrintValues(DataTable table, string label)
{
    // Display the values in the supplied DataTable:
    Console.WriteLine(label);
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn col in table.Columns)
        {
            Console.Write("\t " + row[col].ToString());
        }
        Console.WriteLine();
    }
}
Private Sub DemonstrateMergeTable()
  Dim table1 As New DataTable("Items")

  ' Add columns
  Dim idColumn As New DataColumn("id", GetType(System.Int32))
  Dim itemColumn As New DataColumn("item", GetType(System.Int32))
  table1.Columns.Add(idColumn)
  table1.Columns.Add(itemColumn)

  ' Set the primary key column.
  table1.PrimaryKey = New DataColumn() {idColumn}

  ' Add RowChanged event handler for the table.
  AddHandler table1.RowChanged, AddressOf Row_Changed

  ' Add some rows.
  Dim row As DataRow
  For i As Integer = 0 To 3
    row = table1.NewRow()
    row("id") = i
    row("item") = i
    table1.Rows.Add(row)
  Next i

  ' Accept changes.
  table1.AcceptChanges()
  PrintValues(table1, "Original values")

  ' Create a second DataTable identical to the first.
  Dim table2 As DataTable = table1.Clone()

  ' Add column to the second column, so that the 
  ' schemas no longer match.
  table2.Columns.Add("newColumn", GetType(System.String))

  ' Add three rows. Note that the id column can't be the 
  ' same as existing rows in the original table.
  row = table2.NewRow()
  row("id") = 14
  row("item") = 774
  row("newColumn") = "new column 1"
  table2.Rows.Add(row)

  row = table2.NewRow()
  row("id") = 12
  row("item") = 555
  row("newColumn") = "new column 2"
  table2.Rows.Add(row)

  row = table2.NewRow()
  row("id") = 13
  row("item") = 665
  row("newColumn") = "new column 3"
  table2.Rows.Add(row)

  ' Merge table2 into the table1.
  Console.WriteLine("Merging")
  table1.Merge(table2, False, MissingSchemaAction.Add)
  PrintValues(table1, "Merged With table1, Schema added")
End Sub

Private Sub Row_Changed(ByVal sender As Object, _
      ByVal e As DataRowChangeEventArgs)
  Console.WriteLine("Row changed {0}{1}{2}", _
    e.Action, ControlChars.Tab, e.Row.ItemArray(0))
End Sub

Private Sub PrintValues(ByVal table As DataTable, _
      ByVal label As String)
  ' Display the values in the supplied DataTable:
  Console.WriteLine(label)
  For Each row As DataRow In table.Rows
    For Each col As DataColumn In table.Columns
      Console.Write(ControlChars.Tab + " " + row(col).ToString())
    Next col
    Console.WriteLine()
  Next row
End Sub

注釈

Merge メソッドは、主に類似したスキーマを持つ 2 つの DataTable オブジェクトをマージするために使用されます。 マージは通常、データ ソースからの最新の変更を既存の DataTableに組み込むためにクライアント アプリケーションで使用されます。 これにより、クライアント アプリケーションは、データ ソースからの最新のデータを使用して更新された DataTable を持つことができます。

マージ操作では、元のテーブルとマージするテーブルのみが考慮されます。 子テーブルは影響を受けたり含めたりしません。 テーブルにリレーションシップの一部として定義された 1 つ以上の子テーブルがある場合は、各子テーブルを個別にマージする必要があります。

Merge(DataTable, Boolean, MissingSchemaAction)

ソース:
DataTable.cs
ソース:
DataTable.cs
ソース:
DataTable.cs
ソース:
DataTable.cs
ソース:
DataTable.cs

指定した DataTable を現在の DataTableにマージし、変更を保持するかどうか、および現在の DataTableで不足しているスキーマを処理する方法を示します。

public:
 void Merge(System::Data::DataTable ^ table, bool preserveChanges, System::Data::MissingSchemaAction missingSchemaAction);
public void Merge(System.Data.DataTable table, bool preserveChanges, System.Data.MissingSchemaAction missingSchemaAction);
member this.Merge : System.Data.DataTable * bool * System.Data.MissingSchemaAction -> unit
Public Sub Merge (table As DataTable, preserveChanges As Boolean, missingSchemaAction As MissingSchemaAction)

パラメーター

table
DataTable

現在のDataTableにマージするDataTable

preserveChanges
Boolean

現在の の変更を保持する場合は a0/& 。それ以外の場合は。

missingSchemaAction
MissingSchemaAction

MissingSchemaAction値の 1 つ。

次のコンソール アプリケーションは、missingSchemaAction メソッドの Merge パラメーターの動作を示しています。 この例では、同じテーブルの 2 つのバージョンを作成し、2 番目のバージョンのスキーマを変更します。 その後、コードは 2 番目のテーブルを最初のテーブルにマージしようとします。

private static void DemonstrateMergeTable()
{
    DataTable itemsTable = new DataTable("Items");

    // Add columns
    DataColumn idColumn = new DataColumn("id", typeof(System.Int32));
    DataColumn itemColumn = new DataColumn("item", typeof(System.Int32));
    itemsTable.Columns.Add(idColumn);
    itemsTable.Columns.Add(itemColumn);

    // Set the primary key column.
    itemsTable.PrimaryKey = new DataColumn[] { idColumn };

    // Add RowChanged event handler for the table.
    itemsTable.RowChanged +=
        new System.Data.DataRowChangeEventHandler(Row_Changed);

    // Add ten rows.
    DataRow row;
    for (int i = 0; i <= 9; i++)
    {
        row = itemsTable.NewRow();
        row["id"] = i;
        row["item"] = i;
        itemsTable.Rows.Add(row);
    }

    // Accept changes.
    itemsTable.AcceptChanges();
    PrintValues(itemsTable, "Original values");

    // Create a second DataTable identical to the first.
    DataTable itemsClone = itemsTable.Clone();

    // Add column to the second column, so that the
    // schemas no longer match.
    itemsClone.Columns.Add("newColumn", typeof(System.String));

    // Add three rows. Note that the id column can't be the
    // same as existing rows in the original table.
    row = itemsClone.NewRow();
    row["id"] = 14;
    row["item"] = 774;
    row["newColumn"] = "new column 1";
    itemsClone.Rows.Add(row);

    row = itemsClone.NewRow();
    row["id"] = 12;
    row["item"] = 555;
    row["newColumn"] = "new column 2";
    itemsClone.Rows.Add(row);

    row = itemsClone.NewRow();
    row["id"] = 13;
    row["item"] = 665;
    row["newColumn"] = "new column 3";
    itemsClone.Rows.Add(row);

    // Merge itemsClone into the itemsTable.
    Console.WriteLine("Merging");
    itemsTable.Merge(itemsClone, false, MissingSchemaAction.Add);
    PrintValues(itemsTable, "Merged With itemsTable, schema added");
}

private static void Row_Changed(object sender,
    DataRowChangeEventArgs e)
{
    Console.WriteLine("Row changed {0}\t{1}",
        e.Action, e.Row.ItemArray[0]);
}

private static void PrintValues(DataTable table, string label)
{
    // Display the values in the supplied DataTable:
    Console.WriteLine(label);
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn col in table.Columns)
        {
            Console.Write("\t " + row[col].ToString());
        }
        Console.WriteLine();
    }
}
Private Sub DemonstrateMergeTable()
  Dim itemsTable As New DataTable("Items")

  ' Add columns
  Dim idColumn As New DataColumn("id", GetType(System.Int32))
  Dim itemColumn As New DataColumn("item", GetType(System.Int32))
  itemsTable.Columns.Add(idColumn)
  itemsTable.Columns.Add(itemColumn)

  ' Set the primary key column.
  itemsTable.PrimaryKey = New DataColumn() {idColumn}

  ' Add RowChanged event handler for the table.
  AddHandler itemsTable.RowChanged, AddressOf Row_Changed

  ' Add some rows.
  Dim row As DataRow
  For i As Integer = 0 To 3
    row = itemsTable.NewRow()
    row("id") = i
    row("item") = i
    itemsTable.Rows.Add(row)
  Next i

  ' Accept changes.
  itemsTable.AcceptChanges()
  PrintValues(itemsTable, "Original values")

  ' Create a second DataTable identical to the first.
  Dim itemsClone As DataTable = itemsTable.Clone()

  ' Add column to the second column, so that the 
  ' schemas no longer match.
  itemsClone.Columns.Add("newColumn", GetType(System.String))

  ' Add three rows. Note that the id column can't be the 
  ' same as existing rows in the original table.
  row = itemsClone.NewRow()
  row("id") = 14
  row("item") = 774
  row("newColumn") = "new column 1"
  itemsClone.Rows.Add(row)

  row = itemsClone.NewRow()
  row("id") = 12
  row("item") = 555
  row("newColumn") = "new column 2"
  itemsClone.Rows.Add(row)

  row = itemsClone.NewRow()
  row("id") = 13
  row("item") = 665
  row("newColumn") = "new column 3"
  itemsClone.Rows.Add(row)

  ' Merge itemsClone into the itemsTable.
  Console.WriteLine("Merging")
  itemsTable.Merge(itemsClone, False, MissingSchemaAction.Add)
  PrintValues(itemsTable, "Merged With itemsTable, Schema added")
End Sub

Private Sub Row_Changed(ByVal sender As Object, _
  ByVal e As DataRowChangeEventArgs)
  Console.WriteLine("Row changed {0}{1}{2}", _
    e.Action, ControlChars.Tab, e.Row.ItemArray(0))
End Sub

Private Sub PrintValues(ByVal table As DataTable, ByVal label As String)
  ' Display the values in the supplied DataTable:
  Console.WriteLine(label)
  For Each row As DataRow In table.Rows
    For Each col As DataColumn In table.Columns
      Console.Write(ControlChars.Tab + " " + row(col).ToString())
    Next col
    Console.WriteLine()
  Next row
End Sub

注釈

Merge メソッドは、主に類似したスキーマを持つ 2 つの DataTable オブジェクトをマージするために使用されます。 マージは通常、データ ソースからの最新の変更を既存の DataTableに組み込むためにクライアント アプリケーションで使用されます。 これにより、クライアント アプリケーションは、データ ソースからの最新のデータを使用して更新された DataTable を持つことができます。

マージ操作では、元のテーブルとマージするテーブルのみが考慮されます。 子テーブルは影響を受けたり含めたりしません。 テーブルにリレーションシップの一部として定義された 1 つ以上の子テーブルがある場合は、各子テーブルを個別にマージする必要があります。

Merge メソッドは通常、変更の検証、エラーの調整、変更によるデータ ソースの更新、および既存の DataTableの更新を含む一連のプロシージャの最後に呼び出されます。

マージを実行する場合、 preserveChanges パラメーターに対して開発者が false を指定しない限り、マージ操作中にマージ前に既存のデータに加えられた変更は保持されます。 preserveChanges パラメーターが true に設定されている場合、受信値は既存の行の現在の行バージョンの既存の値を上書きしません。 preserveChanges パラメーターが false に設定されている場合、受信値は既存の行の現在の行バージョンの既存の値を上書きします。 行のバージョンの詳細については、「行の 状態と行のバージョン」を参照してください。

クライアント アプリケーションでは、通常、変更されたデータを収集して検証するボタンをユーザーがクリックして、中間層コンポーネントに送り返す必要があります。 このシナリオでは、GetChanges メソッドが最初に呼び出されます。 このメソッドは、検証とマージ用に最適化された 2 つ目の DataTable を返します。 この 2 つ目の DataTable オブジェクトには、変更された DataTable オブジェクトと DataRow オブジェクトのみが含まれるため、元の DataTableのサブセットになります。 このサブセットは一般に小さいため、このサブセットはより効率的に中間層コンポーネントに戻されます。 その後、中間層コンポーネントは、ストアド プロシージャを使用して元のデータ ソースを変更して更新します。 その後、中間層は、元のデータとデータ ソースからの最新のデータを含む新しい DataTable (元のクエリをもう一度実行) を返すか、データ ソースから変更を加えたサブセットを返すことができます。 (たとえば、データ ソースによって一意の主キー値が自動的に作成される場合、これらの値をクライアント アプリケーションに反映できます)。いずれの場合も、返された DataTable は、DataTable メソッドを使用して、クライアント アプリケーションの元の Merge にマージできます。

Merge メソッドが呼び出されると、スキーマが変更された可能性があるため、2 つのDataTable オブジェクトのスキーマが比較されます。 たとえば、企業間のシナリオでは、自動化されたプロセスによって新しい列が XML スキーマに追加されている可能性があります。 ソース DataTable に、ターゲットに存在しないスキーマ要素 (追加された DataColumn オブジェクト) が含まれている場合は、missingSchemaAction 引数を MissingSchemaAction.Addに設定することで、スキーマ要素をターゲットに追加できます。 その場合、マージされた DataTable には、追加されたスキーマとデータが含まれます。

スキーマをマージすると、データがマージされます。

新しいソース DataTable をターゲットにマージすると、DataRowStateUnchanged、または ModifiedDeleted 値を持つソース行は、同じ主キー値を持つターゲット行と照合されます。 DataRowState 値が Added のソース行は、新しいソース行と同じ主キー値を持つ新しいターゲット行と照合されます。

こちらもご覧ください

適用対象

Merge(DataTable, Boolean)

ソース:
DataTable.cs
ソース:
DataTable.cs
ソース:
DataTable.cs
ソース:
DataTable.cs
ソース:
DataTable.cs

指定した DataTable を現在の DataTableにマージし、現在の DataTableの変更を保持するかどうかを示します。

public:
 void Merge(System::Data::DataTable ^ table, bool preserveChanges);
public void Merge(System.Data.DataTable table, bool preserveChanges);
member this.Merge : System.Data.DataTable * bool -> unit
Public Sub Merge (table As DataTable, preserveChanges As Boolean)

パラメーター

table
DataTable

現在のDataTableにマージするDataTable

preserveChanges
Boolean

現在の の変更を保持する場合は a0/& 。それ以外の場合は。

次のコンソール アプリケーションは、行を含む DataTable を作成し、それらの行のデータの一部を変更し、別の DataTableからデータをマージしようとします。 この例では、 preserveChanges パラメーターのさまざまな動作を示します。


private static void DemonstrateMergeTable()
{
    // Demonstrate merging, within and without
    // preserving changes.

    // In this example, take these actions:
    // 1. Create a DataTable (table1) and fill the table with data.
    // 2. Create a copy of table1, and modify its data (modifiedTable).
    // 3. Modify data in table1.
    // 4. Make a copy of table1 (table1Copy).
    // 5. Merge the data from modifiedTable into table1 and table1Copy,
    //    showing the difference between setting the preserveChanges
    //    parameter to true and false.

    // Create a new DataTable.
    DataTable table1 = new DataTable("Items");

    // Add two columns to the table:
    DataColumn column = new DataColumn("id", typeof(System.Int32));
    column.AutoIncrement = true;
    table1.Columns.Add(column);

    column = new DataColumn("item", typeof(System.String));
    table1.Columns.Add(column);

    // Set primary key column.
    table1.PrimaryKey = new DataColumn[] { table1.Columns[0] };

    // Add some rows.
    DataRow row;
    for (int i = 0; i <= 3; i++)
    {
        row = table1.NewRow();
        row["item"] = "Item " + i;
        table1.Rows.Add(row);
    }

    // Accept changes.
    table1.AcceptChanges();
    PrintValues(table1, "Original values");

    // Using the same schema as the original table,
    // modify the data for later merge.
    DataTable modifiedTable = table1.Copy();
    foreach (DataRow rowModified in modifiedTable.Rows)
    {
        rowModified["item"] = rowModified["item"].ToString()
            + " modified";
    }
    modifiedTable.AcceptChanges();

    // Change row values, and add a new row:
    table1.Rows[0]["item"] = "new Item 0";
    table1.Rows[1]["item"] = "new Item 1";

    row = table1.NewRow();
    row["id"] = 4;
    row["item"] = "Item 4";
    table1.Rows.Add(row);

    // Get a copy of the modified data:
    DataTable table1Copy = table1.Copy();
    PrintValues(table1, "Modified and new Values");
    PrintValues(modifiedTable, "Data to be merged into table1");

    // Merge new data into the modified data.
    table1.Merge(modifiedTable, true);
    PrintValues(table1, "Merged data (preserve changes)");

    table1Copy.Merge(modifiedTable, false);
    PrintValues(table1Copy, "Merged data (don't preserve changes)");
}

private static void PrintValues(DataTable table, string label)
{
    // Display the values in the supplied DataTable:
    Console.WriteLine(label);
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn column in table.Columns)
        {
            Console.Write("\t{0}", row[column, DataRowVersion.Current]);
        }
        Console.WriteLine();
    }
}
Private Sub DemonstrateMergeTable()
  ' Demonstrate merging, within and without
  ' preserving changes.

  ' In this example, take these actions:
  ' 1. Create a DataTable (table1) and fill the table with data.
  ' 2. Create a copy of table1, and modify its data (modifiedTable).
  ' 3. Modify data in table1.
  ' 4. Make a copy of table1 (table1Copy).
  ' 5. Merge the data from modifiedTable into table1 and table1Copy, 
  '    showing the difference between setting the preserveChanges 
  '    parameter to true and false.

  ' Create a new DataTable.
  Dim table1 As New DataTable("Items")

  ' Add two columns to the table:
  Dim column As New DataColumn("id", GetType(System.Int32))
  column.AutoIncrement = True
  table1.Columns.Add(column)

  column = New DataColumn("item", GetType(System.String))
  table1.Columns.Add(column)

  ' Set primary key column.
  table1.PrimaryKey = New DataColumn() {table1.Columns(0)}

  ' Add some rows.
  Dim row As DataRow
  For i As Integer = 0 To 3
    row = table1.NewRow()
    row("item") = "Item " & i
    table1.Rows.Add(row)
  Next i

  ' Accept changes.
  table1.AcceptChanges()
  PrintValues(table1, "Original values")

  ' Using the same schema as the original table, 
  ' modify the data for later merge.
  Dim modifiedTable As DataTable = table1.Copy()
  For Each row In modifiedTable.Rows
    row("item") = row("item").ToString() & " modified"
  Next
  modifiedTable.AcceptChanges()

  ' Change row values, and add a new row:
  table1.Rows(0)("item") = "New Item 0"
  table1.Rows(1)("item") = "New Item 1"

  row = table1.NewRow()
  row("id") = 4
  row("item") = "Item 4"
  table1.Rows.Add(row)

  ' Get a copy of the modified data:
  Dim table1Copy As DataTable = table1.Copy()
  PrintValues(table1, "Modified and New Values")
  PrintValues(modifiedTable, "Data to be merged into table1")


  ' Merge new data into the modified data.
  table1.Merge(modifiedTable, True)
  PrintValues(table1, "Merged data (preserve changes)")

  table1Copy.Merge(modifiedTable, False)
  PrintValues(table1Copy, "Merged data (don't preserve changes)")

End Sub

Private Sub PrintValues(ByVal table As DataTable, _
  ByVal label As String)

  ' Display the values in the supplied DataTable:
  Console.WriteLine(label)
  For Each row As DataRow In table.Rows
    For Each column As DataColumn In table.Columns
      Console.Write("{0}{1}", ControlChars.Tab, row(column, _
          DataRowVersion.Current))
    Next column
    Console.WriteLine()
  Next row
End Sub

注釈

Merge メソッドは、主に類似したスキーマを持つ 2 つの DataTable オブジェクトをマージするために使用されます。 マージは通常、データ ソースからの最新の変更を既存の DataTableに組み込むためにクライアント アプリケーションで使用されます。 これにより、クライアント アプリケーションは、データ ソースからの最新のデータを使用して更新された DataTable を持つことができます。

マージ操作では、元のテーブルとマージするテーブルのみが考慮されます。 子テーブルは影響を受けたり含めたりしません。 テーブルにリレーションシップの一部として定義された 1 つ以上の子テーブルがある場合は、各子テーブルを個別にマージする必要があります。

Merge メソッドは通常、変更の検証、エラーの調整、変更によるデータ ソースの更新、および既存の DataTableの更新を含む一連のプロシージャの最後に呼び出されます。

マージを実行する場合、 preserveChanges パラメーターに対して開発者が false を指定しない限り、マージ操作中にマージ前に既存のデータに加えられた変更は保持されます。 preserveChanges パラメーターが true に設定されている場合、受信値は既存の行の現在の行バージョンの既存の値を上書きしません。 preserveChanges パラメーターが false に設定されている場合、受信値は既存の行の現在の行バージョンの既存の値を上書きします。 行のバージョンの詳細については、「行の 状態と行のバージョン」を参照してください。

クライアント アプリケーションでは、通常、変更されたデータを収集して検証するボタンをユーザーがクリックして、中間層コンポーネントに送り返す必要があります。 このシナリオでは、GetChanges メソッドが最初に呼び出されます。 このメソッドは、検証とマージ用に最適化された 2 つ目の DataTable を返します。 この 2 つ目の DataTable オブジェクトには、変更された DataTable オブジェクトと DataRow オブジェクトのみが含まれるため、元の DataTableのサブセットになります。 このサブセットは一般に小さいため、このサブセットはより効率的に中間層コンポーネントに戻されます。 その後、中間層コンポーネントは、ストアド プロシージャを使用して元のデータ ソースを変更して更新します。 その後、中間層は、元のデータとデータ ソースからの最新のデータを含む新しい DataTable (元のクエリをもう一度実行) を返すか、データ ソースから変更を加えたサブセットを返すことができます。 (たとえば、データ ソースによって一意の主キー値が自動的に作成される場合、これらの値をクライアント アプリケーションに反映できます)。いずれの場合も、返された DataTable は、DataTable メソッドを使用して、クライアント アプリケーションの元の Merge にマージできます。

新しいソース DataTable をターゲットにマージすると、DataRowStateUnchanged、または ModifiedDeleted 値を持つソース行は、同じ主キー値を持つターゲット行と照合されます。 DataRowState 値が Added のソース行は、新しいソース行と同じ主キー値を持つ新しいターゲット行と照合されます。

こちらもご覧ください

適用対象

Merge(DataTable)

ソース:
DataTable.cs
ソース:
DataTable.cs
ソース:
DataTable.cs
ソース:
DataTable.cs
ソース:
DataTable.cs

指定した DataTable を現在の DataTableにマージします。

public:
 void Merge(System::Data::DataTable ^ table);
public void Merge(System.Data.DataTable table);
member this.Merge : System.Data.DataTable -> unit
Public Sub Merge (table As DataTable)

パラメーター

table
DataTable

現在のDataTableにマージするDataTable

次のコンソール アプリケーションは、単純な DataTable を作成し、テーブルにデータを追加します。 次に、テーブルのコピーを作成し、コピーに行を追加します。 最後に、この例では、 Merge メソッドを呼び出して、2 番目のテーブルのデータを最初のテーブルのデータとマージします。

private static void DemonstrateMergeTable()
{
    DataTable table1 = new DataTable("Items");

    // Add columns
    DataColumn column1 = new DataColumn("id", typeof(System.Int32));
    DataColumn column2 = new DataColumn("item", typeof(System.Int32));
    table1.Columns.Add(column1);
    table1.Columns.Add(column2);

    // Set the primary key column.
    table1.PrimaryKey = new DataColumn[] { column1 };

    // Add RowChanged event handler for the table.
    table1.RowChanged +=
        new System.Data.DataRowChangeEventHandler(Row_Changed);

    // Add some rows.
    DataRow row;
    for (int i = 0; i <= 3; i++)
    {
        row = table1.NewRow();
        row["id"] = i;
        row["item"] = i;
        table1.Rows.Add(row);
    }

    // Accept changes.
    table1.AcceptChanges();
    PrintValues(table1, "Original values");

    // Create a second DataTable identical to the first.
    DataTable table2 = table1.Clone();

    // Add three rows. Note that the id column can't be the
    // same as existing rows in the original table.
    row = table2.NewRow();
    row["id"] = 14;
    row["item"] = 774;
    table2.Rows.Add(row);

    row = table2.NewRow();
    row["id"] = 12;
    row["item"] = 555;
    table2.Rows.Add(row);

    row = table2.NewRow();
    row["id"] = 13;
    row["item"] = 665;
    table2.Rows.Add(row);

    // Merge table2 into the table1.
    Console.WriteLine("Merging");
    table1.Merge(table2);
    PrintValues(table1, "Merged With table1");
}

private static void Row_Changed(object sender,
    DataRowChangeEventArgs e)
{
    Console.WriteLine("Row changed {0}\t{1}",
        e.Action, e.Row.ItemArray[0]);
}

private static void PrintValues(DataTable table, string label)
{
    // Display the values in the supplied DataTable:
    Console.WriteLine(label);
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn col in table.Columns)
        {
            Console.Write("\t " + row[col].ToString());
        }
        Console.WriteLine();
    }
}
Private Sub DemonstrateMergeTable()
  Dim table1 As New DataTable("Items")

  ' Add columns
  Dim column1 As New DataColumn("id", GetType(System.Int32))
  Dim column2 As New DataColumn("item", GetType(System.Int32))
  table1.Columns.Add(column1)
  table1.Columns.Add(column2)

  ' Set the primary key column.
  table1.PrimaryKey = New DataColumn() {column1}

  ' Add RowChanged event handler for the table.
  AddHandler table1.RowChanged, AddressOf Row_Changed

  ' Add some rows.
  Dim row As DataRow
  For i As Integer = 0 To 3
    row = table1.NewRow()
    row("id") = i
    row("item") = i
    table1.Rows.Add(row)
  Next i

  ' Accept changes.
  table1.AcceptChanges()
  PrintValues(table1, "Original values")

  ' Create a second DataTable identical to the first.
  Dim table2 As DataTable = table1.Clone()

  ' Add three rows. Note that the id column can't be the 
  ' same as existing rows in the original table.
  row = table2.NewRow()
  row("id") = 14
  row("item") = 774
  table2.Rows.Add(row)

  row = table2.NewRow()
  row("id") = 12
  row("item") = 555
  table2.Rows.Add(row)

  row = table2.NewRow()
  row("id") = 13
  row("item") = 665
  table2.Rows.Add(row)

  ' Merge table2 into the table1.
  Console.WriteLine("Merging")
  table1.Merge(table2)
  PrintValues(table1, "Merged With table1")

End Sub

Private Sub Row_Changed(ByVal sender As Object, _
  ByVal e As DataRowChangeEventArgs)
  Console.WriteLine("Row changed {0}{1}{2}", _
    e.Action, ControlChars.Tab, e.Row.ItemArray(0))
End Sub

Private Sub PrintValues(ByVal table As DataTable, _
  ByVal label As String)
  ' Display the values in the supplied DataTable:
  Console.WriteLine(label)
  For Each row As DataRow In table.Rows
    For Each col As DataColumn In table.Columns
      Console.Write(ControlChars.Tab + " " + row(col).ToString())
    Next col
    Console.WriteLine()
  Next row
End Sub

注釈

Merge メソッドは、主に類似したスキーマを持つ 2 つの DataTable オブジェクトをマージするために使用されます。 マージは通常、データ ソースからの最新の変更を既存の DataTableに組み込むためにクライアント アプリケーションで使用されます。 これにより、クライアント アプリケーションは、データ ソースからの最新のデータを使用して更新された DataTable を持つことができます。

マージ操作では、元のテーブルとマージするテーブルのみが考慮されます。 子テーブルは影響を受けたり含めたりしません。 テーブルにリレーションシップの一部として定義された 1 つ以上の子テーブルがある場合は、各子テーブルを個別にマージする必要があります。

Merge メソッドは通常、変更の検証、エラーの調整、変更によるデータ ソースの更新、および既存の DataTableの更新を含む一連のプロシージャの最後に呼び出されます。

マージを実行する場合、マージ前に既存のデータに加えられた変更は、マージ操作中に既定で保持されます。 開発者は、このメソッドの他の 2 つのオーバーロードのいずれかを呼び出し、 preserveChanges パラメーターに false 値を指定することで、この動作を変更できます。

クライアント アプリケーションでは、通常、変更されたデータを収集して検証するボタンをユーザーがクリックして、中間層コンポーネントに送り返す必要があります。 このシナリオでは、GetChanges メソッドが最初に呼び出されます。 このメソッドは、検証とマージ用に最適化された 2 つ目の DataTable を返します。 この 2 番目の DataTable オブジェクトには、変更された DataRow オブジェクトのみが含まれるため、元の DataTableのサブセットになります。 このサブセットは一般に小さいため、中間層コンポーネントに効率的に戻されます。 その後、中間層コンポーネントは、ストアド プロシージャを使用して元のデータ ソースを変更して更新します。 その後、中間層は、元のデータとデータ ソースからの最新のデータを含む新しい DataTable (元のクエリをもう一度実行) を返すか、データ ソースから変更を加えたサブセットを返すことができます。 (たとえば、データ ソースによって一意の主キー値が自動的に作成される場合、これらの値をクライアント アプリケーションに反映できます)。いずれの場合も、返された DataTable は、DataTable メソッドを使用して、クライアント アプリケーションの元の Merge にマージできます。

新しいソース DataTableをターゲットにマージすると、DataRowStateUnchanged、またはModifiedDeleted値を持つソース行は、同じ主キー値を持つターゲット行と照合されます。 DataRowState 値が Added のソース行は、新しいソース行と同じ主キー値を持つ新しいターゲット行と照合されます。

こちらもご覧ください

適用対象