[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 202
  • Last Modified:

Trigger for audit

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
RIAS
Asked:
RIAS
  • 15
  • 11
1 Solution
 
Vitor MontalvãoMSSQL Senior EngineerCommented:
Blind link comment deleted.
0
 
Vitor MontalvãoMSSQL Senior EngineerCommented:
There's no trigger for SELECT.
What is really your goal here?
0
 
RIASAuthor Commented:
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
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!

 
RIASAuthor Commented:
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
 
Vitor MontalvãoMSSQL Senior EngineerCommented:
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
 
RIASAuthor Commented:
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
 
RIASAuthor Commented:
I am using sql server 2014
0
 
Vitor MontalvãoMSSQL Senior EngineerCommented:
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
 
RIASAuthor Commented:
Standard Edition (64-bit) on Windows NT
0
 
RIASAuthor Commented:
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
 
Vitor MontalvãoMSSQL Senior EngineerCommented:
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
 
RIASAuthor Commented:
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
 
Vitor MontalvãoMSSQL Senior EngineerCommented:
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
 
Vitor MontalvãoMSSQL Senior EngineerCommented:
You can always use SQL Server Trace to capture T-SQL statements.
0
 
RIASAuthor Commented:
Which edition do I require then ? I can ask for it
0
 
RIASAuthor Commented:
How do I SQL Server Trace
0
 
Vitor MontalvãoMSSQL Senior EngineerCommented:
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
 
RIASAuthor Commented:
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
 
RIASAuthor Commented:
Please let me know your thoughts and then i will close the question
0
 
Vitor MontalvãoMSSQL Senior EngineerCommented:
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
 
RIASAuthor Commented:
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
 
RIASAuthor Commented:
It seems Enterprise edition is ruled out and being asked to do it with trigger as the table will be archived every week .
0
 
Vitor MontalvãoMSSQL Senior EngineerCommented:
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
 
RIASAuthor Commented:
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
 
Vitor MontalvãoMSSQL Senior EngineerCommented:
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
 
RIASAuthor Commented:
Thanks Vitor, Very useful !
0

Featured Post

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

  • 15
  • 11
Tackle projects and never again get stuck behind a technical roadblock.
Join Now