SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Administration
 Check when database last used
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

ranvir_2k
Posting Yak Master

United Kingdom
160 Posts

Posted - 11/06/2013 :  08:26:13  Show Profile  Reply with Quote
I have some databases on my server that I suspect have not been used for a long time and I would like to confirm this.

Is there any way to find out when a database was last used/written to?
i.e. check the last transaction.

raghuveer125
Constraint Violating Yak Guru

India
283 Posts

Posted - 11/13/2013 :  02:47:00  Show Profile  Reply with Quote
Hi This is undocumented query I am sharing with you may be this will help you. Your database should be in full recovery mode and at-least one full backup has be taken.

Note:- This query won't find any select statement executed against database. This will give only information about last insert,delete or update.

Use [Your_database_name]
Go

SET NOCOUNT ON
DECLARE @LSN NVARCHAR(46)
DECLARE @LSN_HEX NVARCHAR(25)
DECLARE @tbl TABLE (id INT identity(1,1), i VARCHAR(10))
DECLARE @stmt VARCHAR(256)

SET @LSN = (SELECT TOP 1 [Current LSN] FROM fn_dblog(NULL, NULL))
PRINT @LSN

SET @stmt = 'SELECT CAST(0x' + SUBSTRING(@LSN, 1, 8) + ' AS INT)'
INSERT @tbl EXEC(@stmt)
SET @stmt = 'SELECT CAST(0x' + SUBSTRING(@LSN, 10, 8) + ' AS INT)'
INSERT @tbl EXEC(@stmt)
SET @stmt = 'SELECT CAST(0x' + SUBSTRING(@LSN, 19, 4) + ' AS INT)'
INSERT @tbl EXEC(@stmt)

SET @LSN_HEX =
(SELECT i FROM @tbl WHERE id = 1) + ':' + (SELECT i FROM @tbl WHERE id = 2) + ':' + (SELECT i FROM @tbl WHERE id = 3)
PRINT @LSN_HEX

SELECT [begin time],[Transaction Name],[End Time]
FROM ::fn_dblog(@LSN_HEX, NULL) --where [Database Name]='offline'
Where [transaction name] not in ('Backup:InvalidateDiffMaps','Backup:InvalidateDiffMaps','Backup:CommitDifferentialBase')
and [begin time]<>'null'
or [end time]<> 'null'


In Love... With Me!

Edited by - raghuveer125 on 11/13/2013 03:57:03
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.03 seconds. Powered By: Snitz Forums 2000