SQL Server Query won't run - sql

I am connected to a remote SQL Server instance
These queries works fine:
SELECT COUNT(*) FROM Provider
SELECT TOP 1 * FROM Provider
but these don't
SELECT * FROM Provider
SELECT TOP 2 * FROM Provider
and return this error after a long delay:
Msg 64, Level 20, State 0, Line 0
A transport-level error has occurred when receiving results from the
server. (provider: TCP Provider, error: 0 - The specified network name
is no longer available.)
What configuration should I be looking at that would allow a single row result but not a multiple row result?

I found the following
Hey mate, another thing to try i found the following and have included the URL for you. Considering the first bit of trouble shooting didn't work for you
Symptoms
The stack trace of the error resembles the following:
A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - The specified network name is no longer available.)
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParserStateObject.ReadSniError(TdsParserStateObject stateObj, UInt32 error)
at System.Data.SqlClient.TdsParserStateObject.ReadSni(DbAsyncResult asyncResult, TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParserStateObject.ReadPacket(Int32 bytesExpected)
at System.Data.SqlClient.TdsParserStateObject.ReadBuffer()
at System.Data.SqlClient.TdsParserStateObject.ReadByte()
Cause
The error is being caused by a timeout exception for long running queries. In previous versions of Visual Studio .NET, the exception was properly represented as a exception with a timeout description.
Resolution
Set the commandtimeout property of the command object to an appropriate value. Use a value of zero to wait without an exception being thrown.
Taken from https://support.microsoft.com/en-us/kb/555938

Related

SqlDataReader Item property loses connection

I have this large SQL Server query (legacy) over several tables, that I read with a SqlDataReader. It usually has a limited number of rows to handle, but recently I had to use it over a larger number.
After a number of iterations, the SqlDataReader object, on reading an Item() property, throws a SqlException with the code 0x80131904 and the message "Une erreur de niveau transport s'est produite lors de la réception des résultats du serveur. (provider: TCP Provider, error: 0 - Une connexion existante a dû être fermée par l’hôte distant.)" (More details below.)
The message is in my native French and I'm not entirely sure what the official english version is. My translation would be, after some Web searching, "A transport-level error happened on receiving results from the server. (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.)"
I tried it again: the exception was thrown at the exact same row, reading the exact same field. (Subsequent tries showed the exception might be thrown in different places, but that did not vary wildly : out of eight tries, the exception was thrown in only three different places.
The SqlDataReader object happily reads that same field on the previous Read iterations, and checking the query's results in the database shows that the row where the exception is thrown doesn't have a particular value.
I tried tweaking the query's Where clause to get to the exception faster: it actually read more rows than before, then threw the same exception on a different row. (But again, that was more or less on the same row each time with the tweaked query.)
Looking closer, I put a conditional breakpoint on the instruction that throws the exception. It turns out that:
Reading the Item() property with the QuickWatch throws the same exception.
Reading the Item() property for another field that hasn't been read yet in the current iteration throws the same exception.
Conversely, reading the Item() property for other fields already read in the current iteration throws no exception.
I looked up the SqlDataReader's properties before and after the exception. State changes, going from Open to Closed (which is consistent with the exception). ClientConnectionId changes as well, its new value being an unsurprising series of 0s.
What is happening, and how can I prevent that?
APPENDIX 1
The code that opens the SqlDataReader is as follows:
Dim z_dreLecteur As IDataReader = Nothing
Dim z_dcdCommande As IDbCommand = Nothing
[...]
If TypeOf p_dcxConnexion Is SqlConnection Then
z_dcdCommande = New SqlCommand(p_strQuery, DirectCast(p_dcxConnexion, SqlConnection))
Exit Try
End If
[...]
z_dcdCommande.CommandTimeout = 600
[...]
z_dreLecteur = z_dcdCommande.ExecuteReader()
[...]
z_dcdCommande.Dispose()
p_dcxConnexion is a parameter, already set before the above code runs.
APPENDIX 2
More details on the SqlException.
It has an InnerException:
type System.ComponentModel.Win32Exception,
ErrorCode -2147467259,
Message "Une connexion existante a dû être fermée par l’hôte distant" ("An existing connexion was forcibly closed by the remote host"),
NativeErrorCode 10054.
The SqlException has:
ErrorCode -2146232060,
Number 10054,
Message "Une erreur de niveau transport s'est produite lors de la réception des résultats du serveur. (provider: TCP Provider, error: 0 - Une connexion existante a dû être fermée par l’hôte distant.)", which probably translates to "A transport-level error happened on receiving results from the server. (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.)"
I can add the StackTrace if needed, but it's really bulky so I won't for now.

SQL Service Broker Severe Error Receiving Messages after DB Blocking

We use SQL Service Broker queues to notify our application of new records that meet certain criteria being added to a table in another application's database. This is accomplished by having an after insert trigger run a query with for xml against the inserted virtual table and insert any results into a specific service broker queue. We then have a Notifier object that receives from the service broker queue and invokes a callback for each message received. Our code to receive from the Service Broker queue is as follows:
let receiveXmlMessage connection transaction (cancellation: CancellationToken) queueName messageTypeName =
task {
let commandTimeout = if cancellation.IsCancellationRequested then 1 else 0
let receiveQuery =
sprintf """WAITFOR
(
RECEIVE TOP(1)
#message = CONVERT(xml, message_body),
#messageType = message_type_name,
#dialogId = conversation_handle
FROM dbo.[%s]
), TIMEOUT 60000;""" (sanitize queueName)
use receiveCommand =
match transaction with
| Some tx -> new SqlCommand(receiveQuery, connection, tx, CommandTimeout = commandTimeout)
| None -> new SqlCommand(receiveQuery, connection, CommandTimeout = commandTimeout)
receiveCommand.Parameters.AddRange([| SqlParameter("#message", SqlDbType.Xml, Direction = ParameterDirection.Output);
SqlParameter("#messageType", SqlDbType.NVarChar, Direction = ParameterDirection.Output, Size = 256);
SqlParameter("#dialogId", SqlDbType.UniqueIdentifier, Direction = ParameterDirection.Output); |])
try
let! receiveResult = receiveCommand.ExecuteNonQueryAsync(if commandTimeout = 0 then cancellation else CancellationToken.None)
if receiveResult > 0
then let messageType = receiveCommand.Parameters.["#messageType"].Value |> unbox<string>
let dialogId = receiveCommand.Parameters.["#dialogId"].Value |> unbox<Guid>
if messageType = messageTypeName
then do! endConversation connection transaction dialogId
return receiveCommand.Parameters.["#message"].Value |> unbox<string> |> XDocument.Parse
else return XDocument()
else return XDocument()
with | ex ->
log.errorxf ex "Failed to receive message from Service Broker Queue %s" queueName
return! Task.FromException ex
}
This was working fine for several months, processing millions of messages, until a few days ago, when we had another process cause extensive blocking on the database we monitor and our DBAs had to terminate several database sessions to relieve the contention. Ever since this incident, our application has encountered the following error when attempting to receive from the Service Broker queue:
2018-01-11 07:50:27.183-05:00 [31] ERROR - Failed to receive message from Service Broker Queue Notifier_Queue
System.Data.SqlClient.SqlException (0x80131904): A severe error occurred on the current command. The results, if any, should be discarded.
Operation cancelled by user.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.CompleteAsyncExecuteReader()
at System.Data.SqlClient.SqlCommand.EndExecuteNonQueryInternal(IAsyncResult asyncResult)
at System.Data.SqlClient.SqlCommand.EndExecuteNonQueryAsync(IAsyncResult asyncResult)
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Application.Common.Sql.ServiceBroker.receiveXmlMessage#257-3.Invoke(Unit unitVar0)
at Application.Common.TaskBuilder.tryWith[a](FSharpFunc`2 step, FSharpFunc`2 catch)
New messages are successfully added to the queue, and we are able to receive messages from the same queue using SSMS, or even an F# interactive session running as the same user as the application. It only appears to be our application that is affected, but it does seem to affect all instances of our application, on different servers, as long as they are connected to this specific database. We have tried restarting the application and the SQL Server, and we have tried running an ALTER DATABASE ... SET NEW_BROKER WITH ROLLBACK IMMEDIATE. Nothing we've tried has made a difference, we still end up encountering the same exception, and we have hundreds of thousands of conversations remaining the CONVERSING status, since our code to call END CONVERSATION is only invoked after successfully receiving a message.
Our SQL Service Broker queues are setup to model the monologue pattern as described in this blog post.
How can we diagnose the cause of this rather non-specific exception that our application is returning from SQL Server? Is there anything else we could try to diagnose and/or correct whatever changed between our application and SQL Service Broker when the problem first occurred?
We finally figured out what was causing this error when we tried to receive from the Service Broker queue. As it turns out, the CancellationToken that is passed in to our receiveXmlMessage function was being cancelled by other logic in our application that monitors the number of conversing conversations and attempts to recreate our Notifier object if the number of conversing conversations exceeds a certain threshold and the most recently closed conversation is older than another threshold. Due to a bug in the logic for the age of the most recently closed conversation, effectively only the number of conversing conversations was being used to reset the Notifier, and when the DB blocking occurred last week, over 150,000 conversing conversations accumulated. This caused our application to continually cancel the CancellationToken while we were trying to receive messages from Service Broker. Once we took our application down, cleaned up all the conversing conversations, and fixed the bug in the date math for the last closed conversation, the error stopped occurring.
It may be useful to note, for anyone encountering the message:
A severe error occurred on the current command. The results, if any, should be discarded.
That this can be the result of the CancellationToken passed to the ExecuteNonQueryAsync/ExecuteReaderAsync/ExecuteScalarAsync/ExecuteXmlReaderAsync method on the SqlCommand being cancelled while the method is executing.

System.Data.SqlClient.SqlException (0x80131904)

I have a process that runs every morning looping through thousands of records and establishing whether they can be deleted or not. I sometimes see this exception in the log file:
System.Data.SqlClient.SqlException (0x80131904): A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 - Physical connection is not usable)
I have read a potential solution here: http://wishmesh.com/2013/10/solution-for-a-transport-level-error-has-occurred-when-receiving-results-from-the-server/
I know that the SQLDataReader class implements IDisposable as documented here: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx. Therefore you should either wrap it in USING statements or call .close once you have finished with it.
What happens if you do not call .close? I do not understand why it could cause this exception as I thought a data reader was simply a collection of objects already returned from the database and stored in memory.

Get more info from sqlclient error message

I connect my windows mobile app directly to ms-sql server using the sqlclient dll from microsoft.
Some times I get this error when trying to get some data from the server:
System.Data.SqlClient.SqlException: SqlException
at System.Data.SqlClient.SqlConnection.OnError()
at System.Data.SqlClient.SqlInternalConnection.OnError()
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParser.Run()
at System.Data.SqlClient.SqlDataReader.ConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.ExecuteReader()
at System.Data.SqlClient.SqlCommand.ExecuteReader()
Every time I have a error like this I need to try a few other things, some times the connection string is no good, or the network is not configured right or any other random problem.
Is there a way I could get a bit more info from the program so I shouldn't have to waste a few hours figuring out what might went rung?
That's basically just the stack trace. You should be able to get the Message property of the SqlException which contains the details. In some cases you will have to look at the InnerException to get to the interesting details.
Ok I found the answer... I changed: Catch ex As Exception To: Catch ex As SqlException
Now I get the specific error nicely displayed in the message.

DateInterval.minute is not a recognized dateadd option

I'm trying to test a developer's application against a SQL Server 2005 database (80) instead of the normal SQL Server 2000 database that it would hit.
Is anyone aware of issues that could cause this error that are related to SQL?
'DateInterval.minute' is not a recognized dateadd option.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: 'DateInterval.minute' is not a recognized dateadd option.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SqlException: 'DateInterval.minute' is not a recognized dateadd option.]
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream) +742
System.Data.SqlClient.SqlCommand.ExecuteReader() +41
ConnectString.Timeout.UpdateTimeout.UpdateTime()
RoleMap.HelpDeskCust.Page_Load(Object sender, EventArgs e) in c:\inetpub\wwwroot\program.aspx.vb:35
System.Web.UI.Control.OnLoad(EventArgs e) +67
System.Web.UI.Control.LoadRecursive() +35
System.Web.UI.Page.ProcessRequestMain() +750
Version Information: Microsoft .NET Framework Version:1.1.4322.2407; ASP.NET Version:1.1.4322.2407
DateInterval.minute is not an option in SQL for either SQL 2000 (8.0) or SQL 2005 (9.0). It's a .net enumerator for use in .net DateAdd
You appear to be passing a .net construct to the database engine.
For true SQL, you'd have this: DATEADD(minute, number, date)