Anyway to create a SQL Server DDL trigger for “SELECT” statements?

前端 未结 6 1117
太阳男子
太阳男子 2020-12-03 18:34

I am dealing with some sensitive Accounting tables and I would like to audit any SELECT statement executed on the table or any views associated with them.

6条回答
  •  不知归路
    2020-12-03 19:03

        --In the master database create a server audit
    USE master
    GO
    CREATE SERVER AUDIT [Audit_Select_HumanResources_Employee]
    TO FILE
    (     FILEPATH = N'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup'
          ,MAXSIZE = 0 MB
          ,MAX_ROLLOVER_FILES = 2147483647
          ,RESERVE_DISK_SPACE = OFF)
    WITH
    (QUEUE_DELAY = 1000, state=  on)
    
    ALTER SERVER AUDIT Audit_Select_HumanResources_Employee 
    WITH (STATE = ON) ;
    GO
    --In the database to monitor create a database audit
    USE [AdventureWorks2012]
    go
    
    CREATE DATABASE AUDIT SPECIFICATION [Database-Audit]
    FOR SERVER AUDIT [Audit_Select_HumanResources_Employee]
    --In this example, we are monitoring the humanResources.employee
    ADD (SELECT ON OBJECT::[HumanResources].[Employee] BY [dbo])
    with (state=on)
    
    --Now you can see the activity in the audit file created
    SELECT * FROM sys.fn_get_audit_file ('c:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\Audit_Select_HumanResources_Employee.sqlaudit',default,default);
    GO
    

    I just added some code for you. The code creates a server audit, a database audit for select activities and finally the sys.fn_get_audit_file is used to retrieve the information from the file. You have to do that individually for each table. If you want a more automated query, you can use other tools like Apex SQL Audit or other third party tool of your preference.

提交回复
热议问题