2

我可以像这样检索 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第一个查询返回的每个数据库运行。

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

4

1 回答 1

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      
于 2013-01-09T11:23:18.363 回答