2013-01-09 36 views
2

我可以检索的创造超过6个月前这样的数据库列表: -SQL Server分离数据库超过6个月的

-- 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') 

给出的结果是这样的: -

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

我可以分离数据库是这样的: -

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

我需要为第一个查询返回的每个数据库运行sp_detach_db

这样做的最好方法是什么?

回答

3

您可以使用光标的任务:

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  
相关问题