List and correct DBs that are negatively grown
This script will list out database(s) which has Unallocated space in negative and also generate script for correcting these.
DBA needs to run the generated script to correct problem.
set nocount on
declare @dbname sysname
declare @dbsize dec(15,0)
declare @indsize dec(15)
declare @logsize dec(15)
declare @bytesperpagedec(15,0)
declare @pagesperMBdec(15,0)
declarecur_ChkSpace cursor for select name from master..sysdatabases order by name
open cur_ChkSpace
fetch cur_ChkSpace into @dbname
create table #dbsize
(
dbsize dec(15,0)
)
create table #logsize
(
logsize dec(15)
)
create table #indsize
(
indsize dec(15)
)
declare @vStmt varchar(500)
create table #tblTmpDBDetail
(
database_name sysname,
database_sizevarchar(20),
unallocated_space varchar(20)
)
create table #tblTmpUpdUsgScript
(
scriptnvarchar(2000)
)
while @@fetch_status = 0
begin
set @vStmt = 'select sum(convert(dec(15),size))'
set @vStmt = @vStmt + ' from ' + @dbname + '.dbo.sysfiles'
set @vStmt = @vStmt + 'where (status & 64 = 0)'
insert into #dbsize exec(@vStmt)
select @dbsize = dbsize from #dbsize
set @vStmt = 'select sum(convert(dec(15),size))'
set @vStmt = @vStmt + ' from ' + @dbname + '.dbo.sysfiles'
set @vStmt = @vStmt + ' where (status & 64 <> 0)'
insert into #logsize exec(@vStmt)
select @logsize = logsize from #logsize
set @vStmt = 'select sum(convert(dec(15,0),reserved)) from ' + @dbname + '.dbo.sysindexes where indid in (0, 1, 255)'
insert into #indsize exec (@vStmt)
select @indsize = indsize from #indsize
--===============================================================
select @bytesperpage = low
from master.dbo.spt_values
where number = 1
and type = 'E'
select @pagesperMB = 1048576 / @bytesperpage
if left(ltrim(str((@dbsize - @indsize) / @pagesperMB,15,2)+ ' MB'),1) = '-'
begin
insert into #tblTmpDBDetail(database_name, database_size, unallocated_space)
select @dbname,
ltrim(str((@dbsize + @logsize) / @pagesperMB,15,2) + ' MB'),
ltrim(str((@dbsize - @indsize) / @pagesperMB,15,2)+ ' MB')
insert into #tblTmpUpdUsgScript(script)
values(char(13) + 'use ' + @dbname + char(13) + 'go ' + char(13) + 'sp_spaceused @updateusage=true')
end
fetch cur_ChkSpace into @dbname
end
close cur_ChkSpace
deallocate cur_ChkSpace
select * from #tblTmpDBDetail
select * from #tblTmpUpdUsgScript
drop table #tblTmpDBDetail
drop table #tblTmpUpdUsgScript
drop table #dbsize
drop table #logsize
drop table #indsize