Maybe I am missing something or lack some releveant experience in this area, but i see the following code:
FROM SYS.DM_DB_INDEX_USAGE_STATS AS S
INNER JOIN SYS.INDEXES AS I
ON I.[OBJECT_ID] = S.[OBJECT_ID]
AND I.INDEX_ID = S.INDEX_ID
To me, it seems like joining between these two tables is an error.
works over all databases and has a database_id
Without explicit filtering on the database name, you match index IDs from other databases to the current database, and thus gather the wrong usage statistics. Anyway, please check to see if I am right!
I expected the following where clause to be present and the code executed for each database on a server:
s.database_id = db_id()