Let's say I have a query that is sent to my SQL-Server database, it takes more than 30 seconds, and my program throws an SQL Query Timeout exception. Is the query still chugging along on my database or does it get terminated as soon as the exception is thrown?
A client signals a query timeout to
the server using an attention event.
An attention event is simply a
distinct type of TDS packet a SQL
Server client can send to it. In
addition to connect/disconnect, T-SQL
batch, and RPC events, a client can
signal an attention to the server. An
attention tells the server to cancel
the connection's currently executing
query (if there is one) as soon as
possible. An attention doesn't
rollback open transactions, and it
doesn't stop the currently executing
query on a dime -- the server aborts
whatever it was doing for the
connection at the next available
opportunity. Usually, this happens
pretty quickly, but not always.
Source There's no such thing as a query timeout...
When the client decides that the command has run long enough, it issues an "Abort". The query simply stops running in the database.
Any CATCH block won't be hit, transactions will be left open and locks can still remain allocated after this, even if the connection is closed because "close" means "return to connection pool".
If you expect a lot of Command Timeouts then consider using SET XACT_ABORT ON (and this too) that will release locks and rollback transactions. or fix the code...
Before executing a query, SQL Server
estimates how much memory it needs to
run and tries to reserve this amount
of memory from the buffer pool. If the
reservation succeeds the query is
executed immediately. If there is not
enough memory readily available from
the buffer pool, then the query is put
into a queue with a timeout value,
where the timeout value is guided by
the query cost. The basic rule is:
higher the estimated cost is, larger
the time out value is. When the
waiting time of this query exceeds the
timeout value, a time out error is
thrown and the query is removed from
the queue.
Source
If you get a SQL timeout then SQL has stopped, however web applications can time out and the SQL query can continue.
Usually when it times out it means the connection has died, meaning the query has not been sent to the database, most database support Transactions where you can start a transaction, run your queries, and if your happy you can commit them.
Example:
BEGIN TRAN
UPDATE authors
SET au_fname = 'John'
WHERE au_id = '172-32-1176'
UPDATE authors
SET au_fname = 'Marg'
WHERE au_id = '213-46-8915'
COMMIT TRAN
Related
I've noticed a lot of db connections left open on my production SQL Server, some for a very long time. Many of these have an open transaction. As seen in the query:
select * from sysprocesses where open_tran>0
They are in status = "sleeping", cmd = "AWAITING COMMAND".
The connections are opened using NHIBERNATE as follows:
For<ISessionFactory>().Singleton()
.Use(() => DataContext.GetSessionFactory());
For<ISession>().Transient()
.Use(context => context.GetInstance<ISessionFactory>().OpenSession());
Some sessions use a transaction scope:
_transactionScope = new TransactionScope();
Some create a transaction:
_uncommittedTransaction = SessionUncommittedWrapper.Session.BeginTransaction(IsolationLevel.ReadUncommitted);
The transaction and/or transactionScope are disposed afterwards.
Why are the connections still open? And is it a problem, if nothing is being blocked?
They are in status = "sleeping", cmd = "AWAITING COMMAND".
when you see a row in sysprocesses with a status of sleeping,that means this connection is active ,but not being used..This also happens due to connection Pooling mechanism used by SQLServer..
Awaiting command can be explained by below example..
Session 1: start this transaction
begin tran
insert into sometable
select some columns
Now when you check the status of session1 in sys.processes/session DMV,you can see that as Awaiting command..since ,you didn't committed it.
One more reason of awaiting command can be when you start a transaction and wait for user input like
begin tran
update t
set t1.a=<<some input from user>>--waiting
where t1.a=oldvalue
commit
And is it a problem, if nothing is being blocked?
As long as you see,nothing is blocked,sleeping and sessions are not holding any locks and you don't see any open transactions, you don't need to worry.This is explained by Bob Dorr in this article..
The question usually arises around a session that is holding locks and its state is sleeping / awaiting command. If the client has an open transaction and the client did not submit a commit or rollback command the state is sleeping / awaiting command. I see this quite often with a procedure that times out.
Create proc myProc
As
Begin tran
Update authors ….
Waitfor delay ’10:00:00’ — time out will occur here (simulates long workload)
rollback
go
When run from the client with a 30 second query timeout the transaction will remain open because the client indicated it wanted to ‘cancel execution’ and do no further processing.
To get automatic rollback in this situation transaction abort must be enabled. You now have an open transaction with a SPID sleeping/awaiting command.
The situation can be caused by many other variations but it is always a situation where the SQL Server is waiting for the next command from the client
Based on NHibernate doc.
Hibernate relies on the ADO.NET data provider implementation of
connection pooling.
Connections are open beceuse reusing opened connections improve performace.
More info:
NHibernate Connection Pooling
NHibernate and ADO.NET Connection Pooling
I have more than 12k records.
Default configured is 30 sec for connection time out. In this scenario i am getting exception like sql connection time out is closed.
I configured connection time out 0 for executing from c#.
Any disadvantage for set to value is 0.
Please suggest which value is fine for connection timeout. Please keep in mind I have huge data like 12k to 50k.
A value of 0 indicates no limit, and should be avoided in a ConnectionString because an attempt to connect waits indefinitely.
Making connection depends on database,drivers, it is local or remote.
You can not pin point some specific value knowing all these things. value doesn't depends on number of records.
if some problem occur while processing some specific record and it takes too long and you don't want to wait for so long in order to save time. Set CommandTimeout property but it has nothing to do with connection state
In my Windows application, I use SQL Server 2008. My database size is 5086080 KB. Now I get the error as timeout expired when saving a transaction by using a stored procedure. So I set command timeout to 1200. It works fine. But I think it shouldn't because insert data have 2 or 3 lines. Is there any other way to solve this problem?
This is detail error message:
Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding .
Timeout is entirely on how long the actual SQL command is likely to take.
For example example, most of our commands run sproc's that should take no longer than 30 seconds to complete, however there are a couple that run for much longer, which means they have their own high valued timeouts.
You'll need to profile how long on average your routine takes then adjust the timeout accordingly, and remember to leave room for variables like latency etc
you need to profile your sql query and your code at every step. only then will you be able to know the exact bottleneck in your program.
Is somebody else keeping a transaction open that is holding up your query? Run sp_who or sp_who2 on the server to see what else is running.
I have 1 store procedure to generate some report, its is very complex so it is taking upto 7-8 mins sometimes to generate output.
When i am trying to access from the Webpage ( C# ) i am getting connection time out error.
I have already set remote connection timeout=0 (unlimited) and in connection string also i have tried to supply connection timeout.
I have suppose 6 Lacs around records of bills and i have performing 6 times around sum based on different groups and different dates, so is there any solution to make it faster.
Or any connection timeout workout?
I think the problem with page request timeout. I suppose you start stored procedure execution right on Page_Load event and after some time IIS close request by timeout.
I'm suggesting to you remove load function from Page_Load event and after page loaded send AJAX request to server or page to start stored procedure execution and check execution result from time to time. When result will be ready you can get it by AJAX and display to user.
Is it really connection timeout that you should be worrying about?
Since you have a long-running command, please ensure that you set CommandTimeout on your SqlCommand to 0.
I'm building a site that runs fine for a few hours, but then *.asmx and *.ashx calls start timing out.
The exception is: "Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool This may have occurred because all pooled connections were in use and max pool size was reached."
I'm using SubSonic as the ORM.
I suspect that the problem is based on a scheduled task that runs every few minutes and hits the database. When I look in SQL Server 2000's "Current Activity", I see there are:
100 processes with the status "sleeping"
100 locks
The 100 processes are from the Application ".Net SqlClient Data Provider" and the command is "AWAITING COMMAND".
So I'm guessing that's the issue . . but how do I troubleshoot it? Does this sound like a deadlock condition in the db? As soon as I
c:\> iisrestart
, everything's fine (for a while).
Thanks - I've just never encountered something like this and am not sure the best way to proceed.
Michael
It could be a duplicate of this problem - Is connection pooling working correctly in Subsonic?
If you're loading objects with Load() instead of LoadAndCloseReader(), each connection will be left open and eventually you'll exhaust the connection pool.
When you call Load() on a collection it will leave the Reader open - make sure you call LoadAndCloseReader() if you want the reader to close off - or use a using block.
It helps to have some source code as well.
I don't know anything about Subsonic, but maybe you are leaking database 'contexts'? I'd check that any database resource is being disposed after you're finished with it...