简体   繁体   English

SQL Server 2005表更改历史记录

[英]SQL Server 2005 Table Alter History

Does SQL Server maintains any history to track table alterations like column add, delete, rename, type/ length change etc? SQL Server是否保留任何历史记录来跟踪表更改,例如列添加,删除,重命名,类型/长度更改等? I found many suggest to use stored procedures to do this manually. 我发现许多建议使用存储过程手动执行此操作。 But I'm curious if SQL Server keeps such history in any system tables? 但是我很好奇SQL Server是否在任何系统表中都保留了这样的历史记录? Thanks. 谢谢。

in SQL Server 2005 and up you can create a database level trigger to track table changes. 在SQL Server 2005及更高版本中,您可以创建数据库级触发器来跟踪表更改。 Use something like: 使用类似:

CREATE TRIGGER [YourDatabaseTrigger]
ON DATABASE
FOR DDL_DATABASE_LEVEL_EVENTS
AS

DECLARE @EventData      xml
DECLARE @Message        varchar(1000)
SET @EventData=EVENTDATA()

INSERT INTO YourLogTable 
    (EventDateTime,EventDescription) 
    VALUES (GETDATE(),SUSER_NAME()
                     +'; '+@EventData.value('(/EVENT_INSTANCE/ObjectType)[1]', 'varchar(250)')
                     +'; '+@EventData.value('(/EVENT_INSTANCE/ObjectName)[1]', 'varchar(250)')
                     +'; '+@EventData.value('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]','nvarchar(max)')
           )
RETURN
GO

ENABLE TRIGGER [YourDatabaseTrigger] ON DATABASE

here is some simple output from the log: 这是日志的一些简单输出:

select * from YourLogTable
EventID     EventDateTime           EventDescription
----------- ----------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------
1           2010-04-06 08:25:47.333 sa; TABLE; YourLogTable2; create table YourLogTable2 (EventID int primary key identity(1,1),EventDateTime datetime, EventDescription varchar(max))
2           2010-04-06 08:25:55.113 sa; TABLE; YourLogTable2; drop table YourLogTable2

(2 row(s) affected)

you could expand the log to contain more columns, or just dump everything within a one like in this simple example. 您可以将日志扩展为包含更多列,或者像在此简单示例中那样,仅转储其中的所有内容。

The transaction logs store all this information and the DBCC LOG command should let you view that, but it's an undocumented command. 事务日志存储所有这些信息,并且DBCC LOG命令应允许您查看它,但这是未记录的命令。

DBCC LOG(<database name>[,{0|1|2|3|4}])  
0 – Basic Log Information (default)  
1 – Lengthy Info  
2 – Very Length Info  
3 – Detailed  
4 – Full Example  

Syntax: 句法:

DBCC log (MY_DB, 4)  

This kind of information is not retained in any RDBMS by default because it could increase the required storage requirements by orders of magnitude, and could severely decrease performance. 默认情况下,此类信息不会保留在任何RDBMS中,因为它可能使所需的存储需求增加几个数量级,并可能严重降低性能。

Triggers can do this for you. 触发器可以为您完成此任务。 Triggers are not considered manual method - they are a core part of database design. 触发器不被视为手动方法-触发器是数据库设计的核心部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM