SQL Server Statistics Maintenance Job
Posted at Tuesday, May 20, 2008
I use the following job to augment SQL Server's auto statistics create/update functionality:
create_update_statistics.sql
You can adjust this to fit your needs and implement as part of your Maintenance Plans and/or run from a batch file, such as:
create_update_statistics.bat
create_update_statistics.sql
sp_MSforeachdb @command1='
USE ?;
IF NOT ("?" IN ("model","msdb","master","tempdb"))
BEGIN
EXEC sp_createstats;
DECLARE @tbls TABLE (rowId INT IDENTITY(1,1), tblschema NVARCHAR(128), tblname NVARCHAR(128));
DECLARE @stmt NVARCHAR(2000), @rowId INT, @maxRowId INT, @tblschema NVARCHAR(128), @tblname NVARCHAR(128);
INSERT INTO @tbls (tblschema, tblname)
SELECT table_schema, table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_type="BASE TABLE";
SELECT @rowId = MIN(rowId), @maxRowId = MAX(rowId) FROM @tbls;
WHILE @rowId <= @maxRowId
BEGIN
SELECT @tblschema = tblschema, @tblname = tblname FROM @tbls WHERE rowId = @rowId;
SET @stmt = "UPDATE STATISTICS " + "[" + @tblschema + "].[" + @tblname + "];";
PRINT "?: " + @stmt;
EXECUTE (@stmt);
SET @rowId = @rowId + 1;
END
END
';
You can adjust this to fit your needs and implement as part of your Maintenance Plans and/or run from a batch file, such as:
create_update_statistics.bat
sqlcmd -S PRIVATE-E3A52F5\SS1 -E -i create_update_statistics.sql -o create_update_statistics.out
notepad.exe create_update_statistics.out
Labels: SQL Server, Statistics
