我在服务器中使用示例数据库(名称EX:rr)。在示例数据库中,我有存储过程并且可以由员工访问。现在我的问题是一些身体修改了一个存储过程(例如:SP_EmpInsert)。现在我想知道存储过程的修改历史以及修改它的计算机(计算机的IP地址)。
我提到了这个链接 Get username and/or IP address responsible for a query
答案 0 :(得分:0)
Fisrt我们需要创建数据库
CREATE DATABASE HistoryDB;
GO
需要创建表来存储日志
USE HistoryDB;
GO
CREATE TABLE dbo.tbl_SPHistory
(
EventDate DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
EventType NVARCHAR(64),
EventDDL NVARCHAR(MAX),
EventXML XML,
DatabaseName NVARCHAR(255),
SchemaName NVARCHAR(255),
ObjectName NVARCHAR(255),
HostName VARCHAR(64),
IPAddress VARCHAR(32),
ProgramName NVARCHAR(255),
LoginName NVARCHAR(255)
);
需要插入我们需要创建日志的存储过程
INSERT HistoryDB.dbo.tbl_SPHistory
(
EventType,
EventDDL,
DatabaseName,
SchemaName,
ObjectName,
LoginName
)
SELECT
'CREATE_PROCEDURE',
OBJECT_DEFINITION([object_id]),
DB_NAME(),
OBJECT_SCHEMA_NAME([object_id]),
OBJECT_NAME([object_id]),
'my name'
FROM
sys.procedures;
最后我们需要创建DDL触发器
USE YourDatabase;
GO
CREATE TRIGGER DDLTrigger_Sample
ON DATABASE
FOR CREATE_PROCEDURE, ALTER_PROCEDURE, DROP_PROCEDURE
AS
BEGIN
SET NOCOUNT ON;
DECLARE
@EventData XML = EVENTDATA();
DECLARE
@ip VARCHAR(32) =
(
SELECT client_net_address
FROM sys.dm_exec_connections
WHERE session_id = @@SPID
);
INSERT HistoryDB.dbo.tbl_SPHistory
(
EventType,
EventDDL,
EventXML,
DatabaseName,
SchemaName,
ObjectName,
HostName,
IPAddress,
ProgramName,
LoginName
)
SELECT
@EventData.value('(/EVENT_INSTANCE/EventType)[1]', 'NVARCHAR(100)'),
@EventData.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'NVARCHAR(MAX)'),
@EventData,
DB_NAME(),
@EventData.value('(/EVENT_INSTANCE/SchemaName)[1]', 'NVARCHAR(255)'),
@EventData.value('(/EVENT_INSTANCE/ObjectName)[1]', 'NVARCHAR(255)'),
HOST_NAME(),
@ip,
PROGRAM_NAME(),
SUSER_SNAME();
END
GO
另请参阅链接以获取详细说明 SQL Server DDL Triggers to Track All Database Changes