我正在将表的子集读入DataTable并修改DataTable。我需要使用更新的信息来更新原始SQL Server表。
最终,我接受了马克·克拉姆(Mark Kram)的建议,并使用SqlBulkCopy将DataTable数据放入SQL Server表中,然后运行SQL UPDATE语句以更新每周数据。
Dim conn As New SqlConnection With {.ConnectionString = ConnString}
dim strSQL as String, Sum13 as Double, x as Int16, y as Int16
strSQL = "SELECT Symbol, WeekEnd, AdjClose, Avg13, StdDev13 FROM Weekly " &
"WHERE Symbol = '" & strSym & "' ORDER BY WeekEnd DESC;"
Dim sdCmd As New SqlCommand(strSQL, conn)
Dim sdda As New SqlDataAdapter(sdCmd)
Dim dt As New DataTable
sdda.Fill(dt)
conn.Open()
'calculate the 13 week moving average
Dim row As DataRow
For x = 0 To dt.Rows.Count - 13
Sum13 = 0
For y = x To x + 12
Sum13 += dt.Rows(y).Item("AdjClose")
Next
dt.Rows(x).Item("Avg13") = Math.Round(Sum13 / 13, 4)
Next
'calculate the 13 week standard deviation
For x = 0 To dt.Rows.Count - 13
Sum13 = 0
For y = x To x + 12
Sum13 += (dt.Rows(y).Item("AdjClose") - dt.Rows(x).Item("Avg13")) ^ 2
Next
dt.Rows(x).Item("StdDev13") = Math.Round(Math.Sqrt(Sum13 / 12), 4)
Next
最后一步是将数据插入临时表中,然后更新Weekly SQL Server表。我创建了“ TempWeekly”表以匹配DataTable并重复使用。
'load the TempDaily table with the DataTable
strSQL = "DELETE FROM TempWeekly"
cmd.CommandText = strSQL
cmd.ExecuteNonQuery()
Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(conn)
bulkCopy.DestinationTableName = "dbo.TempWeekly"
Dim mapSym As New SqlBulkCopyColumnMapping("Symbol", "Symbol")
bulkCopy.ColumnMappings.Add(mapSym)
Dim mapWeekEnd As New SqlBulkCopyColumnMapping("WeekEnd", "WeekEnd")
bulkCopy.ColumnMappings.Add(mapWeekEnd)
Dim mapStdDev13 As New SqlBulkCopyColumnMapping("StdDev13", "StdDev13")
bulkCopy.ColumnMappings.Add(mapStdDev13)
Dim mapAvg13 As New SqlBulkCopyColumnMapping("Avg13", "Avg13")
bulkCopy.ColumnMappings.Add(mapAvg13)
bulkCopy.WriteToServer(dt)
End Using
'update the Weekly table from TempDaily
strSQL = "UPDATE Weekly " &
"SET Weekly.Avg13 = TempWeekly.Avg13, " &
"Weekly.StdDev13 = TempWeekly.StdDev13 " &
"FROM TempWeekly " &
"WHERE (Weekly.Symbol = TempWeekly.Symbol) AND " &
(Weekly.WeekEnd = TempWeekly.WeekEnd) AND " &
(TempWeekly.Avg13 <> 0);"
cmd.CommandText = strSQL
cmd.ExecuteNonQuery()