Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 SQL Server Administration (2005)
 reindexing and emails results

Author  Topic 

gazzer 2004
Starting Member

12 Posts

Posted - 2010-06-17 : 08:27:06
Hi all, I am currently working on some code that will allow me to set-up a nightly task that checks the indexes of a particular Db and then emails the results to me.

Now the code I have already does seem to work, but it does not give the reults of the specified DB, it always sends the same results no matter what DB i use.

What am I doing wrong?, here is my code.

USE Database Name Goes Here

EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'Administrator',
@recipients = 'My Email',
@subject = 'Fragmentation Results',
@query = 'SELECT OBJECT_NAME(i.OBJECT_ID) AS TableName, i.name AS IndexName,indexstats.avg_fragmentation_in_percent FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, ''DETAILED'') indexstats INNER JOIN sys.indexes i ON i.OBJECT_ID = indexstats.OBJECT_ID AND i.index_id = indexstats.index_id WHERE indexstats.avg_fragmentation_in_percent > 20'


Cheers

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-06-17 : 14:30:12
It's going to be quite tricky. You are going to need to use sp_executesql, put that data into a table, and then email that table. You can not do the whole thing in @query. You can see my isp_ALTER_INDEX code to figure out what needs to be done for sp_executesql: http://weblogs.sqlteam.com/tarad/archive/2009/11/03/DefragmentingRebuilding-Indexes-in-SQL-Server-2005-and-2008Again.aspx

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page
   

- Advertisement -