简体   繁体   中英

Correct query to pull the last modified time for a table on SQL server?

My goal is to pull the last modified date and time for a table in SQL server (MS SQL SERVER 2008 R2), when I say last modified date and time, I specifically meant the changes of values for the records of that table. For example, value added, deleted, or updated. Not changes such as structural change for the table.

Assuming my DB name is MyDB. Assuming my table name is MyTable.

So I used the following query and it did work every time I changed a value for a record in the table, and reflects the correct time for the change:

SELECT last_user_update from sys.dm_db_index_usage_stats where database_id = DB_ID('MyDB') and object_id = object_id('MyDB.dbo.Mytable')

My question now - Is this query the correct way to meet my goal? Because I sort of came up with this query by trail and error so I need some confirmation. Also, does this query also reflect other changes for the table such as structural changes? If so, is there a better query that is cleaner and only reflects value changes within the table?

MSDN States: The user_updates counter indicates the level of maintenance on the index caused by insert, update, or delete operations on the underlying table or view.

https://msdn.microsoft.com/en-us/library/ms188755.aspx

So its probably OK.

However you could probably put a LastModifiedDateTime field on the DB and set it during an operation and then select the MAX value for this.

EDIT: As per comments:

CREATE TRIGGER LastUpdateTrigger 
ON sourceTable 
AFTER INSERT, UPDATE, DELETE 
AS  
    IF NOT EXISTS(SELECT * FROM destTable WHERE TableName = 'sourceTable') 
    BEGIN
        INSERT INTO destTable (LastUpdateDateTime, TableName) 
        VALUES (GETDATE(), 'sourceTable')
    END
    ELSE
    BEGIN
        UPDATE destTable SET LastUpdateDateTime = GETDATE()
        WHERE Tablename = 'sourceTable'
    END

Also put table name in destTable to track updates accross tables in same database.

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