freachable.net
Next generation's garbage
Wednesday, September 29, 2010
Quick and Dirty SQL Audit Table
CREATE TABLE audit(
[on] datetime not null default getutcdate(),
[by] varchar(255) not null default system_user+','+AppName(),
was xml null,
[is] xml null
)
CREATE TRIGGER
mytable
_audit ON
mytable
for insert, update, delete as
INSERT audit(was,[is]) values(
(select * from deleted as [
mytable
] for xml auto,type),
(select * from inserted as [
mytable
] for xml auto,type)
)
The main goals were to make something really quick to record who did what when across several tables, but it is presumed that this would rarely get used, so queryability wasn't paramount. It would be more likely that tables get created or altered than this stuff would be dived into.
It doesn't work on tables that have certain kinds of fields that are incompatible with FOR XML like TEXT. Had one table with that and I just converted it to nvarchar(max) rather than fight it.
Also, this frees me from having to bloat my tables with fields like CreatedDateTime. Better still, I got to drop fields like DeletedDateTime which implied they shouldn't normally be selected, so every UPDATE and SELECT had to include WHERE DeletedDateTime IS NULL. This really caused problems since I could very easily get primary key violations because a record got 'DELETED' and recreated with the same natural key. I know, I know, just another argument for "surrogate keys only".
Wednesday, September 29, 2010 3:33:22 PM (US Mountain Standard Time, UTC-07:00)
Comments [0]
-
SQL
Comments are closed.
Twitter
Navigation
Home
dasBlog
Scott Hanselman
Categories
.NET
.NET Internals
Apple
Bing Maps
Certification
dasBlog
From the labs
Hardware
HTML
iphone
LINQ
merb
Office 12
ruby
Security
SharePoint
Silverlight
SiteFinity
SQL
tinfoilhat
Virtualization
Visual Studio
Windows 7
Windows Live
WP7
Archive
<
February 2012
>
Sun
Mon
Tue
Wed
Thu
Fri
Sat
29
30
31
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
1
2
3
4
5
6
7
8
9
10
Blogroll
Andrew Connell
BCL Team
Beth Massi - VB
Brad Abrams
IE blog
Mike Stall's .NET Debugging
Panopticon Central
Scott Hanselman
SharePoint Designer Team
SharePoint Team
The Old New Thing
VB Team
Windows PowerShell
All Content © 2012, Hafthor Stefansson -
Disclaimer:
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way. -
Sign In