Friday, October 15, 2021

SQL SERVER last accessed and last restart

 --current connections

SELECT @@ServerName AS server

 ,NAME AS dbname

 ,COUNT(STATUS) AS number_of_connections

 ,GETDATE() AS timestamp

FROM sys.databases sd

LEFT JOIN sysprocesses sp ON sd.database_id = sp.dbid

WHERE database_id NOT BETWEEN 1 AND 4

GROUP BY NAME;


--db last accessed

SELECT d.name,

last_user_seek = MAX(last_user_seek),

last_user_scan = MAX(last_user_scan),

last_user_lookup = MAX(last_user_lookup),

last_user_update = MAX(last_user_update)

FROM sys.dm_db_index_usage_stats AS i

JOIN sys.databases AS d ON i.database_id=d.database_id

GROUP BY d.name


--last restart

SELECT sqlserver_start_time FROM sys.dm_os_sys_info