Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to track changes in table structure in Sql Server

I have a table having three columns (Name, Age, City). Now if after sometime someone adds one extra column (country) to the table. How would I get to know which column has been added to the Table i.e. country.

Is there any way to track the changes of table structure, whenever anybody changes the structure of table?

like image 883
Rahul Singh Avatar asked Oct 07 '22 19:10

Rahul Singh


1 Answers

SQL Server DDL triggers can be used in order to track DDL changes, whether the changes were intentional or accidental. Who committed the change, when, and what was affected by the committed action is the basic information needed to be captured using triggers. To use this solution, it’s required to create and maintain both triggers and captured information storage

In the following example, information about the event that fired the trigger is captured using the SQL Server’s EVENTDATA() function. The SQL script creates DDL trigger that captures CREATE, ALTER, and DROP events on a database level (although, triggers can be created on the server level to capture events for all databases on the server; ON ALL SERVER option should be used, instead of ON DATABASE):

CREATE TRIGGER Audit_DDL
ON DATABASE
    FOR CREATE_TABLE, ALTER_TABLE, DROP_TABLE
AS
     DECLARE
        @event xml;
     SET
     @event = EVENTDATA();
     INSERT INTO Audit_DDL_Events
     VALUES
     (
     REPLACE(CONVERT(varchar(50),
     @event.query('data(/EVENT_INSTANCE/PostTime)')), 'T', ' ')
     ,
     CONVERT(varchar(150),
     @event.query('data(/EVENT_INSTANCE/LoginName)'))
     ,
     CONVERT(varchar(150),
     @event.query('data(/EVENT_INSTANCE/UserName)'))
     ,
     CONVERT(varchar(150),
     @event.query('data(/EVENT_INSTANCE/DatabaseName)'))
     ,
     CONVERT(varchar(150),
     @event.query('data(/EVENT_INSTANCE/SchemaName)'))
     ,
     CONVERT(varchar(150),
     @event.query('data(/EVENT_INSTANCE/ObjectName)'))
     ,
     CONVERT(varchar(150),
     @event.query('data(/EVENT_INSTANCE/ObjectType)'))
     ,
 CONVERT(varchar(max),
 @event.query('data(/EVENT_INSTANCE/TSQLCommand/CommandText)'))
 );

An appropriate storage table for the auditing data from EVENTDATA XML must be created also:

CREATE TABLE Audit_DDL_Events
(
             DDL_Event_Time            datetime
             ,
             DDL_Login_Name            varchar(150)
             ,
             DDL_User_Name             varchar(150)
             ,
             DDL_Database_Name         varchar(150)
             ,
             DDL_Schema_Name           varchar(150)
             ,
             DDL_Object_Name           varchar(150)
             ,
             DDL_Object_Type           varchar(150)
             ,
             DDL_Command              varchar(max)
);
like image 105
Ivan Stankovic Avatar answered Oct 13 '22 11:10

Ivan Stankovic