A little background - I'm trying to create a trigger that logs all logins to a table. While testing, I noticed that if I deleted the table the trigger was trying to call then I could not log on because the trigger would fail. This would cause me to have
to start SQL in single-user mode with -f parameter, and then use SQLCMD to connect then delete the trigger.
I wanted to fix the trigger so that this would not happen. Here's what I did...
Created a table msdb.MySchema.LogonHistory.
and a trigger...
CREATE TRIGGER [Tr_ServerLogon]
ON ALL SERVER WITH EXECUTE AS 'sa'
FOR LOGON
AS
BEGIN
IF OBJECT_ID('msdb.MySchema.LogonHistory', 'U') IS NOT NULL
BEGIN
INSERT INTO msdb.MySchema.LogonHistory
(DBUser, AppName, LogonTime, SystemUser)
VALUES(USER, APP_NAME(), GETDATE(), ORIGINAL_LOGIN())
END
END
This worked perfectly. If I deleted the table people could still log in.
I wanted to expand to add an ELSE statement to send an e-mail if the table didn't exist.Problem is, I received an e-mail for EVERY connection. Simply logging in to Management Studio adds 5-6 rows to my LogonHistory table. Here's the ELSE statement I added:
ELSE
BEGIN
EXEC msdb.dbo.sp_send_dbmail @profile_name = "DBMail", @recipients = 'willtron@willtron.com', @subject = 'Your table doesnt exist', @body='Error'
END
I was thinking instead of executing sp_send_dbmail I could a job with that in it. The question is can I limit the job to run only once every hour? Or is there something else I could do within the trigger? I was thinking I could check send_request_date in sysmail_mailitems where subject = 'Your table doesnt exist' and compare the send_request_date to the current GETDATE() and only e-mail if it's greater than 1 hour difference.
Just want to make sure there's not something easier/obvious that I'm missing.