Testing the result set of an sp_send_dbmail query? - sql

I'm trying to send an email using sp_send_dbmail in Sql Server 2005. I have both body text and a query being sent as an attachment.
Sometimes, however, the query will return an empty dataset.
Is there any way for me to test the results of the dataset before I send out the email, and if it has no results, not send it as an attachment.
I was thinking to maybe run the query before I send the email, and to test the results that way. Then, I'd have an if-else as follows:
if ##rowcount >0
EXEC msdb.dbo.sp_send_dbmail #recipients=#recipients_list,
#subject = #subject,
#body = #body_text, #body_format = 'HTML',
#query = #query,
#attach_query_result_as_file = 1,
#query_result_width = 4000,
#query_attachment_filename = 'Details.txt'
else
EXEC msdb.dbo.sp_send_dbmail #recipients=#recipients_list,
#subject = #subject,
#body = #body_text, #body_format = 'HTML'
But I don't think this is an efficient way to solve the problem.
Any suggestions? TIA!!

Alright, I couldn't test this on my set up at work since it appears our DBAs have blocked access to this procedure. However, I know that sp_send_dbmail will not use local variables in the calling script, but it might let you use a global temp table.
This isn't a great solution, but you could try inserting your query result set into ##tempTable, then changing the query you pass to sp_send_dbmail to select * from ##tempTable if there are > 0 rows.
That should at least be better than running the original query 2x (if it works). Remember to drop it when you're done!

Related

I don't want to send empty email if no results found

I have used cursor to loop through my values and Every time i am sending a mail but if no result found then it was sending an empty mail,How can i avoid that?
This is very much guessed logic, but based on the very vague comments and question, I imagine you simply need to use an IF. This is Pseudo-SQL, however...
DECLARE #TableHTML varchar(MAX);
SELECT #TableHTML = {Your HTML data expression};
IF #TableHTML IS NOT NULL BEGIN
EXEC sp_send_dbmail #Subject = {Your Subject},
#Body = #TableHTML,
#....;
END

Send Error Message From Sql Server to Email

I have SP in SQL Server Agent. for better knowledge lets read this example
USE msdb
EXEC sp_send_dbmail
#profile_name = 'MyProfile',
#recipients = 'Someone#something.com',
#subject = 'T-SQL Query Result',
#body = 'The result from SELECT is appended below.',
#execute_query_database = 'msdb',
#query = 'SELECT *FROM [DB_Mh].[dbo].[mMhs]',
The result is, sql sent me an email like this.
The result from SELECT is appended below.
nim fullname
---------------- ----------
443141100778 Betty
4431411006571 Jessica
4431411002372 Dian
and if an error happen, sql didn't send me any email. so with that script above sql only sent me the result of sql and didn't send me any notification if there is something wrong happen. what I want to ask is How to make sql send me email notification if an error happen with it error message.
You need to use #append_query_error parameter.
Specifies whether to send the e-mail when an error returns from the
query specified in the #query argument.
More # https://msdn.microsoft.com/en-IN/library/ms190307.aspx

Stored procedure using sp_send_dbmail to send emails to multiple recipients queried from database

Like the title says, I'm trying to make a stored procedure used to send emails to addresses stored in the database, often including multiple recipients. I've tried a few approaches to this, but I think I'm hitting a wall and would appreciate any input anyone has. The main issue I've had is querying the database for the addresses and passing that to sp_send_dbmail in a way that works.
The address table is pretty simple, looks something like this, but much larger. Both columns are varchars:
idNumber | email
__________________________
a123 | steve#test.com
a123 | carol#test.com
1-100 | mary#test.com
So if we're sending to ID number "a123", an email needs to go to both Steve and Carol.
Here's a super simple procedure. It's not verbatim since this is all on my work computer, but more of a skeletal gist of what I'm going after.
CREATE PROCEDURE sendMail
#idNumber varchar(MAX),
#subject varchar(MAX),
#body varchar(MAX)
EXEC msdb.dbo.sp_send_dbmail
#recipients = "EXEC SELECT email FROM emailTable WHERE idNumber = " + #idNumber + "';",
#subject = #subject,
#body = #body;
It throws and error; it doesn't seem to like concatenating the ID parameter into the query. I tried making a separate procedure to query emails, but passing the ID parameter to the procedure didn't seem to work either. Even if I did successfully pass the parameter and get the query to execute successfully, I'd still need to join the two results in a single string and delimit them with semicolons so they'll play nice with sp_send_dbmail. I think?
SQL wizards, how would you approach this? I'm not wildly experienced, so is there something simple and syntactic I'm doing wrong? Is my approach flawed fundamentally?
I appreciate your input. Thank you.
EDIT: Here's Kritner's working solution! Thanks a bunch!
CREATE PROCEDURE testMail2
#idNumber varchar(MAX)
AS
BEGIN
DECLARE #recipientList varchar(MAX)
SET #recipientList = (STUFF((SELECT ';' + email FROM emailTable WHERE idNumber = #idNumber FOR XML PATH(' ')),1,1,''))
EXEC msdb..sp_send_dbmail
#recipients=#recipientList,
#subject='Subject Line',
#body='Body Text'
END
You can do a query and assign the values to a variable as such:
DECLARE #myRecipientList varchar(max)
SET #myRecipientList = (STUFF((SELECT ';' + emailaddress FROM table FOR XML PATH('')),1,1,''))
This will set your #myRecipientLIst to a ";" delimited list of the recipients specified your query.
You could also do the same sort of idea with a SP, just throw them into a temp/variable table and stuff into a semi colon separated list.
EDIT:
Finally to send the mail you could do:
EXEC msdb.dbo.sp_send_dbmail
#recipients = #recipientList,
#subject = #subject,
#body = #body // ........
COMMENT EDIT:
based on your original query, your stuff query should look something like this:
DECLARE #myRecipientList varchar(max)
SET #myRecipientList = STUFF((SELECT ';' + email FROM emailTable WHERE idNumber = #idNumber FOR XML PATH('')),1,1,'')
The idea behind this is - for every email found in the email table append to #myrecipientList the email found and a semi colon.

sp_send_dbmail sending mail even if condition is false - SQL

I have an IF statement part of a stored procedure as follows :
BEGIN TRY
IF EXISTS (SELECT which I have confirmed returns no results, has a variable called from another table in the where clause)
BEGIN
EXEC msdb.dbo.sp_send_dbmail
#profile_name = #dynamic_profile,
#recipients = #dynamic_recipient,
#subject = #subjectline,
#body = #mailHTML,
#body_format = 'HTML';
END
END TRY
This is tied to a job that runs every 15mins.
Why is it keep sending me blank emails when the IF statement asks to skip the mail sending if the select returns no results?
My NOCOUNT is set to ON
Try - instead:
IF (SELECT COUNT(*) FROM whatever) > 0
BEGIN
--MAIL
END

Does anyone know why this code is sending users duplicate emails?

We have a stored procedure that is supposed to check db and select all records where sentFlag is No.
Once record(s) found, the stored proc invokes sp_send_dbmail with passed parameters and then sends an email to affected individuals.
This appears to work.
The issue we are having so far though is that each indivual is receiving duplicate emails.
Any ideas what part of this code could be causing this?
OPEN MAIL_CURSOR
FETCH MAIL_CURSOR into #mail1, #sender,#content1
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT #email = #email+';'+Email
FROM GRVRIEVANCES
WHERE sentFlag = 'No'
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'Grievances',
#recipients = #email,
#subject = 'Account Details',
#body = #content1;
FETCH MAIL_CURSOR INTO #mail1, #sender, #content1
END
CLOSE MAIL_CURSOR
DEALLOCATE MAIL_CURSOR
END
If you set email to an initial value within the loop, does the issue go away? Also, make sure you setting the sentflag to 'yes'.
WHILE ##FETCH_STATUS = 0
BEGIN
SET #email=''
SELECT #email = #email+';'+Email
Back to basics to solve this one.
Start with some debugging:
Comment out your EXEC part
Add PRINT #email in the same spot
Run the cursor and see the reults, they should be quite enlightening!
Essentially what you're doing is on every cursor execution you are building up this big ol' string of email addresses for all GRVRIEVANCES WHERE sentFlag = 'No'.