Search code examples
sqlsql-serverdetach

SQL Server DETACH databases older than 6 months


I can retrieve a list of databases created more than 6 months ago like this:-

-- all databases over 6 months old
select name, crdate
from sys.sysdatabases
where crdate <= DATEADD(month, -6, GETDATE())
      AND name not in ('master','model','msdb','tempdb','distribution')

Gives results like this:-

name        crdate
db1         2008-06-25 09:01:11.747
db2         2008-06-25 09:01:50.967

I can detach a database like this:-

-- detach database
EXEC master.dbo.sp_detach_db @dbname = N'db1',
@keepfulltextindexfile = N'true'

I need to run sp_detach_db for each database the first query returns.

What's the best way of doing this ?


Solution

  • You can use a cursor for the task:

    declare cur cursor for
    select name
    from sys.sysdatabases
    where crdate <= DATEADD(month, -6, GETDATE())
    and name not in ('master','model','msdb','tempdb','distribution')
    
    declare @name nvarchar(200)
    
    open cur
    
    fetch next from cur into @name
    
    while @@FETCH_STATUS = 0
    begin
        EXEC master.dbo.sp_detach_db @dbname = @name, @keepfulltextindexfile = N'true'
        fetch next from cur into @name
    end
    
    close cur
    deallocate cur