I have several stored procedures structured like the following:
USE [WHouse]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[pr_Alert_Dly]
AS
IF (SELECT LastRunDate FROM WHouse.dbo.AlertRunDates WHERE NameDescription = 'X' ) < (SELECT CONVERT(DATE, GETDATE()))
BEGIN
--================
--need to comment the following out if trying to re-run
UPDATE x
SET x.LastRunDate = CONVERT(DATE,GETDATE())
FROM WHouse.dbo.AlertRunDates x
WHERE [NameDescription] = 'X'
--================
--===============
--DO A LOAD OF STUFF IN HERE
--INCLUDING USING DB_SENDMAIL TO EMAIL 20 PEOPLE
--===============
END
My colleague has set up a reporting system (using procedures / SSIS) that loops every 10 minutes and as long as a stored procedure completes without an error then it is marked as complete in a control table.
What I don’t understand is even if the above throws an error why would it ever repeat the section between BEGIN / END more than once in the same batch ?
If it is not defensive enough how do defend against my colleagues system causing the same emails to get distributed every 10 minutes?!
Ultimately scrapped the pattern in the OP and have used the suggestions put forward by Aaron in the comments of the OP i.e created a
EmailQueuetable and set up a background process that loops every 5mins (via theAgent). This process scans theEmailQueuetable for any new records and sends out emails if required.