在循环内执行更新查询

时间:2013-12-22 11:16:10

标签: sql sql-server vb.net tsql

   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条记录执行此代码时“没有任何反应”......我做错了什么?有没有其他方法可以更新?

1 个答案:

答案 0 :(得分: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])