Shrinking the space used by SQL databases.
Recently a customer asked me to see if I could reduce the amount of space being taken up by his databases. My immediate thought was to truncate and then shrink the log files.
This was a fantastic success! I managed to shrink the space used from 185 GB down to 11.5 GB – a huge saving. Here is the code snippet I used:
declare @ssql nvarchar(4000)
set @ssql= '
if ''?'' not in (''tempdb'',''master'',''model'',''msdb'') begin
use [?]
declare @tsql nvarchar(4000) set @tsql = ''''
declare @iLogFile int
declare LogFiles cursor for
select fileid from sysfiles where status & 0x40 = 0x40
open LogFiles
fetch next from LogFiles into @iLogFile
while @@fetch_status = 0
begin
set @tsql = @tsql + ''DBCC SHRINKFILE(''+cast(@iLogFile as varchar(5))+'', 1) ''
fetch next from LogFiles into @iLogFile
end
set @tsql = @tsql + '' BACKUP LOG [?] WITH TRUNCATE_ONLY '' + @tsql
--print @tsql
exec(@tsql)
close LogFiles
DEALLOCATE LogFiles
end'
exec sp_msforeachdb @ssql
0 comments:
Post a Comment