Solved

Trigger for audit

Posted on 2016-08-21
26
97 Views
Last Modified: 2016-08-22
Hello,

I am using sql server 2014 .How do I write a trigger for update,delete,select and insert on my database tables  in an audit table called Audit_Trial which has columns like SqlQuery ,datetime,User

Cheers
0
Comment
Question by:RIAS
  • 15
  • 11
26 Comments
 
LVL 49

Expert Comment

by:Vitor Montalvão
ID: 41764914
Blind link comment deleted.
0
 
LVL 49

Expert Comment

by:Vitor Montalvão
ID: 41764915
There's no trigger for SELECT.
What is really your goal here?
0
 

Author Comment

by:RIAS
ID: 41764923
Hello Vitor,

I have a audit table which stores the sql query and the username and time .

Need to update it when any select,update,insert or delete is executed on the database.

Cheers
0
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 

Author Comment

by:RIAS
ID: 41764925
The audit table create query is

CREATE TABLE [dbo].[AuditTRIAL](
      [SQL] [nvarchar](2000) NULL,
      [EntryDateTime] [datetime] NULL   DEFAULT (getdate()),
       [Tracking_user] varchar(255) NOT NULL DEFAULT SYSTEM_USER  
) ON [PRIMARY]
0
 
LVL 49

Expert Comment

by:Vitor Montalvão
ID: 41764956
I highly recommend you to not use a table to store that kind of information. Your database will grow a lot and you'll have disk space issues soon.

My recommendation is to use SQL Server Audit feature and store the information in a file.
Here's an example how Audit works:
-- CREATE THE SERVER AUDIT AND ENABLE IT
USE [master]

GO

CREATE SERVER AUDIT [T-SQL Statements]
TO FILE 
(	FILEPATH = N'S:\MSSQL\MSSQL12.MSSQLSERVER\MSSQL\Log'
)
WITH
(	QUEUE_DELAY = 1000
	,ON_FAILURE = CONTINUE
)

GO

ALTER SERVER AUDIT [T-SQL Statements] WITH (STATE = ON)

-- CREATE THE DATABASE AUDIT SPECIFICATION AND ENABLE IT
USE [DatabaseNameHere]

GO

CREATE DATABASE AUDIT SPECIFICATION [Audit all T-SQL statements]
FOR SERVER AUDIT [T-SQL Statements]
ADD (DELETE ON DATABASE::[DatabaseNameHere] BY [dbo]),
ADD (INSERT ON DATABASE::[DatabaseNameHere] BY [dbo]),
ADD (SELECT ON DATABASE::[DatabaseNameHere] BY [dbo]),
ADD (UPDATE ON DATABASE::[DatabaseNameHere] BY [dbo])
WITH (STATE = ON)

GO

-- THIS IS HOW TO READ THE INFORMATION FROM THE FILE
SELECT event_time ,
       session_server_principal_name,
       server_instance_name ,
       database_name ,
       statement
FROM sys.fn_get_audit_file('S:\MSSQL\MSSQL12.MSSQLSERVER\MSSQL\Log\*.sqlaudit', DEFAULT, DEFAULT)
GROUP BY event_time ,
       session_server_principal_name,
       server_instance_name ,
       database_name ,
       statement

Open in new window

0
 

Author Comment

by:RIAS
ID: 41764965
Thanks a ton Vitor,

But,Is there any way I can have the file stored in the database as the database is on the server.
Also, i get error :


Msg 15151, Level 16, State 1, Line 16
Cannot alter the audit 'T-SQL Statements', because it does not exist or you do not have permission.
Msg 33075, Level 16, State 3, Line 23
Granular auditing is not available in this edition of SQL Server. For more information about feature support in the editions of SQL Server, see SQL Server Books Online.
0
 

Author Comment

by:RIAS
ID: 41764967
I am using sql server 2014
0
 
LVL 49

Expert Comment

by:Vitor Montalvão
ID: 41764971
Cannot alter the audit 'T-SQL Statements', because it does not exist or you do not have permission.
The CREATE SERVER AUDIT needs to run first. Did you check if the SERVER AUDIT has been created before running the ALTER SERVER AUDIT?

Granular auditing is not available in this edition of SQL Server.
I know you're using SQL Server 2014 but what's the Edition (Enterprise, Standard, Express, other)?
0
 

Author Comment

by:RIAS
ID: 41764974
Standard Edition (64-bit) on Windows NT
0
 

Author Comment

by:RIAS
ID: 41765053
Tried:

-- CREATE THE SERVER AUDIT AND ENABLE IT
USE [master]

GO

CREATE SERVER AUDIT [T-SQL Statements]
TO FILE
(      FILEPATH = 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Log'
)
WITH
(      QUEUE_DELAY = 1000
      ,ON_FAILURE = CONTINUE
)

GO



Error:

Msg 33072, Level 16, State 1, Line 6
The audit log file path is invalid.
0
 
LVL 49

Expert Comment

by:Vitor Montalvão
ID: 41765056
Ok, the path I used was mine. You should give a path that exists in your server.
I only have Enterprise Edition here but by the message you can't go so granular in Standard Edition.
You can try the following version but I don't know if gives what you need:
-- CREATE THE DATABASE AUDIT SPECIFICATION AND ENABLE IT
USE [DatabaseNameHere]

GO

CREATE DATABASE AUDIT SPECIFICATION [Audit all T-SQL statements]
FOR SERVER AUDIT [T-SQL Statements]
ADD (SCHEMA_OBJECT_ACCESS_GROUP)
WITH (STATE = ON)

GO

Open in new window

0
 

Author Comment

by:RIAS
ID: 41765059
Thanks but,

Msg 33075, Level 16, State 3, Line 6
Granular auditing is not available in this edition of SQL Server. For more information about feature support in the editions of SQL Server, see SQL Server Books Online.
0
 
LVL 49

Expert Comment

by:Vitor Montalvão
ID: 41765063
Oh, just found this statement in MSDN article about SQL Server Audit:
Database level auditing is limited to Enterprise, Developer, and Evaluation editions.
I'm sorry but you can't audit at database level with Standard Edition :(
0
 
LVL 49

Expert Comment

by:Vitor Montalvão
ID: 41765064
You can always use SQL Server Trace to capture T-SQL statements.
0
 

Author Comment

by:RIAS
ID: 41765065
Which edition do I require then ? I can ask for it
0
 

Author Comment

by:RIAS
ID: 41765066
How do I SQL Server Trace
0
 
LVL 49

Expert Comment

by:Vitor Montalvão
ID: 41765068
Easiest way is to open SQL Server Profiler utility and then follow these steps:
  1. File->New Trace
  2. Give a Trace Name
  3. You can choose between "Save to file:" or "Save to table:". Depending on the choice you need to provide the file or table name
  4. Go to the "Event Selection" Tab
  5. Uncheck all Events
  6. Click on  "Show all events" and find TSQL->SQL:StmtStarting and check it
  7. Click on the Run button and the trace will start immediately
0
 

Author Comment

by:RIAS
ID: 41765077
Vitor,
It does not give the exact sql executed but gives alot of information which is not required.
Will try to install enterprise edition.
0
 

Author Comment

by:RIAS
ID: 41765079
Please let me know your thoughts and then i will close the question
0
 
LVL 49

Accepted Solution

by:
Vitor Montalvão earned 500 total points
ID: 41765086
It does not give the exact sql executed but gives alot of information which is not required.
You can always filter the information to be traced as well selecting only few columns instead of all. Here's a good tutorial to show how to reduce the information to be captured.
0
 

Author Comment

by:RIAS
ID: 41765097
Vitor Montalvão,

Other than Enterprise edition and trace.
Is there any way I can write trigger to :
I have a audit table which stores the sql query and the username and time .
Need to update it when any select,update,insert or delete is executed on the database.

Cheers
0
 

Author Comment

by:RIAS
ID: 41765100
It seems Enterprise edition is ruled out and being asked to do it with trigger as the table will be archived every week .
0
 
LVL 49

Expert Comment

by:Vitor Montalvão
ID: 41765104
Problem with trigger is that isn't available for SELECT and also doesn't gives you the T-SQL statement. At least not so direct.
0
 

Author Comment

by:RIAS
ID: 41765106
Ok, but can I have trigger for update, insert and delete?
Even if it is like old value and new value and type of query i.e insert ot update will be very very helpful.
0
 
LVL 49

Expert Comment

by:Vitor Montalvão
ID: 41765115
Ok, but can I have trigger for update, insert and delete?
Yes.
Even if it is like old value and new value and type of query i.e insert ot update will be very very helpful.
Inside a trigger you can get old values by querying DELETED table. New values are in INSERTED table.
So for a delete operation you check DELETED table and for an insert operation you check INSERTED table. For an update operation you need to check both tables (old value is in DELETED and new one in INSERTED).

These and more information can be found in MSDN trigger's article.
1
 

Author Comment

by:RIAS
ID: 41765141
Thanks Vitor, Very useful !
0

Featured Post

NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
I have a large data set and a SSIS package. How can I load this file in multi threading?
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

733 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question