• 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

1CREATE TRIGGER OPS_LOGON
2   ON ALL SERVER
3   AFTER LOGON
4   AS
5   BEGIN
6      PRINT SUSER_SNAME() + 'HAS JUST LOGGED IN TO '+UPPER(LTRIM(@@SERVERNAME))+ 'SQL SERVER AT '+LTRIM(GETDATE())
7   END
8   GO

Limit a Login to 5 Concurrent Sessions

1CREATE TRIGGER OPS_LOGON
2   ON ALL SERVER WITH EXECUTE AS [Microsoft\SALEEM]
3   FOR LOGON
4   AS
5   BEGIN
6      IF ORIGINAL_LOGIN()= [Microsoft\SALEEM] AND
7         (SELECT COUNT(*) FROM SYS.DM_EXEC_SESSIONS WHERE IS_USER_PROCESS = 1 AND ORIGINAL_LOGIN_NAME = [Microsoft\SALEEM]) > 5
8      ROLLBACK;
9      END;

Querying all Server Level Triggers

1SELECT * FROM SYS.SERVER_TRIGGERS
2GO

Dropping or Deleting OPS_Logon Server Level Trigger

1DROP TRIGGER OPS_LOGON ON ALL SERVER
2GO