To find active and inactive databases in SQL Server when you have a large number of databases, you can use the following code:
CREATE TABLE #T (dbName varchar(100),last_user_seek datetime,last_user_scan datetime,last_user_lookup datetime,last_user_update datetime)
declare @dbId as int
declare @dbname as varchar(100)
declare crs cursor for select dbid,name from sysdatabases
open crs
fetch next from crs into @dbId,@dbname
while @@FETCH_STATUS=0
begin
Insert Into #T
Select @dbname,
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
WHERE
database_id=@dbId
fetch next from crs into @dbId,@dbname
end
close crs
deallocate crs
select * from #t
drop table #t
Here are the steps to execute this query in SQL Server Management Studio (SSMS): ... READ MORE ❯❯❯