2011-08-22 78 views
1

我试图使用以下代码跨“非链接”SQL服务器更新表: C#或VB.net和ADO.net SqlDataAdapter。我需要使用DataTableSqlDataAdapter跨非连接SQL服务器的批量更新表

非常重要:我需要使用BatchUpdate并避免通过DataTable循环。

在服务器1中的表的设计从表设计的不同之处服务器2

源表:

Server 1. Table 1 
ID INT 
NAME Varchar(30) 
Date DateTime 

目标表:

Server 2. Table 2 
ID INT 
TableOneId INT (Foreign Key from Server 1. Table 1) 
NAME Varchar(30) 
Date DateTime 

我需要一个有关如何使用更新服务器2上的表2的示例或另一种批处理方法。

+0

你想避免循环DataTable或避免往返数据库? –

+0

我想使用BatchUpdate,因为性能问题是正确的。 –

+0

好的,我的代码工作吗? –

回答

1

您应该的SqlDataAdapter的UpdateBatchSize属性设置为0(无限制)。 我没有看到更新table2而没有循环table1的方法。

这里是一个示例代码向您展示实现这一目标的一种方法:

Public Sub BatchUpdate(ByVal table1 As DataTable) 
    Dim connectionStringServer2 As String = GetConnectionString() 

    Using connection As New SqlConnection(connectionStringServer2) 
     Dim adapter As New SqlDataAdapter() 

     'Set the UPDATE command and parameters' 
     adapter.UpdateCommand = New SqlCommand(_ 
      "UPDATE Table2 SET " _ 
      & "[email protected],[email protected] WHERE [email protected];", _ 
      connection) 
     adapter.UpdateCommand.Parameters.Add("@Name", _ 
      SqlDbType.NVarChar, 50, "Name") 
     adapter.UpdateCommand.Parameters.Add("@Date", _ 
      SqlDbType.DateTime, 0, "Date") 
     adapter.UpdateCommand.Parameters.Add("@TableOneId", _ 
     SqlDbType.Int, 0, "TableOneId") 
     adapter.UpdateCommand.UpdatedRowSource = _ 
      UpdateRowSource.None 

     ' Set the batch size,' 
     ' try to update all rows in a single round-trip to the server' 
     adapter.UpdateBatchSize = 0 

     Dim table2 As New DataTable("table2") 
     table2.Columns.Add(New DataColumn("Name", GetType(String))) 
     table2.Columns.Add(New DataColumn("Date", GetType(Date))) 
     table2.Columns.Add(New DataColumn("TableOneId", GetType(Int32))) 

     ' copy content from table1 to table2' 
     For Each row As DataRow In table1.Rows 
      Dim newRow = table2.NewRow 
      newRow("TableOneId") = row("ID") 
      newRow("Name") = row("Name") 
      newRow("Date") = row("Date") 
      table2.Rows.Add(newRow)  
      ' note: i have not tested following, but it might work or give you a clue' 
      newRow.AcceptChanges() 
      newRow.SetModified() 
     Next 
     ' Execute the update' 
     adapter.Update(table2) 
    End Using 
End Sub 
+0

现在正在处理它 –

+0

转到http://stackoverflow.com/questions/7126356/sqldataadapter-not-updating并提交相同的答案,我会给你赏金。 –

+0

@Internet:好的,我已经在你的其他问题上发布了这个答案,并在那里删除了我的其他方法。 –

0

由于您的DataTable具有不同的架构,因此您必须遍历DataTable中的每一行才能使其正确地从一个端口移到另一个端口。

如果是我,那将是我最关心的事情。那会很快。最大的问题是内存使用率和网络速度。

你将不得不有两个DataTables,两个DataAdapter和两个到数据库的访问(每个服务器一个)。这是很多工作要做的。循环应该不是一个问题。

(虽然,我同意服务器2的数据表的那批更新将是明智的。)

0

如果您使用的SQLServer 2008或更高版本,另一种使用SqlDataAdapter的可能是使用表值参数:

http://msdn.microsoft.com/en-us/library/bb675163.aspx

所以步骤将是:

1)读取源数据到一个DataTable

2)在目标数据库中写入一个新的存储过程,执行导入。这会将表值参数作为其参数之一。您将在步骤1中创建的DataTable传递给此存储过程。优点:完全控制导入过程。可能比使用SqlDataAdapter更好的性能。例如你可以编写T-SQL来一次更新完整的表。

缺点:需要编写一些T-SQL(如果您对此感到满意,可能不会有问题)。