将游标与动态 SQL 一起使用。这将在每个数据库上单独收缩每个文件。
Declare @dataFiles Table (databaseName Varchar(256), datafile Varchar(256))
Declare @SQL Nvarchar(Max), @databaseName Varchar(256), @dbfile Varchar(256)
Insert @dataFiles
select sd.name, smf.name
from sys.sysdatabases sd
join sys.master_files smf
On sd.[dbid] = smf.database_id
Where sd.name not in ('master','tempdb','model','msdb')
Declare cur Cursor For
Select databaseName,
datafile
From @dataFiles
Open cur
Fetch Next
From cur
Into @databaseName,
@dbfile
While @@Fetch_Status = 0
Begin
Set @SQL = 'USE [' + @databasename + ']
DBCC SHRINKFILE (''' + @dbfile + ''', 10) WITH NO_INFOMSGS'
Exec sp_executeSQL @SQL
Fetch Next
From cur
Into @databaseName,
@dbfile
End
Close cur
Deallocate cur
select sd.name As DatabaseName, smf.name DBFileName, (size*8)/1024 SizeMB
from sys.sysdatabases sd
join sys.master_files smf
On sd.[dbid] = smf.database_id
Where sd.name not in ('master','tempdb','model','msdb')