I hate cursors and it is possible to do this without one.
Create a temporary table to log your progress and update it as you send the emails out. E.g.
DECLARE @SENDTOLIST TABLE (id int identity(1,1), sendto VARCHAR(4000), done bit)
INSERT INTO @SENDTOLIST(sendto, done)
SELECT EMAIL, 0 FROM @Employee WHERE FACILITY = @FACILITY ORDER BY TSG_RECORD_ID
Then just use two loops - the outer one ensures you cover every item to be emailed and the inner one does the 200 emails
DECLARE @SENDTO VARCHAR(4000)
DECLARE @id INT
WHILE EXISTS(SELECT TOP 1 done FROM @SENDTOLIST WHERE done = 0)
BEGIN
print 'Sending 200 emails'
DECLARE @i INT = 1
WHILE @i <= 200
BEGIN
SELECT TOP 1 @SENDTO=sendto, @id = id FROM @SENDTOLIST WHERE done = 0
EXEC [sp_EmailAlert] @SENDTO,@EMAILDESC,@FACILITY
UPDATE @SENDTOLIST SET done = 1 WHERE id = @id
SET @i = @i + 1
END
print 'waiting for next slot'
END
Things to note:
The outer WHILE depends on there being a minimum of 1 item left to process - that
TOP 1
is not a typing error. This covers off the number of emails not being an exact multiple of 200.
Similarly, because I'm using a loop and not a cursor, I only want to read one record at a time. So that second
TOP 1
is also not a typing error.