DBA Diaries

Thoughts and experiences of a DBA working with SQL Server and MySQL

Using DBCC SQLPERF

Posted on October 19, 2013 Written by Andy Hayes 3 Comments

dbcc sqlperfThere are a number of uses for the DBCC SQLPERF command. I touched upon one of them in my last post on how you can use the command to obtain information about transaction log growth.

This handy little DBCC command has been around for a while now. So lets look at the others ways you use it….

  1. Viewing wait statistics data
  2. Clearing wait statistics data
  3. Clearing latch wait statistics data
  4. Obtaining log space size and used data

Syntax and examples for DBCC SQLPERF


--syntax
DBCC SQLPERF(option)
WITH NO_INFOMSGS


--example uses

DBCC SQLPERF(waitstats)

DBCC SQLPERF('sys.dm_os_latch_stats' , CLEAR)

DBCC SQLPERF('sys.dm_os_wait_stats' , CLEAR)

DBCC SQLPERF(logspace)


Looking at each use case for DBCC SQLPERF in turn….

DBCC SQLPERF(waitstats)

There are newer ways to do this by reading from sys.dm_os_wait_stats but it can be used to obtain wait statistics from your SQL Server.

I wrote about waits stats and wait types in an earlier post so have a read of that if you want to know more about them.

DBCC SQLPERF(‘sys.dm_os_wait_stats’ , CLEAR)

This resets the wait statistics data that your SQL Server has collected since it was last restarted – very handy for performance tuning.

DBCC SQLPERF(‘sys.dm_os_latch_stats’ , CLEAR)

Latches are internal resource locks and wait data is recorded in a similar way to wait type data. To clear out the latch waits that your SQL Server has collected since it was last restarted then run this command.

DBCC SQLPERF(logspace)

Finally, in order to get log space data on how large your transaction logs are and what percentage of them is in use then execute this command. My last post was about this dbcc command, you can view that here.

Permissions needed for DBCC SQLPERF

In order to run this command, your user needs VIEW SERVER STATE permission on the server.

Filed Under: All Articles, SQL Server Administration Tagged With: dbcc, sql server

Monitoring SQL Server Transaction Log Growth Using DBCC SQLPERF(logspace)

Posted on October 13, 2013 Written by Andy Hayes 5 Comments

monitor transaction log growth with dbcc sqlperf(logspace)For this article, I am using DBCC SQLPERF(logspace) to get size information about the transaction logs. I hope you will find this post useful in helping to monitor the growth of your transaction logs.

The idea here is to capture and store the growth information at set intervals. This can provide a way to report on how much the logs are growing by and when. Reports are then delivered by an automated process.

If you issue DBCC SQLPERF(logspace), you will see output similar to the following:

dbcc sqlperf(logspace)

The output is self explanatory where for each database you can see the size of the transaction log and how much of it is in use currently.

So this is useful information on its own and even more useful if it can be captured on a regular basis and reported on.

So I wrote some T-SQL to do this and wrapped it up inside a stored procedure.

Firstly I will create a table to store the output of DBCC SQLPERF(logspace).

CREATE TABLE dbo.TransLogMonitor
(
LogID INT PRIMARY KEY IDENTITY(1,1),
LogDate DATETIME NOT NULL DEFAULT(GETDATE()),
DatabaseName VARCHAR(100) NOT NULL,
LogSizeMB DECIMAL(18, 2) NOT NULL,
LogSpaceUsed DECIMAL(18, 2) NOT NULL,
[Status] INT NOT NULL
)

CREATE INDEX IX_LogDate ON TransLogMonitor(LogDate);

Now this is the bit where we capture the output.

INSERT INTO TransLogMonitor(DatabaseName, LogSizeMB, LogSpaceUsed, [Status])
EXEC ('DBCC SQLPERF(logspace)')

DBCC execution completed. If DBCC printed error messages, contact your system administrator.
(5 row(s) affected)

Now run the code and then have a look at the data in your new table and it will look very similar to the output from running DBCC SQLPERF(logspace) to screen but with a couple of extra columns for the primary key values and the date that the data was inserted. The LogDate values are obviously very valuable enabling you to report on the data within any date range.

So lets say I wanted a report made available each day which gave me a comparison between yesterday’s and today’s growth, you could write something like this having the data collector running once a day.

DECLARE @Yesterday DATE = CONVERT(DATE, GETDATE()-1);
DECLARE @Today DATE = CONVERT(DATE, GETDATE());

SELECT COALESCE(Y.DatabaseName,T.DatabaseName) AS DatabaseName
, T.LogSizeMB AS TodayLogSizeMB
, Y.LogSizeMB AS YestLogSizeMB
, T.LogSizeMB - Y.LogSizeMB AS SizeMBDiff
, T.LogSpaceUsed AS TodayLSpaceUsed
, Y.LogSpaceUsed AS YestLSpaceUsed
, T.LogSpaceUsed - Y.LogSpaceUsed AS UsedDiff
FROM dbo.TransLogMonitor Y
FULL OUTER JOIN dbo.TransLogMonitor T ON T.DatabaseName = Y.DatabaseName
WHERE CONVERT(DATE, Y.LogDate) = @Yesterday AND CONVERT(DATE, T.LogDate) = @Today
ORDER BY TodayLogSizeMB DESC

Returning this output:

dbcc sqlperf(logspace)

Delivering the DBCC SQLPERF(logspace) report

Providing that you are running a version of SQL Server that is able to send email then you could deliver the report via this method. This example has attached the output as a text file but you can also format it up nicely as HTML if you want to.

EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'DB1'
, @recipients = 'your smtp email address goes in here'
, @subject='Transaction Log Space Consumption Report'
, @query = 'EXEC DBName.dbo.usp_stored_procedure_name'
, @attach_query_result_as_file = 1

To wrap this up….

Once you have the code written, it could be scheduled to your preference. As I mentioned, this example is to run daily and compares yesterday and today but you could run it hourly if you wanted to and then write some T-SQL to analyze the hours of the day when you get the most growth. You could write daily reports for the whole week, something to report on the month etc. It could be a great report to help with capacity planning.

In order to deliver this, you could send the report by scheduling with SQL Server Agent, an SSIS package, Reporting Services or SQLCMD called from a batch file using windows task scheduler.

It’s really up to you 🙂

References

DBCC SQLPERF – link to documentation is here
sp_send_dbmail – link to documentation is here

Filed Under: All Articles, SQL Server Administration Tagged With: dbcc, sql server, transaction logs

Using DBCC FREEPROCCACHE to Clear SQL Server Procedure Cache

Posted on May 14, 2013 Written by Andy Hayes Leave a Comment

It is possible to clear out the entire SQL Server procedure cache using DBCC FREEPROCCACHE

The procedure cache is where SQL Server will cache execution plans after they have been compiled. The benefit of this caching is that there is no need for the execution plans to be compiled at run time. This compiling operation typically consumes resource and slows down the execution time of the query.

The obvious disadvantage of clearing out the plan cache is that all execution plans for your SQL Server instance are recompiled upon execution which may slow things down temporarily until the cache is re-populated. Great for development, give thought before executing in production.

You may be under pressure to quickly get performance back to normal but it’s better to laser target the offending queries if you have time and address accordingly. You can clear out the procedure cache for specific queries as we will see further down the post.

Running DBCC FREEPROCCACHE

DBCC FREEPROCCACHE;

…and you should be presented with the following informational message:

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

This is optional – WITH NO_INFOMSGS and will simply suppress the informational message above.

DBCC FREEPROCCACHE WITH NO_INFOMSGS;

Upon executing, messages with be written to the SQL Server error log for each cache store in the plan cache.

Here is an example:

SQL Server has encountered 1 occurrence(s) of cachestore flush for the ‘Object Plans’ cachestore (part of plan cache) due to ‘DBCC FREEPROCCACHE’ or ‘DBCC FREESYSTEMCACHE’ operations.

Using DBCC FREEPROCCACHE to clear specific execution plans from the cache

You first need to pinpoint the identifier of the execution plan which you want to clear out of the cache. This is known as a “plan handle” and you can find the plan handles and the cached SQL by issuing a query against sys.dm_exec_cached_plans and sys.dm_exec_sql_text

SELECT cp.plan_handle, st.text
FROM sys.dm_exec_cached_plans cp
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS st
WHERE st.text LIKE N'{3a76cbff1b5ce5ace3bd34bbdd68f71285d81fb9af60114c7a6db80d3a8688de}ThePlanYouAreLookingFor{3a76cbff1b5ce5ace3bd34bbdd68f71285d81fb9af60114c7a6db80d3a8688de}'

So here I will clear a plan from the cache, firstly by running this query to get the plan inserted to the plan cache.

SELECT TOP 1 * FROM Person.Person;

Now I will attempt to find the plan_handle for the execution plan.

SELECT cp.plan_handle, st.text
FROM sys.dm_exec_cached_plans cp
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS st
WHERE st.text LIKE '{3a76cbff1b5ce5ace3bd34bbdd68f71285d81fb9af60114c7a6db80d3a8688de}Person.Person{3a76cbff1b5ce5ace3bd34bbdd68f71285d81fb9af60114c7a6db80d3a8688de}'

dbcc freeproccache clear sql server plan cache

So I can see that I want to clear out the cache for the second row as displayed in the screenshot.

So add the plan_handle and say bye to that query plan. 🙂 (The plan handle has been deliberately shortened in the code below otherwise my CMS has trouble displaying it 🙂 )

DBCC FREEPROCCACHE (0x060006002FE61B1D40FDAFF501000000010000....);

Filed Under: All Articles, SQL Server Performance Tagged With: dbcc, performance, sql server

Reset Table Identity Value Using DBCC CHECKIDENT RESEED

Posted on September 23, 2012 Written by Andy Hayes 1 Comment

DBCC CHECKINDENT RESEED can be used to reset a tables identity value on a column.

On the official Microsoft page about it, it reads

“Checks the current identity value for the specified table in SQL Server 2016 and, if it is needed, changes the identity value. You can also use DBCC CHECKIDENT to manually set a new current identity value for the identity column.”

This was an interesting find but when you might you use it?

I will create a small table to demonstrate how to use this.

T-SQL:

CREATE TABLE Table_1
(
ID INT IDENTITY(1,1) NOT NULL,
DateAdded DATETIME NOT NULL
)

Insert some rows….

INSERT INTO Table_1(DateAdded)
VALUES(GETDATE());
INSERT INTO Table_1(DateAdded)
VALUES(GETDATE());
INSERT INTO Table_1(DateAdded)
VALUES(GETDATE());
INSERT INTO Table_1(DateAdded)
VALUES(GETDATE());
INSERT INTO Table_1(DateAdded)
VALUES(GETDATE());

Check the current value which produces the below output….

DBCC CHECKIDENT ('Table_1', NORESEED);

Checking identity information: current identity value ‘5’, current column value ‘5’.
DBCC execution completed. If DBCC printed error messages, contact your system administrator.

dbcc checkident noreseed

Now we will reset the identity value so that the next time we insert data, the value will be 10….

DBCC CHECKIDENT('Table_1', RESEED, 9);

Checking identity information: current identity value ‘5’.
DBCC execution completed. If DBCC printed error messages, contact your system administrator.

dbcc checkident reseed

Add another row and check identity value. The row inserted will have a value of 10….

INSERT INTO Table_1(DateAdded)
VALUES(GETDATE());

Checking identity information: current identity value ’10’, current column value ’10’.
DBCC execution completed. If DBCC printed error messages, contact your system administrator.

Scenarios when you might use DBCC CHECKIDENT

It’s already clear what the function of this is but when might you use it?

I’m nervous at the thought of this being called in a production environment but in a dev environment, sure it could come in handy if you need to reset things to a known state.

TRUNCATE TABLE is a command which will enable you to delete all rows from a table and at the same time, reset the identity value. However you need permission to be able to do this and it will only work if the table is not referenced by a foreign key constraint. This is when DBCC CHECKIDENT is useful.

Some notes about DBCC CHECKIDENT

  • You need to be a db_owner (dbo) of the database. If you are not a dbo, you would need permission to execute on behalf of dbo using WITH EXECUTE AS
  • Reseed as (n – 1). So if you wanted a value of 5 as your next value, reseed using 4
  • Setting a value which is less than values which are already in the table will result in unique constraint violations as soon as the value inserted hits a value which already exists in the table.
  • Data type limits apply, you cannot exceed the max value of a TINYINT for example when reseeding.
  • Running it on an empty table produces a change in behaviour. The following demonstrates this….
DBCC CHECKIDENT('Table_1', RESEED, 0);

Now after running that DBCC statement and then adding a row, you would expect the next value to be a 1 but it’s not….

INSERT INTO Table_1(DateAdded)
VALUES(GETDATE());

DBCC CHECKIDENT ('Table_1', NORESEED)

Checking identity information: current identity value ‘0’, current column value ‘0’.
DBCC execution completed. If DBCC printed error messages, contact your system administrator.

This is normal behaviour however. If the table is empty, then the next value is the reseed value as opposed to the reseed value plus the increment value.

Filed Under: All Articles, SQL Server Administration Tagged With: dbcc, sql server

  • 1
  • 2
  • Next Page »

Categories

  • All Articles (82)
  • Career Development (8)
  • MySQL Administration (18)
  • MySQL Performance (2)
  • SQL Server Administration (24)
  • SQL Server News (3)
  • SQL Server Performance (14)
  • SQL Server Security (3)
  • SQL Tips and Tricks (19)

Top 10 Popular Posts

  • Using sp_change_users_login to fix SQL Server orphaned users
  • How to shrink tempdb
  • MySQL SHOW USERS? – How to List All MySQL Users and Privileges
  • How to Transfer Logins to Another SQL Server or Instance
  • How to Delete Millions of Rows using T-SQL with Reduced Impact
  • T-SQL – How to Select Top N Rows for Each Group Using ROW_NUMBER()
  • New T-SQL features in SQL Server 2012 – OFFSET and FETCH
  • How to Kill All MySQL Processes For a Specific User
  • Using exec sp_who2 to help with SQL Server troubleshooting
  • How to move tempdb

Recent Posts

  • How to Setup MySQL Master Master Replication
  • How To Use SQL to Convert a STRING to an INT
  • How to set up MySQL Replication Tutorial
  • How to Use SQL CASE for Conditional Logic in Your SQL Queries
  • Using ISNULL in SQL Server to Replace NULL Values

Search

Connect

  • Twitter
  • Facebook
  • Google+
  • RSS

About

  • Cookie Policy
  • Disclaimer
  • About
Copyright © ‘2021’ DBA Diaries built on the Genesis Framework

This site uses cookies. We assume you are happy with cookies but click the link if you are not. Close