Search This Blog

SQL:When was my database last taken Offline or Online


Here is a T-SQL script which tells when and who took the database offline or online recently.
This script utilizes the default trace and if the trace is reset after the database went offline or online then you have change the trace file path and name in the script.

DECLARE  @DBNAME nvarchar(100)
  ,@FileName nvarchar(max)
  ,@spid int
  ,@LogDate Datetime
  ,@Status nvarchar(10)
   
SET @DBNAME = 'AdventureWorks2012' -- Change DB Name
SET @Status = 'ONLINE' --[OFFLINE or ONLINE]
SELECT @FileName=[path] FROM sys.traces WHERE is_default=1
print(@FileName)
DECLARE @ErrorLogTable table (Logdate datetime, ProcessInfo nvarchar(10), [Text] nvarchar(max))

INSERT INTO @ErrorLogTable
EXEC xp_readerrorlog 0,1, @Status, @DBNAME, NULL, NULL, 'desc'

SELECT TOP 1 @spid=cast(SUBSTRING(ProcessInfo,5,5) AS int)
   ,@LogDate=cast(Logdate AS nvarchar) 
FROM @ErrorLogTable

--select * from  @ErrorLogTable
 print(@spid)
SELECT DatabaseID, DatabaseName, HostName, ApplicationName, LoginName, StartTime,spid,CAST(StartTime AS nvarchar),@LogDate
FROM sys.fn_trace_gettable( @FileName, DEFAULT )
WHERE spid=@spid and  DatabaseName=@DBNAME
--and StartTime=@LogDate