2009-04-13

Last time statistics were done?

-- view the date the statistics were last updated:
select 'index Name' = i.[name],
'Statistics Date' = stats_date(i.[object_id], i.index_id)
from sys.objects o
inner join sys.indexes i
on o.name = 'Employee'
and o.[object_id] = i.[object_id]
-- if you need to update all the indexes:


update statistics HumanResources.Employee
with fullscan

2009-04-07

Find fragmentation (globally)

Ok. As I am working through this certification, it is getting easier.
this is a global way to work with indexes.

select *
into #t
from sys.dm_db_index_physical_stats(null, null, null, null, null)


Then you can find the database name by selecting this:

select db_name(database_id) from #t


if you want to sift through all the gobbldygook, you can filter out non-fragmented items:

select db_name(database_id) from #t
where
fragment_count > 0 and
avg_fragmentation_in_percent > 0

... and you can build and analyze as you go.
Happy hunting!

2009-04-01

Find Fragmentation on a specific table

-- How to find fragmentation (yet another way)
declare @MyDatabase sysname,
@MyTable sysname

set @MyDatabase = 'Adventureworks'
set @MyTable = 'HumanREsources.Employee'
select
index_id,
avg_fragmentation_in_percent,
avg_page_space_used_in_percent
from
sys.dm_db_index_physical_stats(db_id(@MyDatabase),
object_id(@MyTable),
null,
null, 'detailed')
where
index_id <> 0


also, find row-level i/o, locking and latching issues and access method activity:
by the way, this is an excerpt from SQL Server Books online
DECLARE @db_id smallint;
DECLARE @object_id int;
SET @db_id = DB_ID(N'AdventureWorks');
SET @object_id = OBJECT_ID(N'AdventureWorks.Person.Address');
IF @db_id IS NULL
BEGIN;
PRINT N'Invalid database';
END;
ELSE IF @object_id IS NULL
BEGIN;
PRINT N'Invalid object';
END;
ELSE
BEGIN;
SELECT * FROM sys.dm_db_index_operational_stats(@db_id, @object_id, NULL, NULL);
END;
GO