ALTER TRIGGER DroppinDatabasesAwYeah
ON ALL SERVER
FOR DROP_DATABASE
AS
BEGIN
DECLARE
@name NVARCHAR(255),
@login NVARCHAR(255),
@msg NVARCHAR(MAX);
SELECT
@name = EVENTDATA().value('(/EVENT_INSTANCE/DatabaseName)[1]','NVARCHAR(255)'),
@login = EVENTDATA().value('(/EVENT_INSTANCE/LoginName)[1]','NVARCHAR(255)');
SELECT @msg = N'It appears that '
+ QUOTENAME(COALESCE(@login, N'<unknown>'))
+ N' has dropped the database '
+ QUOTENAME(COALESCE(@name, N'<unknown>')) + N'.';
EXEC msdb.dbo.sp_send_dbmail
@profile_name = N'default',
@recipients = N'[email protected]',
@subject = N'Somebody done dropped a database',
@body = @msg;
END
GO
SELECT SPID
,LoginName
,NTUserName
,NTDomainName
,HostName
,ApplicationName
,StartTime
,ServerName
,DatabaseName
,CASE EventClass
WHEN 46
THEN 'CREATE'
WHEN 47
THEN 'DROP'
ELSE 'OTHER'
END AS EventClass
,CASE ObjectType
WHEN 16964
THEN 'DATABASE'
ELSE 'OTHER'
END AS ObjectType
FROM [fn_trace_gettable](CONVERT(VARCHAR(150), (
SELECT TOP 1 value
FROM [fn_trace_getinfo](NULL)
WHERE [property] = 2
)), DEFAULT) T
WHERE ObjectType = 16964 /* Database */
AND EventSubClass = 1 /* Committed */
AND StartTime > DATEADD(HH, - 24, GETDATE()) -- get for last 24 hrs Only !!
ORDER BY StartTime
GO
@Kin 从默认跟踪中获取此信息是正确的,如果它实际上仍然存在(取决于您的服务器有多忙,以及这发生在多长时间前)。
不过,要立即收到电子邮件,您可以从 DDL 触发器中执行此操作,而不必一直记住检查默认跟踪以防万一。数据库邮件配置超出了问题的范围,我认为,所以我会把那部分留给你(这里有问答环节)。
如果您有默认跟踪运行并且希望它没有被回收,它将被记录在那里:
在这里回答了一个类似的问题。追踪的基本概念是相同的。