I believe that a part of your problem is that you've hardcoded the database ID in your code at the following line.
from sys.dm_db_index_physical_stats ([font="Arial Black"]5[/font], null,null,null,'Limited') S
--Jeff Moden
Change is inevitable... Change for the better is not.