• This is good for a basic start. I would simplify this a little - for example, I would change the dynamic query to the following:

    EXEC sp_msforeachdb 'Use ?;

    INSERT INTO #Frag (

    DBName,

    TableName,

    SchemaName,

    IndexName,

    AvgFragment

    )

    Select db_name()

    ,object_name(s.object_id) As ObjectName

    ,object_schema_name(s.object_id) As SchemaName

    ,s.avg_fragmentation_in_percent

    From sys.dm_db_index_physical_stats(db_id(), Null, Null, Null, ''Sampled'') s

    Join sys.indexes i On i.object_id = s.object_id And i.index_id = s.index_id

    Where i.index_id > 0

    And i.index_id < 255

    And s.avg_fragmentation_in_percent > 20'

    And move the ordering of the results to the cursor instead (guarantees the order will always be what I want).

    Jeffrey Williams
    “We are all faced with a series of great opportunities brilliantly disguised as impossible situations.”

    ― Charles R. Swindoll

    How to post questions to get better answers faster
    Managing Transaction Logs