There are four main points to consider:
- What do I need to accomplish
- Cost of implementation
- Cost of rollback/removal
- Performance impact
I'm keeping this blog as a repository for SQL tips and tricks I have learned over my time working with SQL Server.
USE [AdminDB] CREATE TABLE dbo.tblLogonTrackingThen the trigger itself:
(
stblLogonTrackingID int primary key clustered identity (1,1) NOT NULL,
login_time datetime NOT NULL,
[host_name] varchar(50) NOT NULL,
[program_name] varchar(100) NOT NULL,
[EventData] VARCHAR(15) NULL
) ON [PRIMARY]
USE [master]I've created the trigger 'ON ALL SERVER' since I need to use it for several databases/applications. But it could be created just for a single database by running it on the required db and using 'ON DATABASE'. Due to the nature of the applications I've also included a NOT EXISTS statement so I don't record the same user logging in and out successively. The goal here is to know that someone is accessing the database in out of hours periods, not necessarily how many times they are accessing the system. But that should be relatively easy to modify based on requirements.
ALTER TRIGGER trLogonTracking
ON ALL SERVER
FOR LOGON
AS
BEGIN
IF DATEPART(HH, getdate()) NOT BETWEEN 9 AND 17
OR (DATEPART(DW,GETDATE()) IN (1,7))
BEGIN
INSERT INTO AdminDB.dbo.tblLogonTracking (login_time,[program_name],[host_name],[EventData])
SELECT GETDATE(),APP_NAME(),HOST_NAME(),
EVENTDATA().value('(/EVENT_INSTANCE/ClientHost)[1]','NVARCHAR(15)')
WHERE ORIGINAL_LOGIN() IN ('AppLogin1','AppLogin2')
AND (APP_NAME() LIKE '%app1_name %' OR APP_NAME() LIKE '%app2_name%')
AND NOT EXISTS (SELECT 1 FROM AdminDB.dbo.tblLogonTracking as a
WHERE DATEDIFF(mi,GETDATE(),a.login_time) > 60
AND APP_NAME() = a.[program_name]
AND HOST_NAME() = [host_name])
AND EVENTDATA().value('(/EVENT_INSTANCE/ClientHost)[1]','NVARCHAR(15)') NOT LIKE '10.1.%'
END
END