我有一个带有外键的SQL Server 2008数据库神秘地消失了。通过大量定制软件,MS Excel查询和SQL Server Management Studio访问数据库。我想在从数据库添加,修改或删除外键时设置某种日志记录/审计。我该怎么做呢?理想情况下,更改将写入SQL表,并帮助确定谁进行了更改。
答案 0 :(得分:1)
答案 1 :(得分:1)
您创建一个表,可以创建触发器来存储对数据库的更改。 全文:http://www.sqlbook.com/sql-server/using-ddl-triggers-in-sql-server-to-audit-database-objects/
Decimal
答案 2 :(得分:0)
Stivan在上述评论中提供了我的问题的答案。如果他将其作为答案提交,我会将其转换为已接受的答案。话虽这么说,我在我想跟踪的数据库中添加了一个DDL审计表,并在执行Create / Alter / Drop Table语句时添加了一个DB触发器来填充它。我运行的查询如下所示:
USE DBName
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[DDLAudit](
[RowID] [int] IDENTITY(1,1) NOT NULL,
[PostTime] [datetime] NULL,
[DatabaseName] [varchar](256) NULL,
[Event] [nvarchar](100) NULL,
[ObjectName] [varchar](256) NULL,
[TSQL] [nvarchar](2000) NULL,
[Login] [varchar](256) NULL,
CONSTRAINT [PK_DDLAudit] PRIMARY KEY CLUSTERED
(
[RowID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
CREATE TRIGGER AuditProcChanges
ON DATABASE
FOR CREATE_TABLE, ALTER_TABLE, DROP_TABLE
AS
DECLARE @ed XML
SET @ed = EVENTDATA()
INSERT INTO DDLAudit (PostTime, DatabaseName, Event, ObjectName, TSQL, Login)
VALUES
(
GetDate(),
@ed.value('(/EVENT_INSTANCE/DatabaseName)[1]', 'varchar(256)'),
@ed.value('(/EVENT_INSTANCE/EventType)[1]', 'nvarchar(100)'),
@ed.value('(/EVENT_INSTANCE/ObjectName)[1]', 'varchar(256)'),
@ed.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'nvarchar(2000)'),
@ed.value('(/EVENT_INSTANCE/LoginName)[1]', 'varchar(256)')
)