SQL Server多次收缩操作

时间:2011-09-13 16:12:31

标签: sql-server sql-server-2008-r2

我正在尝试缩小SQL Server 2008 R2中的所有数据库(文件和日志)。

我已经完成了脚本,但问题是,当我遍历所有数据库并执行查询以执行shrink file时,前3或4个收缩工作但是我有这个错误:

  

消息0,级别11,状态0,行0   当前命令发生严重错误。结果,如果有的话,   应该被丢弃。

剧本:

declare @db_name as varchar(30)
declare @db_recorvery_model as varchar(30)
declare @db_files_name as varchar(250)
declare @db_files_physical_name as varchar(250)

declare get_files cursor for 
     select b.name, a.name  
     from sys.master_files as a, 
          sys.databases as b 
     where a.database_id = b.database_id  
     order by b.name  

open get_files

fetch next from get_files into @db_files_name, @db_files_physical_name

set @db_files_name = (select @db_files_name)
set @db_files_physical_name = (select @db_files_physical_name)

DECLARE @Command as nvarchar(max)
set @Command=''

while(@@FETCH_STATUS=0)
BEGIN
   if (@db_files_name='master' or @db_files_name='msdb' or @db_files_name='tempdb' or @db_files_name='model')
   BEGIN
      print 'Bases de dados do sql server: '+@db_files_name
   END
   ELSE
   BEGIN
      set @Command = 'USE ' + '[' + @db_files_name + '] DBCC SHRINKFILE ("'+@db_files_physical_name+'", 1 )'
      EXEC sp_executesql @Command
      print @Command
   END

   fetch next from get_files into @db_files_name, @db_files_physical_name

   set @db_files_name = (select @db_files_name)
   set @db_files_physical_name = (select @db_files_physical_name)
END

close get_files
deallocate get_files

有没有人有任何想法?

PS:我知道我不应该缩小,但这是一个非常特殊的环境而且效率不高。

2 个答案:

答案 0 :(得分:1)

您能确定哪个数据库标记错误吗?您是否可以尝试在有问题的单个数据库上运行脚本,并查看它是否始终与触发错误的数据库相同?也许这是一个你错过的特殊数据库,不能以这种方式缩小。

我有一个类似的环境,其中包含不用于长期存储的临时数据库,我使用以下脚本,该脚本可以完美地用于数百个数据库:

CREATE procedure [dbo].[ShrinkLog]
    @DB varchar(200)
as

declare @LogFile varchar(200)
declare @Sql varchar(500)

SELECT @LogFile = name
FROM sys.master_files
where type_desc = 'LOG'
and db_name(database_id) = @DB


set @Sql = '
    Use [' + @DB + ']
    DBCC SHRINKFILE([' + @LogFile + '], 1)
'
print(@sql)
exec(@sql)

请记住,除非您的服务器还有足够的硬盘/内存空间,否则您不想运行此命令。

致以最诚挚的问候,

答案 1 :(得分:0)

如果你想进行日志缩减,这将是最好的代码。我正在使用它一段时间,它永远不会崩溃。

declare @SQL nvarchar(max)

select @SQL = coalesce(@SQL + char(13) + char(10),'') + N'
Use ' + QUOTENAME(d.[name]) + ';' + CHAR(13) + '
ALTER DATABASE ' + QUOTENAME(d.[name]) + ' SET RECOVERY SIMPLE;
DBCC SHRINKFILE (' + quotename(mf.[name],'''') + ', 1);
ALTER DATABASE ' + QUOTENAME(d.[name]) + ' SET RECOVERY FULL;'
FROM sys.databases d
INNER JOIN sys.master_files mf ON [d].[database_id] = [mf].[database_id]
WHERE
    d.[database_id] > 4 --no sys dbs
    AND d.recovery_model = 1
    AND d.is_read_only = 0
    AND mf.[type] = 1 --log files
ORDER BY d.name

--print @SQL

execute (@SQL)