Tag: sys.dm_os_performance_counters

How to capture deadlock occurrences in SQL Server using sys.dm_os_performance_counters

Today, let us quickly see how to monitor deadlocks in your SQL Server. There are multiple ways to get the deadlock information.

But, this blog post details an approach to capture the number of deadlocks using performance monitor dynamic management view in a SQL Server.

This approach does not really cover the deadlock graph capturing or analyzing the deadlock graph etc. This enables you to just understand if there are deadlocks in your system and it captures the data as you configured. This data can be used to generate nice reports as per your requirement.

Object creation script

First step is to create the objects to store the deadlock information. Please note, we are not doing to capture the deadlock information, but just the occurrence of deadlocks. So we need a table with DateAdded to denote the captured date and time and deadlocks column to denote the number of deadlocks occurred.
Drop Table  if exists DeadlockTracker

CREATE TABLE DeadlockTracker(
    DateAdded datetime NOT NULL
    , Deadlocks int NOT NULL
)


CREATE UNIQUE CLUSTERED INDEX IX_DeadlockTracker_DateAdded_U_C ON DeadlockTracker
(
    DateAdded
) WITH (FillFactor = 100)

Capture Query

The next step is to define the capture process. The idea is to frequently query a dynamic management view – sys.dm_os_performance_counter and log the data in the table as defined int he first step.

We need to capture these information in a defined interval, may be every 15 minutes. We can configure a SQL job to run every 15 minutes.
DECLARE @CounterPrefix NVARCHAR(30)
SET @CounterPrefix = CASE WHEN @@SERVICENAME = 'MSSQLSERVER'
                            THEN 'SQLServer:'
                        ELSE 'MSSQL$' + @@SERVICENAME + ':'
                        END

INSERT INTO DeadlockTracker(DateAdded,  Deadlocks)
SELECT DateAdded            = GetDate()
     , Deadlocks             = (SELECT cntr_value FROM sys.dm_os_performance_counters 
									WHERE object_name like @CounterPrefix + '%'
										AND instance_name IN ('', '_Total')
										AND counter_name ='Number of Deadlocks/sec')

Sample Report Dashboard Queries

This is the last step which is nothing but visualization of data captured. This is absolutely depending on data analyst discretion, but a very basic report sample has provided for your reference. You can change the query to get the data group by month/days/quarter etc.

Select *, Deadlocks - Lag(Deadlocks) Over(Order by DateAdded asc) From  DeadlockTracker

I’d like to grow my readership. If you enjoyed this blog post, please share it with your friends!

Temporary table caching in SQL Server

Caching of Temporary table is an interesting topic but not appreciated/recognized one in SQL Server due to several reasons.

First off, Let us see whats caching of temporary tables? – Caching temporary objects like temp tables/table variables will improve the performance of execution by eliminating the
recreation of objects.There are certain operations which will prevent the caching of temporary objects are below.

1. DDL commands once the object is created
2. Recompilation of Procedure associated
3. Dynamic SQL is used to create the objects
4. Named Constraints etc

Today, we are going to see how DDL commands is preventing the caching of temp objects.

Lets Create a Procedure and create a temp object:


--Create a procedure 
create Procedure Test_TempCaching
as
Begin
	create Table #Temp (EmpId int, FirstName varchar(50), LastName Varchar(50))
	create clustered index ix_test on #Temp(EmpId)
	Insert into #Temp Values(1,'SQL','Server'),(2, 'Biz','Talk')
End

We are going to see the temp tables creation rate using the below query:


SELECT cntr_value FROM sys.dm_os_performance_counters WHERE counter_name = 'Temp Tables Creation Rate'

The above will result a cumulative information on the number of times the temp objects created.

For the first time, when we create the procedure and executing the procedure, it will create a plan for the procedure and temp object is being created and cached.
If you look at the procedure, A temp table is created and later the object has been modified with DDL to add an index on the temp table.

Every time, the procedure gets executed, you can see the value gets changed,
Use the below query multiple times, and see the difference.


SELECT cntr_value FROM sys.dm_os_performance_counters WHERE counter_name = 'Temp Tables Creation Rate'
EXEC  Test_TempCaching
SELECT cntr_value FROM sys.dm_os_performance_counters WHERE counter_name = 'Temp Tables Creation Rate'


The above behavior shows that, if there is any DDL applied after the temp object, then the object will become obsolete and evict from the cache(later) and create a new object. You may find a performance issue if the procedure is executing very frequently in your application.

Now, Let us modify the procedure to comine the DDL command inline at the creation of temporary table as below:


ALTER Procedure Test_TempCaching
as
Begin
	create Table #Temp (EmpId int, FirstName varchar(50), LastName Varchar(50), Primary Key(EmpID))
	Insert into #Temp Values(1,'SQL','Server'),(2, 'Biz','Talk')

End

If you execute for the first time, you can execute the value gets changed. This is because, for the first time, the plan from the cache will be deleted once the procedure altered and a new plan will be created for the procedure. But for subsequent execution, the cntr_value never gets changed as the object has already been cached.


SELECT cntr_value FROM sys.dm_os_performance_counters WHERE counter_name = 'Temp Tables Creation Rate'
EXEC  Test_TempCaching
SELECT cntr_value FROM sys.dm_os_performance_counters WHERE counter_name = 'Temp Tables Creation Rate'

Conclusion:
If you see more high temp tables creation rate in your application, you may find the procedures and see if you can take advantage of the above scenario.
There is a caveat – statistics with temp objects(I am not covering here),you may need to verify and confirm the changes thoroughly to make sure you do not have any other performance issues.