Reputation: 640
This is my code for insert and update statement:
For i = 0 To lvFabric1.Items.Count - 1
strQ4 = ""
strQ4 = strQ4 & "INSERT into js_det(LINE_NO, FABRIC1, FABRIC2, `DESC`) SELECT LPAD('" & i + 1 & "',2, '0'), '" & lvFabric1.Items(i).Text & "','sdf', `DESC` from rm_inv where ITEM_CODE = '" & lvFabric1.Items(i).Text & "'"
strQ5 = ""
strQ5 = strQ5 & "UPDATE js_det set TRAN_NO = (SELECT JS_TRAN FROM counter) where Fabric1 = '" & lvFabric1.Items(i).Text & "'"
cmd.CommandText = strQ4
cmd.ExecuteNonQuery()
cmd.CommandText = strQ5
cmd.ExecuteNonQuery()
Next
What the problem here is that its getting slower if it is looping 5 times and above, it take above 3 second. How can I speed up this code? or is there another way?
Thanks for the help.
Upvotes: 0
Views: 1060
Reputation: 2140
To speed it up, commit the whole thing in one go, somthing like:
Dim sqls As New List(Of String)
For i = 0 To lvFabric1.Items.Count - 1
sqls.Add("INSERT into js_det(LINE_NO, FABRIC1, FABRIC2, `DESC`) SELECT LPAD('" & i + 1 & "',2, '0'), '" & lvFabric1.Items(i).Text & "','sdf', `DESC` from rm_inv where ITEM_CODE = '" & lvFabric1.Items(i).Text & "'")
sqls.Add("UPDATE js_det set TRAN_NO = (SELECT JS_TRAN FROM counter) where Fabric1 = '" & lvFabric1.Items(i).Text & "'")
Next
If sqls.Any() Then
cmd.CommandText = sqls.Aggregate(Function(m, n) m & ";" & n)
cmd.ExecuteNonQuery()
End If
However, it's not a recommended way to do sql query in .net.
SQL parameter should be used to avoid any sql injection or sql syntax error.
EDIT: using sql parameter -
Using con As New SqlConnection("My connection string..."),
cmd As New SqlCommand(sql, con)
cmd.CommandText = "UPDATE js_det set TRAN_NO = (SELECT JS_TRAN FROM counter) where Fabric1 = @fabric"
Dim fabricParam = cmd.Parameters.Add("@fabric", SqlDbType.VarChar)
con.Open()
For i = 0 To lvFabric1.Items.Count - 1
fabricParam.Value = lvFabric1.Items(i).Text
cmd.ExecuteNonQuery()
Next
con.Close()
End Using
Upvotes: 3