调用存储过程的统计信息

Statistics for calls to stored procedure

有什么方法可以找出 SQL 服务器上存储过程调用的统计信息?

我正在寻找以下信息:

  1. 调用存储过程的日期和时间
  2. 谁调用了存储过程(用户名)
  3. 即使用户收到错误消息,我也想获得以上信息"The EXECUTE permission was denied on the object 'sp_name', database 'db_name', schema 'schema_name'"

默认情况下SQL服务器不维护此类信息。 您必须设置以下方法之一来收集它:

  • SQL 审核
  • 扩展事件
  • SQL 追踪

此类任务的 SQL 审核示例:

-- step 1:
USE [master]
GO
CREATE SERVER AUDIT [SrvAudit_sp_execution]
TO FILE 
( FILEPATH = N'E:\DBA_Audit'
 ,MAXSIZE = 20 MB
 ,MAX_ROLLOVER_FILES = 50
 ,RESERVE_DISK_SPACE = OFF
)
WITH
( QUEUE_DELAY = 1000  -- equal to 1 second
 ,ON_FAILURE = CONTINUE
)
GO

-- step 2: 
CREATE DATABASE AUDIT SPECIFICATION [DBAudit_sp_execution]
FOR SERVER AUDIT [SrvAudit_sp_execution]
GO

-- step 3: 
ALTER DATABASE AUDIT SPECIFICATION [DBAudit_sp_execution]
FOR SERVER AUDIT [SrvAudit_sp_execution]
    ADD (EXECUTE ON OBJECT::dbo.proc1 BY [public]) ;

-- step 4:
ALTER SERVER AUDIT [SrvAudit_sp_execution]   WITH (STATE = ON);

USE [_DemoDB]    
ALTER DATABASE AUDIT SPECIFICATION [DBAudit_sp_execution]
FOR SERVER AUDIT [SrvAudit_sp_execution] WITH (STATE = ON);

可以在 SSMS 中进一步查看审计数据或通过以下方式查询:sys.fn_get_audit_file

参考文献:

https://www.mssqltips.com/sqlservertip/3259/several-methods-to-collect-sql-server-stored-procedure-execution-history/