简体   繁体   中英

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? 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? Thanks.

in SQL Server 2005 and up you can create a database level trigger to track table changes. 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(<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.

Triggers can do this for you. Triggers are not considered manual method - they are a core part of database design.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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