Microsoft SQL Server 2005
Performance Tuning
Best Practices

How to display last statistics update date for all indexes?

 

Execute the following script in Query Editor to display last statistics update for all indexes in the database:

USE AdventureWorks
GO

DECLARE @SchemaName VARCHAR(255), @TableName VARCHAR(255)
DECLARE @AllTables TABLE(
TableName VARCHAR (255) collate database_default,
SchemaName VARCHAR(127) collate database_default )

DECLARE @TablesStats TABLE (
ID int IDENTITY(1,1)
, SchemaName sysname null
, TableName sysname
, IndexName sysname
, LastUpdate datetime
)

INSERT INTO @AllTables
SELECT t.name, s.name
FROM sys.tables t
JOIN sys.schemas s
ON t.schema_id = s.schema_id

DECLARE curTable CURSOR FOR
SELECT s.name, s.name + '.' + t.name
FROM sys.tables t
JOIN sys.schemas s
ON t.schema_id = s.schema_id

OPEN curTable;
FETCH NEXT FROM curTable INTO @SchemaName, @TableName;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @TableName = REPLACE(@TableName, '[','');
SET @TableName = REPLACE(@TableName, ']','');

IF EXISTS(SELECT OBJECT_ID FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(@TableName))
BEGIN
PRINT @SchemaName +', '+ @TableName
INSERT @TablesStats ( SchemaName, TableName, IndexName, LastUpdate)
SELECT @SchemaName, @TableName,
[Index] = isnull(i.name,''), LastDate=STATS_DATE(i.object_id, i.index_id)
FROM sys.objects o
join sys.indexes i
on o.object_id = i.object_id
join sys.schemas s
on s.schema_id = o.schema_id
WHERE s.name+'.'
+ o.name = @TableName
END

FETCH NEXT FROM curTable INTO @SchemaName, @TableName;
END;
CLOSE curTable;
DEALLOCATE curTable;

SELECT SchemaName, TableName, IndexName, LastUpdate
FROM @TablesStats
ORDER BY LastUpdate, SchemaName, TableName

GO

 

The Best SQL Server 2005 Training in the World
 
 
SQLUSA.com Home Page