为什么我不能使用循环在数据库中插入结果值?

时间:2015-01-28 08:20:15

标签: vb.net

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim con As New SqlConnection
    con.ConnectionString = "server=hcl-pc\SQLEXPRESS;Initial Catalog=UBGB_HRMS;Integrated Security=True"
    Dim s As String
    Dim t As Decimal
    Dim CMD1, CMD2, cmd3 As SqlCommand
    Dim cmd4 As New SqlCommand("ins_loopres", con)
    con.Open()
    CMD1 = New SqlCommand("select sl from loopex ", con)  
    s = Convert.ToString(CMD1)
    While CMD1.ExecuteScalar
        CMD2 = New SqlCommand("select val1 from loopex where sl='" + s + "'", con)
        cmd3 = New SqlCommand("select val2 from loopex  where sl= '" + s + "'", con)
        t = Convert.ToDecimal(CMD2.ExecuteScalar()) + Convert.ToDecimal(cmd3.ExecuteScalar())
        cmd4.CommandType = CommandType.StoredProcedure
        cmd4.Parameters.AddWithValue("sl", s)
        cmd4.Parameters.AddWithValue("val", Decimal.Parse(t))
        cmd4.ExecuteNonQuery()
    End While

我收到以下错误:

  转换varchar值system.dat ti数据时

转换失败   输入int

1 个答案:

答案 0 :(得分:0)

我已经解决了我的问题:

Dim con As New SqlConnection
    con.ConnectionString = "server=hcl-pc\SQLEXPRESS;Initial Catalog=UBGB_HRMS;Integrated Security=True;MultipleActiveResultSets=True"
    Dim CMD1, cmd2, cmd3 As SqlCommand
    Dim t As Integer
    Dim dr As SqlDataReader
    Dim cmd4 As New SqlCommand("ins_loopres", con)
    Dim s As String
    con.Open()
    CMD1 = New SqlCommand("select sl from loopex ", con)
    dr = CMD1.ExecuteReader
    While dr.Read
        s = dr.Item("sl")
        cmd2 = New SqlCommand("select val1 from loopex where sl='" + s + "' ", con)
        cmd3 = New SqlCommand("select val2 from loopex where sl='" + s + "' ", con)
        t = Convert.ToInt32(cmd2.ExecuteScalar()) + Convert.ToInt32(cmd3.ExecuteScalar())
        cmd4.CommandType = CommandType.StoredProcedure
        cmd4.Parameters.AddWithValue("sl", s)
        cmd4.Parameters.AddWithValue("val", t)
        cmd4.ExecuteNonQuery()
        cmd4.Parameters.Clear()
    End While
    dr.Close()
End Sub