SQLUSA.com
SQL SERVER 2008 GRAND SLAM
FREE TRIAL  CLICK HERE TO ORDER  SEARCH
SQL JOBS SQL Server Training Scripts JOB BANK
  SQL Server 2008 Training Scripts  
  SQL Server 2005 Training Scripts  
News SQL Server Articles SQL Format

How to display last statistics update date for all indexes?

Execute the following Microsoft SQL Server Transact-SQL (T-SQL) script in Management Studio (SSMS) Query Editor, SQLCMD or other client software 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

 

Order SQL 2008 GRAND SLAM Today!
SQLUSA.com Home Page
SQL Server Training at www.sqlusa.com.
SQL Server 2008 Video Training at www.sqlusa.com.
SQL Server 2005 Training Videos at www.sqlusa.com.
Microsoft SQL Server 2000 Training Videos at www.sqlusa.com.

FREE SQL & Business Intelligence / OLAP Short Videos on YOUTUBE.com

Microsoft Community Contributor 2011
Invest in Your SUCCESS!

Search SQLUSA FREE SQL Server Articles & FREE T-SQL Scripts


Copyright 2005-2011, SMI Corp. All Rights Reserved.

SQL Server 2012 is a program product of Microsoft Corporation.
SQL Server 2008 is a program product of Microsoft Corporation.
SQL Server 2005 is a program product of Microsoft Corporation.
SQL Server 2000 is a program product of Microsoft Corporation.