我正在使用VS 2010同步2个数据库(SQL Express和SQL Compact Edition)。它在程序首次运行时工作正常。但是,当代码执行多次时,SQL命令“超时已过期”异常发生。错误消息是:
超时已过期。操作完成之前经过的超时时间或服务器没有响应。
以下是我处理ClientInsertServerInsert冲突的代码。 (编辑:根据这篇MSDN文章,这与客户端和服务器都插入具有相同主键值的行有关。这会导致主键违规。)
Dim conflictTableName As String = e.TableMetadata.TableName.ToString
Dim serverConflictDT, clientConflictDT As DataTable
Dim clientConflictID As Int16
Dim new_ID As Int16
Dim SqlCon As New SqlConnection
clientConflictDT = e.Conflict.ClientChange
serverConflictDT = e.Conflict.ServerChange
If e.Conflict.ConflictType = ConflictType.ClientInsertServerInsert Then
SqlCon = New SqlConnection(STR_SQL_CON)
Using SqlCon
If SqlCon.State = ConnectionState.Closed Then SqlCon.Open()
MsgBox(SqlCon.PacketSize.ToString & vbNewLine & conflictTableName.ToString)
Dim sqlStr = "SELECT CASE WHEN MAX(ID) IS NULL THEN 0 ELSE MAX(ID)+1 END FROM " & conflictTableName
Dim sqlcmd As New SqlCommand(sqlStr, SqlCon)
sqlcmd.CommandTimeout = 2
new_ID = sqlcmd.ExecuteScalar '<- This is the line where the Exception occurred
clientConflictID = clientConflictDT.Rows(0)(0)
MsgBox(new_ID.ToString & conflictTableName.ToString)
Try
Using SqlCeCon As New SqlCeConnection(STR_SQLCE_CON)
If SqlCeCon.State = ConnectionState.Closed Then SqlCeCon.Open()
Dim sqlCeCmd As New SqlCeCommand
Dim sqlCeStr = Nothing
sqlCeStr = "SELECT CASE WHEN MAX(ID) IS NULL THEN 0 ELSE MAX(ID)+1 END FROM " & conflictTableName
sqlCeCmd = New SqlCeCommand(sqlCeStr, SqlCeCon)
If new_ID < sqlCeCmd.ExecuteScalar Then
new_ID = sqlCeCmd.ExecuteScalar
End If
sqlCeStr = "UPDATE " & conflictTableName & " SET id=" & new_ID & " WHERE id=" & clientConflictID
sqlCeCmd.CommandText = sqlCeStr
sqlCeCmd.ExecuteNonQuery()
End Using
Catch ex As Exception
Finally
End Try
End Using
End If
提前致谢
答案 0 :(得分:2)
我想这是由数据库锁引起的。从
修改SQL SELECT语句后"SELECT CASE WHEN MAX(ID) IS NULL THEN 0 ELSE MAX(ID)+1 END FROM " & conflictTableName
到
"SELECT CASE WHEN MAX(ID) IS NULL THEN 0 ELSE MAX(ID)+1 END FROM " & conflictTableName & " WITH (NOLOCK)"
然后问题就解决了。
无论如何,感谢所有评论: - )