- Ever felt the need for knowing who is logging on to your SQL Server and at what time?
- Ever felt the need to restrict specific users for certain time-period or firing a trace to track down user activity?
- Ever felt like limiting the number of concurrent connections for specific users?
Well, you can do all that now with Logon Triggers.
Logon Trigger allows you to fire a T-SQL, or a stored procedure in response to a LOGON event. You may use logon trigger to audit and control users by tracking login activity, restricting logins from accessing SQL Server, or by limiting the number of sessions for specific logins. Logon Triggers are fired only after a login is successfully authenticated but just before the user session is actually established.
All messages originating from inside the trigger (ex: messages, errors) using the PRINT statement are sent to the SQL Server error log.
NOTE: If the user authentication fails for any reason, then the Logon triggers are not fired.
Below example shows you how you can create a Logon trigger and send a message to SQL Server error log as soon as any user logs in:
Creating a LOGON Trigger
CREATE TRIGGER OPS_LOGON ON ALL SERVER AFTER LOGON AS BEGIN PRINT SUSER_SNAME() + 'HAS JUST LOGGED IN TO '+UPPER(LTRIM(@@SERVERNAME))+ 'SQL SERVER AT '+LTRIM(GETDATE()) END GO
Limit a Login to 5 Concurrent Sessions
CREATE TRIGGER OPS_LOGON ON ALL SERVER WITH EXECUTE AS [Microsoft\SALEEM] FOR LOGON AS BEGIN IF ORIGINAL_LOGIN()= [Microsoft\SALEEM] AND (SELECT COUNT(*) FROM SYS.DM_EXEC_SESSIONS WHERE IS_USER_PROCESS = 1 AND ORIGINAL_LOGIN_NAME = [Microsoft\SALEEM]) > 5 ROLLBACK; END;
Querying all Server Level Triggers
SELECT * FROM SYS.SERVER_TRIGGERS GO
Dropping or Deleting OPS_Logon Server Level Trigger
DROP TRIGGER OPS_LOGON ON ALL SERVER GO