I have developed an application which runs with multiple instance simultaneously. In the application it connects to a SQL Server and fetches some data, while working on that data, it updates the row as picked so that no other instance of the application picks up the same record for research. While updating the row for the fetched record, sometime it gets deadlock issue and not updating the record as already picked.
Dim MyConnection As SqlConnection
Try
MyConnection = New SqlConnection(connString)
MyConnection.Open()
Dim tableName As String = myTableName
Dim sqlQuery As String = "Select Top 1 * from " + tableName + " where "<some condition>
Dim MyCommand As SqlDataAdapter = New SqlDataAdapter(sqlQuery, MyConnection)
Dim DS as DataSet = New DataSet
MyCommand.Fill(DS, tableName)
If DS.Tables(0).Rows.Count >= 1 Then
sqlQuery = "UPDATE " + tableName + " SET Fld = @fld where Cond1= '" + DS.Tables(0).Rows(0).Item("Cond1").ToString + "'"
Dim cmd As New Data.SqlClient.SqlCommand(sqlQuery)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("@fld", Data.SqlDbType.VarChar).Value = "Picked"
Try
cmd.Connection = MyConnection
cmd.ExecuteNonQuery() <---- Dead lock occurs here
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End If
Catch ex As Exception
MsgBox(ex.ToString)
Finally
MyConnection.Close()
End Try
While executing the update statement, deadlock occurs and it goes to catch block and then exits the sub without updating the required field in the table. I want it to try to update until the dead lock is removed.
Creating Stored Procedure is not possible as I do not have the admin rights to this DB.
How can I overcome the problem?