Home > Ask the SQL Server Experts > Andrew Novick - Development Questions & Answers > Code trigger that captures login and system date
Ask The SQL Server Expert: Questions & Answers
EMAIL THIS

Code trigger that captures login and system date

Andrew Novick EXPERT RESPONSE FROM: Andrew Novick

Pose a Question
Other SQL Server Categories
Meet all SQL Server Experts
Become an Expert for this site


Expert advice on database administration
Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us    Add to Google


>
QUESTION POSED ON: 06 July 2005
I need code for a trigger that captures the user/login and system date after a specific column has been updated in a table.


Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us    Add to Google



RELATED CONTENT
Andrew Novick - Development
Nullable fields in a table
Connecting Visual Basic to SQL Server
Stored procedures in Crystal Reports
Storing an image file in SQL Server
Storing large amounts of data as ntext data type
Stored procedures looking at different databases
Stored procedures and remote procedure calls
Using newid in SQL Server to insert records in parent-child tables
How to use results from one stored procedure in another
How to display the XML result of 'Select For XML Explicit'

SQL Server Security
Meet compliance requirements with improved database security practices
Hardening the network and OS for SQL Server security
Securing the server and database in SQL Server
SQL Server security made simple and sensible
Blog: Protect your databases from the internal threat
Setting up SQL Server Service Broker for secure communication
The keys to database backup protection for SQL Server
Understanding transparent data encryption in SQL Server 2008
The fine line between not encrypting your databases and breach notification
Securing SQL Server with access control, login monitoring and DDL triggers

SQL Server Stored Procedures
SQL Server Mailbag: CALs, witnesses and unwanted changes
SQL Server Mailbag: Stored procedures, triggers and SSRS reports
Top tips and tricks for SQL Server database development
Top 10 SQL Server development tips of 2008
SQL Server trigger vs. stored procedure to receive data notification
SQL Server errors, failures and other problems fixed from the trenches
SQL Server and data manipulation in T-SQL
How to use SQL Server 2008 hierarchyid data type
SQL Server stored procedures tutorial: Write, tune and get examples
Check SQL Server database and log file size with this stored procedure

RELATED GLOSSARY TERMS
Terms from Whatis.com − the technology online dictionary
data corruption  (SearchSQLServer.com)
data hiding  (SearchSQLServer.com)

RELATED RESOURCES
2020software.com, trial software downloads for accounting software, ERP software, CRM software and business software systems
Search Bitpipe.com for the latest white papers and business webcasts
Whatis.com, the online computer dictionary


This request is pretty easy to fulfill. Let's start with two tables: A table for data named DataTable and one to record the SQL Server Login that performed the change and the date and time of the change. The latter table is named myAuditTable. Here's the script to create the two tables.

CREATE TABLE DataTable ([Id] int identity (1,1) primary key
, UnMonitoriedColumn char(10)
, MonitoredColumn varchar(10)
) GO

CREATE TABLE myAuditTable (AuditEventID int identity (1,1) primary key
, USERLOGIN nvarchar(128)
, ChangeDT datetime
)
GO

Note DataTable as one column that is going to be monitored and another that is not monitored. myAuditTable has its own identity column, AuditEventID, so that events the occur at the same time can be distinguished. It might also be valuable to add additional columns to the table to record the ID column from the modified row and even the old and new values of MonitoredColumn. I'll leave that for another article.

Next comes the trigger. Here's the script to create the trigger.

CREATE TRIGGER DataTable_Audit on DataTable
FOR INSERT, UPDATE
AS IF UPDATE(MonitoredColumn)
INSERT INTO myAuditTable (USERLOGIN, ChangeDT)
VALUES (SYSTEM_USER, getdate())
GO

The body of the trigger contains only one statement. That statement uses the UPDATE function to test if MonitoredColumn has been changed, and if so it records the system user and date/time of the change. The UPDATE function is only available inside triggers for the purpose of detecting changes in individual columns. Beware that if more than one row is changed by a SQL statement, the UPDATE(MonitoredColumn) clause will be true if MonitoredColumn is changed in any of the rows modified by the statement.

The SYSTEM_USER function identifies the SQL Login change. This might be either a SQL Server login or the Windows login if that's how the user connected to SQL Server. In environments, such as Web applications where it's common to use only one SQL Server login for all users of the application, SYSTEM_USER will be the same for all users and not very helpful. In these situations, the Web application would have to supply additional information about the user in order to identify him.

Next, let's test the trigger with this script:

DECLARE @ID int
INSERT INTO DataTable (UnMonitoriedColumn, MonitoredColumn)
VALUES ('ABC', 'DEF')
SELECT @ID = SCOPE_IDENTITY()
UPDATE DataTable
SET MonitoredColumn = 'GHI'
WHERE [Id] = @ID
UPDATE DataTable
SET UnMonitoriedColumn = 'JKL'
WHERE [Id] = @ID
SELECT * FROM myAuditTable
GO

One row is inserted into DataTable and the ID column captured in the @Id variable. Next two updates are performed, one that changes MonitoredColumn and the second that does not. Here are the results of the query:

AuditEventID USERLOGIN ChangeDT
------------ -------------------- ------------------------------------------------------
1 NSandrew 2005-07-18 03:13:20.403
2 NSandrew 2005-07-18 03:13:20.403
(2 row(s) affected)

There are two rows in myAuditTable because the trigger audits both INSERTs and UPDATEs. The first row is for the INSERT and the second for the first UPDATE statement. The second UPDATE statement didn't change MonitoredColumn, so there are no rows added to myAuditTable.


Do you have comments on this Ask the Expert Q&A? Let us know.




Search and Browse the Expert Answer Center
Search and browse more than 25,000 question and answer pairs from more than 250 TechTarget industry experts.
Browse our Expert Advice



SQL Solutions - SQL Database Design
HomeNewsTopicsITKnowledge ExchangeTipsAsk the ExpertsMultimediaWhite PapersIT Downloads
About Us  |  Contact Us  |  For Advertisers  |  For Business Partners  |  Site Index  |  RSS
SEARCH 
TechTarget provides technology professionals with the information they need to perform their jobs - from developing strategy, to making cost-effective purchase decisions and managing their organizations' technology projects - with its network of technology-specific websites, events and online magazines.

TechTarget Corporate Web Site  |  Media Kits  |  Site Map




All Rights Reserved, Copyright 2005 - 2009, TechTarget | Read our Privacy Policy
  TechTarget - The IT Media ROI Experts