DataTable.Merge DataTable.Merge DataTable.Merge DataTable.Merge Method

定義

將指定的 DataTable 與目前的 DataTable 合併。Merge the specified DataTable with the current DataTable.

多載

Merge(DataTable, Boolean, MissingSchemaAction) Merge(DataTable, Boolean, MissingSchemaAction) Merge(DataTable, Boolean, MissingSchemaAction)

合併指定的 DataTable 與目前的 DataTable,指出是否保留變更,以及如何處理目前在 DataTable 中缺少的結構描述。Merge the specified DataTable with the current DataTable, indicating whether to preserve changes and how to handle missing schema in the current DataTable.

Merge(DataTable, Boolean) Merge(DataTable, Boolean) Merge(DataTable, Boolean) Merge(DataTable, Boolean)

合併指定的 DataTable 與目前的 DataTable,指出是否保留目前 DataTable 中的變更。Merge the specified DataTable with the current DataTable, indicating whether to preserve changes in the current DataTable.

Merge(DataTable) Merge(DataTable) Merge(DataTable) Merge(DataTable)

將指定的 DataTable 與目前的 DataTable 合併。Merge the specified DataTable with the current DataTable.

範例

下列主控台應用程式會示範missingSchemaAction Merge方法之參數的行為。The following console application demonstrates the behavior of the missingSchemaAction parameter of the Merge method. 這個範例會建立相同資料表的兩個版本,並修改第二個版本的架構。This example creates two versions of the same table, modifying the schema for the second version. 然後,程式碼會嘗試將第二個數據表合併到第一個。The code then attempts to merge the second table into the first.

注意

這個範例會示範如何使用其中一個「合併」的多載版本。This example shows how to use one of the overloaded versions of Merge. 如需其他可能可用的範例,請參閱個別多載主題。For other examples that might be available, see the individual overload topics.

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

備註

方法是用來合併兩個DataTable主要具有類似架構的物件。 MergeThe Merge method is used to merge two DataTable objects that have largely similar schemas. 合併通常用於用戶端應用程式,以將資料來源中的最新變更併入現有DataTable的。A merge is typically used on a client application to incorporate the latest changes from a data source into an existing DataTable. 這可讓用戶端應用程式DataTable重新整理資料來源中的最新資料。This allows the client application to have a refreshed DataTable with the latest data from the data source.

合併作業只會將原始資料表和要合併的資料表納入考慮。The merge operation takes into account only the original table, and the table to be merged. 不會影響或包含子資料工作表。Child tables are not affected or included. 如果資料表有一或多個子資料工作表定義為關聯性的一部分,則必須個別合併每個子資料工作表。If a table has one or more child tables, defined as part of a relationship, each child table must be merged individually.

Merge(DataTable, Boolean, MissingSchemaAction) Merge(DataTable, Boolean, MissingSchemaAction) Merge(DataTable, Boolean, MissingSchemaAction)

合併指定的 DataTable 與目前的 DataTable,指出是否保留變更,以及如何處理目前在 DataTable 中缺少的結構描述。Merge the specified DataTable with the current DataTable, indicating whether to preserve changes and how to handle missing schema in the current 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

參數

table
DataTable DataTable DataTable DataTable

DataTable,要與目前的 DataTable 合併。The DataTable to be merged with the current DataTable.

preserveChanges
Boolean Boolean Boolean Boolean

若要保留目前 true 中的變更,則為 DataTable,否則為 falsetrue, to preserve changes in the current DataTable; otherwise false.

範例

下列主控台應用程式會示範missingSchemaAction Merge方法之參數的行為。The following console application demonstrates the behavior of the missingSchemaAction parameter of the Merge method. 這個範例會建立相同資料表的兩個版本,並修改第二個版本的架構。This example creates two versions of the same table, modifying the schema for the second version. 然後,程式碼會嘗試將第二個數據表合併到第一個。The code then attempts to merge the second table into the first.

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

備註

方法是用來合併兩個DataTable主要具有類似架構的物件。 MergeThe Merge method is used to merge two DataTable objects that have largely similar schemas. 合併通常用於用戶端應用程式,以將資料來源中的最新變更併入現有DataTable的。A merge is typically used on a client application to incorporate the latest changes from a data source into an existing DataTable. 這可讓用戶端應用程式DataTable重新整理資料來源中的最新資料。This allows the client application to have a refreshed DataTable with the latest data from the data source.

合併作業只會將原始資料表和要合併的資料表納入考慮。The merge operation takes into account only the original table, and the table to be merged. 不會影響或包含子資料工作表。Child tables are not affected or included. 如果資料表有一或多個子資料工作表定義為關聯性的一部分,則必須個別合併每個子資料工作表。If a table has one or more child tables, defined as part of a relationship, each child table must be merged individually.

方法通常會在一系列的程式結束時呼叫,其中包含驗證變更、調節錯誤、以變更更新資料來源,最後重新整理現有DataTable的。 MergeThe Merge method is typically called at the end of a series of procedures that involve validating changes, reconciling errors, updating the data source with the changes, and finally refreshing the existing DataTable.

執行合併時,除非開發人員針對preserveChanges參數指定 false,否則在合併作業期間會保留對現有資料所做的變更。When performing a merge, changes made to the existing data before the merge are preserved during the merge operation unless the developer specifies false for the preserveChanges parameter. 如果參數設定為true,傳入的值就不會覆寫現有資料列之目前資料列版本中現有的值。 preserveChangesIf the preserveChanges parameter is set to true, incoming values do not overwrite existing values in the Current row version of the existing row. 如果參數設定為false,傳入的值會覆寫現有資料列之目前資料列版本中現有的值。 preserveChangesIf the preserveChanges parameter is set to false, incoming values do overwrite the existing values in the Current row version of the existing row. 如需資料列版本的詳細資訊,請參閱資料列狀態和資料列版本For more information about row versions, see Row States and Row Versions.

在用戶端應用程式中,通常會有一個按鈕,使用者可以按一下它來收集已變更的資料,並在將它傳回仲介層元件之前進行驗證。In a client application, it is usual to have a single button that the user can click that gathers the changed data and validates it before sending it back to a middle tier component. 在此案例中, GetChanges會先叫用方法。In this scenario, the GetChanges method is first invoked. 該方法會傳回第DataTable二個優化的以進行驗證和合併。That method returns a second DataTable optimized for validating and merging. 第二DataTable個物件只包含DataTableDataRow變更的和物件,因此會產生原始DataTable的子集。This second DataTable object contains only the DataTable and DataRow objects that were changed, resulting in a subset of the original DataTable. 這個子集通常較小,因此這個子集會更有效率地傳回仲介層元件。This subset is generally smaller, and thus this subset is more efficiently passed back to a middle tier component. 中介層元件接著會透過預存程式,以變更來更新原始資料來源。The middle tier component then updates the original data source with the changes through stored procedures. 中介層接著可以傳回新DataTable的,其中包含原始資料和資料來源中的最新資料(藉由再次執行原始查詢),或傳回子集,其中包含從資料來源對其所做的任何變更。The middle tier can then send back either a new DataTable that includes original data and the latest data from the data source (by running the original query again), or it can send back the subset with any changes that have been made to it from the data source. (例如,如果資料來源會自動建立唯一的主鍵值,則這些值可以傳播回用戶端應用程式)。不論是哪一種情況DataTable ,傳回的都可以使用Merge方法合併回客戶DataTable端應用程式的原始。(For example, if the data source automatically creates unique primary key values, these values can be propagated back to the client application.) In either case, the returned DataTable can be merged back into the client application's original DataTable with the Merge method.

當呼叫DataTable方法時,會比較兩個物件的架構,因為架構可能已經變更。 MergeWhen the Merge method is called, the schemas of the two DataTable objects are compared, because it is possible that the schemas may have been changed. 例如,在企業對企業案例中,新的資料行可能已透過自動化程式新增至 XML 架構。For example, in a business-to-business scenario, new columns may have been added to an XML schema by an automated process. DataTable如果來源包含目標中遺漏的架構DataColumn元素(已加入的物件),則可以藉由將missingSchemaAction引數設定為MissingSchemaAction.Add,將架構專案新增至目標。If the source DataTable contains schema elements (added DataColumn objects) that are missing in the target, the schema elements can be added to the target by setting the missingSchemaAction argument to MissingSchemaAction.Add. 在此情況下,合併DataTable的會包含新增的架構和資料。In that case, the merged DataTable contains the added schema and data.

合併架構之後,會合並資料。After merging schemas, the data is merged.

將新DataTable的來源合併到目標時,任何DataRowState具有、 ModifiedDeleted值的Unchanged來源資料列都會與具有相同主鍵值的目標資料列進行比對。When merging a new source DataTable into the target, any source rows with a DataRowState value of Unchanged, Modified, or Deleted are matched to target rows with the same primary key values. DataRowState值為的Added來來源資料列會與新的目標資料列相符,其主鍵值與新的來源資料列相同。Source rows with a DataRowState value of Added are matched to new target rows with the same primary key values as the new source rows.

另請參閱

Merge(DataTable, Boolean) Merge(DataTable, Boolean) Merge(DataTable, Boolean) Merge(DataTable, Boolean)

合併指定的 DataTable 與目前的 DataTable,指出是否保留目前 DataTable 中的變更。Merge the specified DataTable with the current DataTable, indicating whether to preserve changes in the current 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 DataTable

DataTable,要與目前的 DataTable 合併。The DataTable to be merged with the current DataTable.

preserveChanges
Boolean Boolean Boolean Boolean

若要保留目前 true 中的變更,則為 DataTable,否則為 falsetrue, to preserve changes in the current DataTable; otherwise false.

範例

下列主控台應用程式會建立DataTable包含列、修改這些資料列中的部分資料,並嘗試合併不同DataTable的資料。The following console application creates a DataTable containing rows, modifies some of the data in those rows, and attempts to merge data from a different DataTable. 此範例會示範preserveChanges參數的不同行為。The example demonstrates the different behaviors for the preserveChanges parameter.


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(modifiedTable, "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(modifiedTable, "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 方法是用來合併兩個DataTable主要具有類似架構的物件。The Merge method is used to merge two DataTable objects that have largely similar schemas. 合併通常用於用戶端應用程式,以將資料來源中的最新變更併入現有DataTable的。A merge is typically used on a client application to incorporate the latest changes from a data source into an existing DataTable. 這可讓用戶端應用程式DataTable重新整理資料來源中的最新資料。This allows the client application to have a refreshed DataTable with the latest data from the data source.

合併作業只會將原始資料表和要合併的資料表納入考慮。The merge operation takes into account only the original table, and the table to be merged. 不會影響或包含子資料工作表。Child tables are not affected or included. 如果資料表有一或多個子資料工作表定義為關聯性的一部分,則必須個別合併每個子資料工作表。If a table has one or more child tables, defined as part of a relationship, each child table must be merged individually.

方法通常會在一系列的程式結束時呼叫,其中包含驗證變更、調節錯誤、以變更更新資料來源,最後重新整理現有DataTable的。 MergeThe Merge method is typically called at the end of a series of procedures that involve validating changes, reconciling errors, updating the data source with the changes, and finally refreshing the existing DataTable.

執行合併時,除非開發人員針對preserveChanges參數指定 false,否則在合併作業期間會保留對現有資料所做的變更。When performing a merge, changes made to the existing data before the merge are preserved during the merge operation unless the developer specifies false for the preserveChanges parameter. 如果參數設定為true,傳入的值就不會覆寫現有資料列之目前資料列版本中現有的值。 preserveChangesIf the preserveChanges parameter is set to true, incoming values do not overwrite existing values in the Current row version of the existing row. 如果參數設定為false,傳入的值會覆寫現有資料列之目前資料列版本中現有的值。 preserveChangesIf the preserveChanges parameter is set to false, incoming values do overwrite the existing values in the Current row version of the existing row. 如需資料列版本的詳細資訊,請參閱資料列狀態和資料列版本For more information about row versions, see Row States and Row Versions.

在用戶端應用程式中,通常會有一個按鈕,使用者可以按一下它來收集已變更的資料,並在將它傳回仲介層元件之前進行驗證。In a client application, it is usual to have a single button that the user can click that gathers the changed data and validates it before sending it back to a middle tier component. 在此案例中, GetChanges會先叫用方法。In this scenario, the GetChanges method is first invoked. 該方法會傳回第DataTable二個優化的以進行驗證和合併。That method returns a second DataTable optimized for validating and merging. 第二DataTable個物件只包含DataTableDataRow變更的和物件,因此會產生原始DataTable的子集。This second DataTable object contains only the DataTable and DataRow objects that were changed, resulting in a subset of the original DataTable. 這個子集通常較小,因此這個子集會更有效率地傳回仲介層元件。This subset is generally smaller, and thus this subset is more efficiently passed back to a middle tier component. 中介層元件接著會透過預存程式,以變更來更新原始資料來源。The middle tier component then updates the original data source with the changes through stored procedures. 中介層接著可以傳回新DataTable的,其中包含原始資料和資料來源中的最新資料(藉由再次執行原始查詢),或傳回子集,其中包含從資料來源對其所做的任何變更。The middle tier can then send back either a new DataTable that includes original data and the latest data from the data source (by running the original query again), or it can send back the subset with any changes that have been made to it from the data source. (例如,如果資料來源會自動建立唯一的主鍵值,則這些值可以傳播回用戶端應用程式)。不論是哪一種情況DataTable ,傳回的都可以使用Merge方法合併回客戶DataTable端應用程式的原始。(For example, if the data source automatically creates unique primary key values, these values can be propagated back to the client application.) In either case, the returned DataTable can be merged back into the client application's original DataTable with the Merge method.

將新DataTable的來源合併到目標時,任何DataRowState具有、 ModifiedDeleted值的Unchanged來源資料列都會與具有相同主鍵值的目標資料列進行比對。When merging a new source DataTable into the target, any source rows with a DataRowState value of Unchanged, Modified, or Deleted are matched to target rows with the same primary key values. DataRowState值為的Added來來源資料列會與新的目標資料列相符,其主鍵值與新的來源資料列相同。Source rows with a DataRowState value of Added are matched to new target rows with the same primary key values as the new source rows.

另請參閱

Merge(DataTable) Merge(DataTable) Merge(DataTable) Merge(DataTable)

將指定的 DataTable 與目前的 DataTable 合併。Merge the specified DataTable with the current 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

DataTable,要與目前的 DataTable 合併。The DataTable to be merged with the current DataTable.

範例

下列主控台應用程式會建立簡單DataTable的,並將資料新增至資料表。The following console application creates a simple DataTable and adds data to the table. 然後,此範例會建立資料表的複本,並將資料列加入至複本。The example then creates a copy of the table, adding rows to the copy. 最後,此範例會呼叫Merge方法,將第二個數據表中的資料與第一個資料表中的資料合併。Finally, the example calls the Merge method to merge the data in the second table with the data in the first table.

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 方法是用來合併兩個DataTable主要具有類似架構的物件。The Merge method is used to merge two DataTable objects that have largely similar schemas. 合併通常用於用戶端應用程式,以將資料來源中的最新變更併入現有DataTable的。A merge is typically used on a client application to incorporate the latest changes from a data source into an existing DataTable. 這可讓用戶端應用程式DataTable重新整理資料來源中的最新資料。This allows the client application to have a refreshed DataTable with the latest data from the data source.

合併作業只會將原始資料表和要合併的資料表納入考慮。The merge operation takes into account only the original table, and the table to be merged. 不會影響或包含子資料工作表。Child tables are not affected or included. 如果資料表有一或多個子資料工作表定義為關聯性的一部分,則必須個別合併每個子資料工作表。If a table has one or more child tables, defined as part of a relationship, each child table must be merged individually.

方法通常會在一系列的程式結束時呼叫,其中包含驗證變更、調節錯誤、以變更更新資料來源,最後重新整理現有DataTable的。 MergeThe Merge method is typically called at the end of a series of procedures that involve validating changes, reconciling errors, updating the data source with the changes, and finally refreshing the existing DataTable.

執行合併時,在合併作業期間預設會保留合併之前對現有資料所做的變更。When performing a merge, changes made to the existing data before the merge are preserved by default during the merge operation. 開發人員可以藉由呼叫這個方法的其他兩個多載,並為preserveChanges參數指定 false 值,來修改此行為。Developers can modify this behavior by calling one of the other two overloads for this method, and specifying a false value for the preserveChanges parameter.

在用戶端應用程式中,通常會有一個按鈕,使用者可以按一下它來收集已變更的資料,並在將它傳回仲介層元件之前進行驗證。In a client application, it is usual to have a single button that the user can click that gathers the changed data and validates it before sending it back to a middle tier component. 在此案例中, GetChanges會先叫用方法。In this scenario, the GetChanges method is first invoked. 該方法會傳回第DataTable二個優化的以進行驗證和合併。That method returns a second DataTable optimized for validating and merging. 第二DataTable個物件只包含DataRow已變更的物件,因此會產生原始DataTable的子集。This second DataTable object contains only the DataRow objects that were changed, resulting in a subset of the original DataTable. 這個子集通常較小,因此更有效率地傳回中介層元件。This subset is generally smaller and thus more efficiently passed back to a middle tier component. 中介層元件接著會透過預存程式,以變更來更新原始資料來源。The middle tier component then updates the original data source with the changes through stored procedures. 中介層接著可以傳回新DataTable的,其中包含原始資料和資料來源中的最新資料(藉由再次執行原始查詢),或傳回子集,其中包含從資料來源對其所做的任何變更。The middle tier can then send back either a new DataTable that includes original data and the latest data from the data source (by running the original query again), or it can send back the subset with any changes that have been made to it from the data source. (例如,如果資料來源會自動建立唯一的主鍵值,則這些值可以傳播回用戶端應用程式)。不論是哪一種情況DataTable ,傳回的都可以使用Merge方法合併回客戶DataTable端應用程式的原始。(For example, if the data source automatically creates unique primary key values, these values can be propagated back to the client application.) In either case, the returned DataTable can be merged back into the client application's original DataTable with the Merge method.

將新DataTable的來源合併到目標時,任何DataRowState具有、 ModifiedDeleted值的Unchanged來源資料列,都會與具有相同主鍵值的目標資料列進行比對。When merging a new source DataTable into the target, any source rows with a DataRowState value of Unchanged, Modified, or Deleted, is matched to target rows with the same primary key values. DataRowState值為的Added來來源資料列會與新的目標資料列相符,其主鍵值與新的來源資料列相同。Source rows with a DataRowState value of Added are matched to new target rows with the same primary key values as the new source rows.

另請參閱

適用於