已经有一个与此命令关联的打开DataReader,必须先关闭它

时间:2012-03-13 15:27:44

标签: asp.net vb.net

Dim staffid = TextBox1.Text
    Dim conn As New SqlConnection
    conn.ConnectionString = SqlDataSource1.ConnectionString

    Dim command1 As New SqlCommand("SELECT StaffDetails.StaffID, SUM(HolidayRequests.RequestTotalDays) AS Expr1 FROM HolidayRequests INNER JOIN StaffDetails ON HolidayRequests.Username = StaffDetails.UserName WHERE (StaffDetails.StaffID = staffID) GROUP BY StaffDetails.StaffID, HolidayRequests.ApprovalStatus HAVING (HolidayRequests.ApprovalStatus = N'approved')", conn)
    Dim command2 As New SqlCommand()
    conn.Open()
    Dim rdr As SqlDataReader
    rdr = command1.ExecuteReader
    Dim UpdateQuery As String
    While (rdr.Read())

        UpdateQuery = "UPDATE HolidayEntitlement set Holiday_Taken = @Expr1"
        command2.Parameters.AddWithValue("@Expr1", rdr("Expr1").ToString())

        'run update query

        command2.CommandText = UpdateQuery
        command2.ExecuteNonQuery()

        conn.Close()
    End While

以下错误: command2.ExecuteNonQuery:尚未初始化Connection属性。

2 个答案:

答案 0 :(得分:2)

您好需要创建第二个命令对象。由于您正在尝试使用相同的命令对象进行读取,因此尝试使用。

执行更新语句

此外,您正在关闭while循环内部的连接。之后你必须这样做。

答案 1 :(得分:1)

创建第二个命令。换句话说,使用一个光标进行读取,另一个用于更新。