0

This is the scenario, I have a select query then all fetched data must be inserted into another table.. This is what I came up, I don't know if the for loop does anything.

If I would remove the for loop. Example: Fetched data is id1, id2, id3 the inserted data in my database is id1, id1, id1 instead of id1, id2, id3

sql = "SELECT * FROM dummy_violate WHERE res_month <> @month Or res_year <> @year"
    cmd = New MySqlCommand(sql, con)
    cmd.Parameters.AddWithValue("@month", DateTime.Now.ToString("MMMM"))
    cmd.Parameters.AddWithValue("@year", DateTime.Now.ToString("yyyy"))
    dr = cmd.ExecuteReader
    While dr.Read
        id += dr(0)
        count += 1
    End While
    dr.Close()
    If count > 0 Then

        For i As Integer = 1 To count
            sql2 = "INSERT INTO dummy_violate(res_id, res_month, res_year, is_paid)VALUES(@id,@month,@year,@paid)"
            cmd = New MySqlCommand(sql2, con)
            cmd.Parameters.AddWithValue("@id", id)
            cmd.Parameters.AddWithValue("@month", DateTime.Now.ToString("MMMM"))
            cmd.Parameters.AddWithValue("@year", DateTime.Now.ToString("yyyy"))
            cmd.Parameters.AddWithValue("@paid", 0)
            cmd.ExecuteNonQuery()
        Next
    ElseIf count = 0 Then

        MsgBox("Wrong Query")

    End If
4

1 回答 1

2

我真的不明白您要做什么以及为什么,您似乎只是将表中已经存在的记录与具有相同数据但 is_paid 标志设置为零的新记录重复。如果是这样,请尝试以这种方式更改您的代码:

sql = "SELECT res_id FROM dummy_violate WHERE res_month <> @month Or res_year <> @year"
cmd = New MySqlCommand(sql, con)
cmd.Parameters.AddWithValue("@month", DateTime.Now.ToString("MMMM"))
cmd.Parameters.AddWithValue("@year", DateTime.Now.ToString("yyyy"))
Dim da = new MySqlDataAdapter(cmd)
Dim dt = new DataTable()
da.Fill(dt)

' if we have records to duplicate we have Rows.Count > 0
If dt.Rows.Count > 0 Then
   sql2 = "INSERT INTO dummy_violate(res_id, res_month, res_year, is_paid) " & _ 
          "VALUES(@id,@month,@year,@paid)"
    cmd = New MySqlCommand(sql2, con)

    ' Add all the parameters before entering the loop. Just @id changes for every loop,
    ' so we set it with a dummy value outside the loop and we change it when looping over
    ' the result table.....
    cmd.Parameters.AddWithValue("@id", 0) 
    cmd.Parameters.AddWithValue("@month", DateTime.Now.ToString("MMMM"))
    cmd.Parameters.AddWithValue("@year", DateTime.Now.ToString("yyyy"))
    cmd.Parameters.AddWithValue("@paid", 0)

    ' execute the insert for all the rows count 
    ' rows array starts at zero so loop to count -1
    For i As Integer = 0 To dt.Rows.Count - 1
        cmd.Parameters("@id").Value = dt.Rows(i)("res_id")
        cmd.ExecuteNonQuery()
    Next
ElseIf count = 0 Then
    MsgBox("Wrong Query")
End If

请记住,如果 res_id 是主键,则不能将具有相同 res_id 的记录插入两次。此外,如果 res_id 是一个 auto_number 列(又名 IDENTITY),那么您不能显式设置它的值

于 2013-10-06T10:40:58.243 回答