SQL Tips #11 - Rebuilding the Query Cache and Statistics


Tuesday, 7 March 2017

This script updates the statistics for every table in the current database, forcing SQL Server to rebuild its query plans with fresh information.

The Query

EXEC sp_updatestats
SET NOCOUNT  ON
DECLARE  @SQLcommand NVARCHAR(512), @Table      SYSNAME
DECLARE curAllTables CURSOR  FOR
SELECT table_schema + '.' + table_name
	FROM   information_schema.tables
	WHERE  TABLE_TYPE = 'BASE TABLE'
OPEN curAllTables
FETCH NEXT FROM curAllTables INTO @Table
WHILE (@@FETCH_STATUS = 0)
  BEGIN
    PRINT N'UPDATING STATISTICS FOR TABLE: ' + @Table
    SET @SQLcommand = 'UPDATE STATISTICS ' + @Table + ' WITH FULLSCAN'
    EXEC sp_executesql @SQLcommand
    FETCH NEXT FROM curAllTables
    INTO @Table
  END
CLOSE curAllTables
DEALLOCATE curAllTables
SET NOCOUNT  OFF
GO

Disclaimer

These queries are provided as a guide, and are by no means perfect. I didn't write all of these - many are collated from MSDN documentation and community sources over the years.

Tags

SQL, Programming
Share with: 

Useful SQL tips - how to update statistics for every table and rebuild the query cache


Support this Site

Buy me a coffee

Developer Courses

Pluralsight - Hardcore Developer and IT Training
Skype Web SDK: Getting Started
Skype Web SDK: Audio & Video

Popular Articles

What is Kutamo?
Kilimanjaro Climb
Kilimanjaro 2015
Kilimanjaro 2013
Australian Postcodes
New Zealand Postcodes
Worldwide City Database

Favourite Links

Kilimanjaro Climbs
Kutamo Studios
Kutamo Meetings
Litzi
ErrLog.IO
Kutamo

Tags / Keywords

SQL, Programming