I try to find out the performance or internal implementation for WAITFOR in T-SQL, have gone through MSDN and Stackoverflow and other sites without luck, here is my question
For below code, I want to delete the top 10,000 rows from table DUMMY
. I want to make this delete job have the least performance impact on the database's other jobs as possible and give priority to others (if any). So I make it delete 100 rows at a time and do it 100 times with sleep time in two adjacent deletes.
Question:
During the WAITFOR
blocking time, will this transaction consume CPU or just idle and waiting for kicked up by some event 1 second later?
During that 1 sec, if there are other transactions trying to INSERT/UPDATE
on the DUMMY
table, who gets priority?
Really appreciate your help or any insights for this
declare @cnt int
set @cnt = 0
while @cnt < 100
begin
delete top 100 from DUMMYTABLE where FOO = 'BAR'
set @cnt = @cnt + 1
waitfor delay '00:00:01'
end
As long as you don't COMMIT or ROLLBACK a transaction, it's still "running" and potentially holding locks. If your client (application or user) closes the connection to the database before committing, any still running transactions will be rolled back and terminated.
Your largest consequence will be blocking of the objects used in the transaction. Especially if you assume your users are inserting data, then that long running transaction could include SELECT statements on commonly used tables.
If the query isn't executed within a transaction (and no lock hints are used), the locks for SELECT statements will only be held on a resource at the time it's actually being read, not during the query.
The WAITFOR wait type means that the session is running the WAITFOR statement. Hence, if you're seeing that wait, the app is running that statement. Look through that app's code for the presence of the WAITFOR statement anywhere.
You can see this with 2 query windows:
SELECT @@SPID;
GO
WAITFOR DELAY '000:03:00'; -- three minutes
Then in the other
SELECT * FROM sys.sysprocesses S WHERE S.spid = 53; -- replace 53
Note: SQL Server 2012 SP1 but AFAIK behaviour is the same
Point 2, sorry missed this
Another session will modify the table while the WAITFOR is running. It isn't a lock.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With