Both the above answers helped me . What I did to troubleshoot my issue is that instead of a query I used a stored procedure. It works fine now.
@query = 'exec DatabaseName.dbo.storedprocedure'
Question
I am trying to run the following as a job on Sql Server Agent
and I don't get an email.
I think there is something wrong with the way I am representing tables in the inner join
because if I replace the query with a simple query without joins, the task works .
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'TEST_DEV',
@recipients = 'xxx@gmail.com',
@query = ' select
Percentage = CONVERT(DECIMAL(10,1),100 - (CAST(COUNT(DISTINCT case when PD.Exception != ' ' then PD.Id END) as float)/CAST(COUNT(PD.Id) as float)*100))
from
DataBaseName.dbo.Product P INNER JOIN DataBaseName.dbo.LogProduct PD
ON P.LogId = PD.LogId
WHERE
ResponseTime < GETDATE() and RequestTime > DATEADD(MINUTE, -150, GETDATE())
' ,
@subject = 'Test',
@attach_query_result_as_file = 1 ;
Solution 3
Both the above answers helped me . What I did to troubleshoot my issue is that instead of a query I used a stored procedure. It works fine now.
@query = 'exec DatabaseName.dbo.storedprocedure'
OTHER TIPS
I use joins in my @query parameter all the time without error. The fact that you don't get an email sent is typically an indication that the query did not parse successfully at run time.
Does the query, with joins, run in SSMS directly? You might consider creating a variable @ResponseTime TYPE??? and SETing the value of the Variable prior to the send_dbmail and then simply passing that value in replacing the syntax with the @ResponseTime
I did notice a formatting issue. You need to use '' to escape a quote '. This might be your first issue with your query.
If you have Adventure Works installed, run the below query from my database mail blog entry. Just replace the profile name and recipients mail address. This will test the sp_send_dbmail() function.
-- Send with query results as an attachment
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'The Public Profile',
@recipients = 'john@craftydba.com',
@query = 'SELECT COUNT(*) FROM AdventureWorks2008R2.Production.WorkOrder
WHERE DueDate > ''2006-04-30''
AND DATEDIFF(dd, ''2006-04-30'', DueDate) < 2' ,
@subject = 'Work Order Count',
@attach_query_result_as_file = 1 ;
GO
If this does work, then test your query in SSMS to make sure you are getting results.