發現原因出在迴圈搭配 DataAdapter.Fill 上
有問題的程式大致如下:
Dim dt As New DataTable
Dim saDept() As New String {"A01", "A02"}
For i As Integer = 0 To saDept.Length - 1
Dim strSQL As String = "SELECT * FROM Employee WHERE Dept = '" & saDept(i) & "' "
Dim scCmd As New SqlClient.SqlCommand
Dim sdaAdapter As New SqlClient.SqlDataAdapter
scCmd.CommandText = strSQL
sdaAdapter.SelectCommand = scCmd
sdaAdapter.Fill(dt)
.
.
.
Next
Dim saDept() As New String {"A01", "A02"}
For i As Integer = 0 To saDept.Length - 1
Dim strSQL As String = "SELECT * FROM Employee WHERE Dept = '" & saDept(i) & "' "
Dim scCmd As New SqlClient.SqlCommand
Dim sdaAdapter As New SqlClient.SqlDataAdapter
scCmd.CommandText = strSQL
sdaAdapter.SelectCommand = scCmd
sdaAdapter.Fill(dt)
.
.
.
Next
之前一直以為 DataAdapter.Fill 執行時
會先清空 DataTable 內容再重新寫入資料
沒想到實際動作是
保留 DataTable 內的資料, 再將新資料 append 進 DataTable
導致這次資料異常寫入
只要在 DataTable 使用完後 (Next 上方)
加一個 dt.Clear()
就可解決這個問題
算是學到了一個經驗
沒有留言:
張貼留言