2013-12-22 121 views
0
cmd = New SqlCommand("select enrollment,total_fee,discount,net_fee from stu_dtl", openConnection()) 
     ' dr = cmd.ExecuteReader 
     adpt = New SqlDataAdapter(cmd) 
     adpt.Fill(ds, "stu_dtl") 
     dt = ds.Tables("stu_dtl") 
For i = 0 To dt.Rows.Count - 1 
       cmd = New SqlCommand("update stu_dtl set net_fee = '" & (Val(dt.Rows(i).Item("total_fee")) - Val(dt.Rows(i).Item("discount"))) & "' where enrollment = '" & dt.Rows(i).Item("enrollment") & "'", openConnection()) 
      cmd.ExecuteNonQuery() 
     Next 

當我對超過150條記錄執行此代碼「Nothing happens」......我在做什麼錯誤?是否有任何其他方式更新?在循環內執行更新查詢

+0

除非我錯過了某些東西,否則不需要任何代碼。只是創建一個SQL更新查詢和ExecuteNonQuery將做同樣的事情 – peterG

回答

1

我不確定你在做什麼錯。但試試這個代碼。如果發生錯誤,確保數據庫回滾。請注意,我假設net_feeenrollment列的數據類型爲Integer

Using connection As SqlConnection = New SqlConnection("TODO: Set connection string.") 

    Dim table As DataTable = New DataTable("stu_dtl") 
    Dim [error] As Exception = Nothing 

    Using command As SqlCommand = connection.CreateCommand() 
     command.CommandText = "SELECT [enrollment], [total_fee], [discount], [net_fee] FROM [stu_dtl];" 
     Using adapter As New SqlDataAdapter(command) 
      adapter.Fill(table) 
     End Using 
    End Using 

    Using transaction As SqlTransaction = connection.BeginTransaction() 
     Try 

      Dim net_fee As Integer = 0 
      Dim enrollment As Integer = 0 

      For Each row As DataRow In table.Rows 

       net_fee = (CInt(row.Item("total_fee")) - CInt(row.Item("discount"))) 
       enrollment = CInt(row.Item("enrollment")) 

       Using command As SqlCommand = connection.CreateCommand() 
        command.CommandText = "UPDATE [stu_dtl] SET [net_fee] = @net_fee WHERE [enrollment] = @enrollment;" 
        command.Parameters.AddWithValue("@net_fee", net_fee) 
        command.Parameters.AddWithValue("@enrollment", enrollment) 
        command.ExecuteNonQuery() 
       End Using 

      Next 

      transaction.Commit() 

     Catch ex As Exception 
      [error] = ex 
      transaction.Rollback() 
     End Try 
    End Using 

    If (Not table Is Nothing) Then 
     table.Dispose() 
     table = Nothing 
    End If 

    If (Not [error] Is Nothing) Then 
     Throw [error] 
    End If 

End Using 

編輯

試想想起來了,你可能希望將net_fee欄更改爲computed column。該公式將只是([total_fee] - [discount])

+0

計算列肯定是一個更好的選擇....仍然無法弄清楚爲什麼查詢不起作用。無論如何感謝您的幫助 – user108