我可以检索超过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
。
这样做的最佳方式是什么?
答案 0 :(得分: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