Friday, May 30, 2008

Checking for Locks/Blocks in SQL Server

OK, this is one that I will never forget, because I use it often enough that it stays fresh in my mind. I have read a lot if ways that people use to check on the server for blocks. Well, I like to keep things simple. So, I have 1 query that I run. Run it against the master database and you'll see who is your culprit causing slowness (in most cases).

use master
go

select * from sysprocesses where blocked <> 0

quite simply.. this query is going to return to you the connections that are being blocked. Now, the number that appears in the 'blocked' column is a spid (connection id) for the blocker. So, you can check the returned results and follow the block path.
Now, once you find the spid that appeared in others blocked column, but has a '0' in their blocked path, they are the ones causing all the problems.

In other words, spid 224 is blocked by 143, and 143 is blocked by 68, 68 is blocked by nobody(has 0 in their blocked column) .. 68 is your culprit!

So, say you see that 68 is your culprit. You naturally wonder to your pea brained self "I wonder what 68 is doing?"

Turns out MSFT Thought of that too.. created a DBCC function just for that. "dbcc inputbuffer" is it's name, returning query info is it's game.

Here is an example of execution that will match our purposes here

dbcc inputbuffer(68)

The query they are running, more accurately, the query that was last run by this spid will be returned in the "EventInfo" column of the results.
Please note.. You can only get a max of 256 characters returned from this process. Which, coincidently, causes me much frustration at times! Often, a query is > 256 characters!

No comments: