snippetsqlMinor
How to create login and logout trigger for client audit?
Viewed 0 times
triggercreateauditloginclientforhowandlogout
Problem
I need a table to put login and logout information for client not sysadmin,then i can use date to statistic user login/off ration...
Can anyone offer me a simple method to create login and logout trigger for audit specific client not the sysadmin,
Thanks in advance.
Can anyone offer me a simple method to create login and logout trigger for audit specific client not the sysadmin,
Thanks in advance.
Solution
You can add a simple
This will only audit logons for users not named 'sa' by virtue of the line
Alternatively, if you want to ONLY audit the login of a specific user, you could write the trigger like:
This will only record when
IF statement to your LOGON trigger, as such:USE test;
GO
CREATE TABLE LogonAudit
(
AuditID INT NOT NULL CONSTRAINT PK_LogonAudit_AuditID
PRIMARY KEY CLUSTERED IDENTITY(1,1)
, UserName NVARCHAR(255)
, LogonDate DATETIME
, spid INT NOT NULL
);
GO
GRANT INSERT ON Test.dbo.LogonAudit TO public;
GO
CREATE TRIGGER MyLogonTrigger ON ALL SERVER FOR LOGON
AS
BEGIN
IF SUSER_SNAME() <> 'sa'
INSERT INTO Test.dbo.LogonAudit (UserName, LogonDate, spid)
VALUES (SUSER_SNAME(), GETDATE(), @@SPID);
END;
GO
ENABLE TRIGGER MyLogonTrigger ON ALL SERVER;This will only audit logons for users not named 'sa' by virtue of the line
IF SUSER_SNAME() <> 'sa'Alternatively, if you want to ONLY audit the login of a specific user, you could write the trigger like:
CREATE TRIGGER MyLogonTrigger ON ALL SERVER FOR LOGON
AS
BEGIN
IF SUSER_SNAME() = 'SomeUser'
INSERT INTO Test.dbo.LogonAudit (UserName, LogonDate, spid)
VALUES (SUSER_SNAME(), GETDATE(), @@SPID);
END;This will only record when
SomeUser logs into the server.Code Snippets
USE test;
GO
CREATE TABLE LogonAudit
(
AuditID INT NOT NULL CONSTRAINT PK_LogonAudit_AuditID
PRIMARY KEY CLUSTERED IDENTITY(1,1)
, UserName NVARCHAR(255)
, LogonDate DATETIME
, spid INT NOT NULL
);
GO
GRANT INSERT ON Test.dbo.LogonAudit TO public;
GO
CREATE TRIGGER MyLogonTrigger ON ALL SERVER FOR LOGON
AS
BEGIN
IF SUSER_SNAME() <> 'sa'
INSERT INTO Test.dbo.LogonAudit (UserName, LogonDate, spid)
VALUES (SUSER_SNAME(), GETDATE(), @@SPID);
END;
GO
ENABLE TRIGGER MyLogonTrigger ON ALL SERVER;CREATE TRIGGER MyLogonTrigger ON ALL SERVER FOR LOGON
AS
BEGIN
IF SUSER_SNAME() = 'SomeUser'
INSERT INTO Test.dbo.LogonAudit (UserName, LogonDate, spid)
VALUES (SUSER_SNAME(), GETDATE(), @@SPID);
END;Context
StackExchange Database Administrators Q#50620, answer score: 5
Revisions (0)
No revisions yet.