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

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

 All Forums
 SQL Server 2005 Forums
 SQL Server Administration (2005)
 reindexing and emails results
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

gazzer 2004
Starting Member

12 Posts

Posted - 06/17/2010 :  08:27:06  Show Profile  Reply with Quote
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, 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'


Almighty SQL Goddess

38200 Posts

Posted - 06/17/2010 :  14:30:12  Show Profile  Visit tkizer's Homepage  Reply with Quote
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:

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server

Subscribe to my blog
Go to Top of Page
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.02 seconds. Powered By: Snitz Forums 2000