How to send email from execute sql task? - sql-server

How can i send email if execute sql task get executed and loads a table. so, if table is loaded with any record send email, if not loaded no email.
Appreciate any help.

after that task add another task that checks if there are any rows in the table
something like
IF EXISTS (SELECT 1 FROM Yourtable)
BEGIN
EXEC msdb.dbo.sp_send_dbmail ---------
END
read up on sp_send_dbmail here: http://msdn.microsoft.com/en-us/library/ms190307.aspx

its cool i solved it. i used two execute sql tasks and first one for loading data into the table, second one counting the records and i put variable on green arrow #MyVariable > 0 and connected the send mail task.
Thanks to all.

Related

SQL Server send email when query result is not empty

I need to send an email from SQL Server when a query result set holds records. The query can be based on a lot of logic with joins between several tables.
Please send me in the right direction (views, triggers on views, SQL Server agent job..?).
using sp_send_DBmail as documented here(https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-send-dbmail-transact-sql?view=sql-server-2017) for all parameter options
declare #bodytext varchar(max)= '<b>Hey look I wrote something</b>'
if(Exists(select 1 from ....))
begin
EXEC msdb.dbo.sp_send_dbmail
#recipients='xyz#gmail.com',
#subject='ATTN! There are records',
#body=#bodytext,
#body_format='HTML',
#from_address='DBA <kl#domain.com>',
#reply_to='xyz#gmail.com'
end
take a look at Vsql-email app (you can search on google, I think I'm not allowed to post the direct link here), it has this option to not send the email if the query has 0 rows, and you can send the email as HTML formatted body and/or as excel attachment and no need to enable and configure Database Mail in SQL Server and write code for HTML formatting.

How do I find out which stored procedure sent an email?

We have an email that is being sent to us from SQL Server that we want to stop. How do I find out which stored procedure is sending that email so I can modify/disable it?
What I've tried
Searching through all stored procedures via sys.all_sql_modules for words in the email subject and body text.
SELECT *
FROM sys.all_sql_modules AS asm
INNER JOIN sys.objects AS o ON o.object_id = asm.object_id
WHERE asm.definition LIKE '%*[subject/body words]*%'
I've looked through the sysmail_* tables and I have found my email being sent but I haven't found a way to trace it back to a stored procedure.
SELECT TOP 100 *
FROM msdb.dbo.sysmail_sentitems AS ss
WHERE ss.subject LIKE '%keyword%'
you could search sys.modules for the string
sp_send_dbmail
Then look at all the hits. OTOH how do you know it was sent from a PROC at all? It could be an ad-hoc query calling sp_send_dbmail, or an agent job, or something else.
I would simply create a server side trace and with filter for textdata like '%sp_send_dbmail%'
Then just run the trace for 1 day, and then you can figure out which SP is sending out db mail. This way, you can surely find out whether the email is sent via a stored proc or via an ad-hoc query (like inside a SSRS report?) or from a job step.

SSIS 2008 task dependency configuration

I have a package that before any ETL happens it checks source tables to ensure they exist. If they do not exist, it sends me an email via send mail task then waits 30 mins via execute sql task, before trying again via for loop container.
I'm trying to configure this package so if it loops, and then finally succeeds I get an email telling me succeeded. But I don't want an email EVERY time it succeeds, just if the loop occurred and then finished.
So if the source data does not exist, do not proceed to next container, instead send me an email, wait 30 mins, and try again. If finally the source tables appear, then proceed to next container, and send me an email.
If I understand your steps correctly, you have an Execute SQL Task which checks for the schema, if schema is not present sends an email and then waits for 30 mins and loops back again to check the schema. You can add a boolean variable say SendSucessEmail which can be set with something like this
DECLARE #SendSucessEmail BIT = 0
WHILE NOT EXISTS(
SELECT TOP 1 1
FROM sys.tables where name = 'checktable'
)
BEGIN
SET #SendSucessEmail = 1
WAITFOR DELAY '00:30:00'
END
SELECT #SendSucessEmail AS SucessEmailVariable
In your package, You can get this value and use it to send your email.

CASE Statement in SQL Server to get output I need

So a friend of mine told me to check the almost 5 million email addresses that got 'Hacked' on Gmail.
I downloaded the file a text file, with almost 5 million emails (4804288). I figured I'd just open it in my text editor and Ctrl+F my email address. Well it took forever to just open the .txt document and it crashed. I then exported it to Excel but it has a limit of 1 million+ rows. Since I'm studying SQL I figured I'll just load it into SQL Server and query it creating a stored procedure. It should be cool.
So.. what did I do?
Created a table called 5Mil.
And bulk inserted the info from the .txt file:
BULK INSERT [dbo].[5Mil]
FROM 'C:\list\google.txt'
WITH (fieldterminator = ',', rowterminator = '#gmail.com')
GO
First question, since the txt file had one line per email without a ',' at the end the only way I could load the info was using the rowterminator = '#gmail.com' which truncated '#gmail.com' and left only the username part of the email.
Maybe someone can help me understand how to import the information including the #gmail.com.
I was able to import the email addresses 1 per row. total rows 4804288.
So far so good.
I am currently learning CTE's so I figured I'd apply this to my stored procedure.
This is what I did.
CREATE PROC googlemails
#email VARCHAR(MAX)
AS
WITH CTE AS
(
SELECT Emails
FROM dbo.[5Mil]
WHERE Emails LIKE '%'+#email+'%'
)
SELECT
CASE
WHEN Emails IS NOT NULL
THEN Emails
ELSE 'you are safe'
END AS 'Google Email'
FROM CTE
When I run the procedure and it finds emails it properly lists them.
But when I put an email address that's not in the list I get
Google Email
Blank. What I want is to be able to show 'You are safe' letting the user know that your email was not part of the 5 Mill 'hacked'.
What would be the proper way to use the CASE statement here. Or like always other ways of accomplishing this task. For learning purposes.
Thank you.
select case when exists( select 1 from 5MIL WHERE Emails LIKE '%'+#email+'%')
then 'hacked'
else 'not hacked' end
CTE not appropriate here; they're mostly for simplifying large queries and for recursive queries.
As I understand it you now have a table called 5Mil with one column called Email each with a username without the "#gmail.com". It is unnecessarily redundant to append "#gmail.com" to each one.
Soooo.... why not just search for the username part? Using a LIKE '%email%' is slow and inefficient. Much simpler to just to do this in your stored procedure (similar to dudNumber4's answer but don't use "LIKE"):
--SET #Email = 'someusername' -- note no "#gmail.com"
if EXISTS(SELECT 1 from 5Mil where Email = #Email)
SELECT 'Hacked'
ELSE
SELECT "Not hacked"
if you create an index on 5Mil.Email the search will be almost instant.

simple way to know the updates in table

hi just wanted to know is there any way to know if any update happens in column like Ex:Author ID, and once its update happen in column is there any simple way so that all the managers should know that new author update happen in Database or via email, i am a newbie, if anyone help me step by step on this it will be really greatful for me at the appraisel time please help on this..
Thanks
aaru
You need to create a trigger
CREATE TRIGGER reminder2
ON Sales.Customer
AFTER INSERT, UPDATE, DELETE
AS
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'AdventureWorks Administrator',
#recipients = 'danw#Adventure-Works.com',
#body = 'Don''t forget to print a report for the sales force.',
#subject = 'Reminder';
However, using the sp_send_dbmail is not appropriate from within a stored procedure as it will slow down the update of a row. Meaning that everytime an update is done to the row, it will have to wait until the email is sent.
Instead, you should use another table to store the action on the row, have a batch job or a service scan the table and send the email itself.
For example:
CREATE TRIGGER SendEmailOnUpdate
ON Author
AFTER UPDATE
AS
INSERT INTO Notification(AuthorId) VALUES(updated.AuthorId);
The create a Windows Service that scan the table Notification and take one row at a time and send an email against the data it contains.
See MSDN for more information about triggers.
You might want to use a Sql Trigger to create a log of all the updates that occur on certain tables and fields.
You may want to use the UPDATE() function (lookup in books on-line) within the trigger to test just for changes to the field you are interested in (i.e. Author)
Actually, using sp_send_dbmail inside a trigger isn't so bad. Unlike the MAPI xp_sendmail days, sp_send_dbmail just queues up the email (essentially writing a record into a table). It will not cause the trigger to wait for the email to be sent. While SQL BOL says the sp "sends an email message", the result of a successful call is the message "Mail queued."
I am still not sure I would call it from a trigger, but I'd now consider it with dbmail.

Resources