hi experts, I want to only send the email If Rows Are Returned. But the report is being sent even if row count is zero for some reason.
ANy ideas? Thanks
DECLARE @currDate Date = GETDATE();
DECLARE @30DaysFromNow Date;
DECLARE @xml NVARCHAR(MAX)
DECLARE @body NVARCHAR(MAX)
Set @30DaysFromNow = DateAdd(Day, +30, @currDate)
SET @xml = CAST((SELECT dbo_Orgs_1.Name AS 'td', '', Orgs.Name AS 'td', '', ViewCWTContracts.EffectiveStartDT AS 'td', '', ViewCWTContracts.EffectiveEndDT AS 'td', ''
FROM Orgs INNER JOIN (ViewCWTContracts INNER JOIN Orgs AS dbo_Orgs_1 ON ViewCWTContracts.CarrierOrgId = dbo_Orgs_1.Id) ON Orgs.Id = ViewCWTContracts.ParentOrgId
GROUP BY dbo_Orgs_1.Name, Orgs.Name, ViewCWTContracts.EffectiveStartDT, ViewCWTContracts.EffectiveEndDT
HAVING (((ViewCWTContracts.EffectiveEndDT) < @30DaysFromNow And (ViewCWTContracts.EffectiveEndDT) > @currDate))
FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX));
If @@ROWCOUNT > 0
SET @body ='
TMS 2 email sarah cwt contracts ending in 30 days
'SET @body = @body + @xml +'
Name1 | Name2 | StartDT | EndDT |
---|
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'MyProfile',
@body = @body,
@body_format ='HTML',
@recipients = 'my email;',
@subject = 'subject';