join the MSSQLTips community

Today's Site Sponsor


 

SQL Compare quickly and easily compares and synchronizes SQL Server database schemas
 



The industry standard database comparison and synchronization tool.

Execute UPDATE STATISTICS for all SQL Server Databases

Written By: Tim Ford -- 10/17/2008 -- read/post comments -- print -- Bookmark and Share

Rating: (not rated yet) Rate

Problem
If you're like me, you have a SQL Agent job in place to rebuild or reorganize only the indexes in your databases that truly require such actions.  If you rely on the standard maintenance plans in Microsoft SQL Server, a Scorched-Earth policy of rebuilding all indexes occurs.  That is whether such actions are required or not for a specific index, a rebuild of the index and all the locking and churning in the logs occurs.  That is why so many of us "roll our own" index maintenance solutions as it were.  It is also one of my biggest peeves with Microsoft - why was this not built into SQL Server 2008?  Ah, at any rate, by only maintaining indexes that are fragmented, statistics updates do not occur globally against the tables/indexes in your databases.  What we need is a quick solution for updating all the statistics for every database on our SQL Server instance. 

Solution
Before you go ahead and state the fact that you have AUTO_UPDATE_STATISTICS ON for your databases remember that does not mean that they are being updated! 

Bah! You say?  Well think about this for a second.  I've touched upon this in an earlier tip, SQL Server's engine will update the statistic when:

  • When data is initially added to an empty table
  • The table had > 500 records when statistics were last collected and the lead column of the statistics object has now increased by 500 records since that collection date
  • The table had < 500 records when statistics were last collected and the lead column of the statistics object has now increased by 500 records + 20% of the row count from the previous statistics collection date

Based upon this criteria, there will be many cases where the underlying data changes in such a way or in such levels that the statistics that exist for an index will not be indicative of the actual data in the database.  Because of this you simply can not rely on the engine to keep you statistics in check and current.  Here is a simple block of code that will iterate through all your databases in order to build the sp_updatestats command that can then be copied and pasted into a new query window for execution.  This code will work with all current and previous versions of SQL Server back through SQL 7.0.

DECLARE @SQL VARCHAR(1000
DECLARE @DB sysname 

DECLARE curDB CURSOR FORWARD_ONLY STATIC FOR 
   SELECT 
[name] 
   
FROM master..sysdatabases
   
WHERE [name] NOT IN ('model''tempdb')
   
ORDER BY [name]
    
OPEN curDB 
FETCH NEXT FROM curDB INTO @DB 
WHILE @@FETCH_STATUS 
   
BEGIN 
       SELECT 
@SQL 'USE [' @DB +']' CHAR(13) + 'EXEC sp_updatestats' CHAR(13
       
PRINT @SQL 
       
FETCH NEXT FROM curDB INTO @DB 
   
END 
   
CLOSE 
curDB 
DEALLOCATE 
curDB

On my test server this code yields the following results.

 

The next step is to copy this text, paste it into a query window in SQL Server Management Studio, then execute it against the instance.  Alternately you may choose only to execute it against select databases, but that is entirely up to you.

USE [Dummy]
EXEC sp_UpdateStats

USE [master]
EXEC sp_UpdateStats

USE [msdb]
EXEC sp_UpdateStats

USE [MSSQLTips]
EXEC sp_UpdateStats

USE [MSSQLTips_DUPE]
EXEC sp_UpdateStats

USE [Northwind]
EXEC sp_UpdateStats

USE [Sitka]
EXEC sp_UpdateStats

USE [Utility]
EXEC 
sp_UpdateStats

 

I've provided a sample of the output generated by the collection of SQL statements executed above. As you can see, the engine still will review the statistics to see if they warrant updating. It will ignore those that are acceptable and will update only the statistics that require such action. I can assure you that each of the databases in the listing above had AUTO_UPDATE_STATISTICS and AUTO_CREATE_STATISTICS both set to ON, yet the following results are indicative of statistics that can become outdated.

 

Next Steps

Readers Who Read This Tip Also Read Free Live Webcast Comment or Ask Questions About This Tip


Sponsor Information
Free SQL Server performance monitoring dashboard – Idera SQL check

Try Red Gate SQL Backup Pro for smaller, more robust SQL Server backups. Download a free trial now!

SQL Server Issues? Not sure where to turn for answers? Innovative SQL DBA consultants

Looking for SQL Server interview questions and answers?

Free whitepaper - Top 10 Things You Should Know About Optimizing SQL Server Performance


Get Our Tips Newsletter

We keep 50,000+ SQL Server professionals informed.

Red Gate Software - SQL Refactor

SQL Server Management Studio add-in SQL Refactor dramatically speeds up database development and administration of legacy SQL code by providing over a dozen code refactorings, including Layout SQL, Summarize Script, Encapsulate as SP, Smart Object Rename and more. Free 14-day trial download.

Download now!



More SQL Server Tools
SQL Compare

SQL comparison toolset

SQL defrag manager

SQL Backup

SQL Prompt




Copyright (c) 2006-2010 Edgewood Solutions, LLC All rights reserved
privacy statement | disclaimer | copyright | advertise | write for mssqltips | feedback | about
Some names and products listed are the registered trademarks of their respective owners.


CareerQandA.com | MSSharePointTips.com | MSSQLTips.com