CREATE      PROCEDURE [dbo].[CheckSpace]as
begin
DECLARE @PageSize float 
declare @dbname sysname
declare @sqlstr nvarchar(1000)
declare @ldf float,@mdf float,@mdfuse float

SELECT @PageSize=v.low/1024.0 FROM master..spt_values v WHERE v.number=1 AND v.type='E' create table #tmplogspc (DatabaseName sysname, LogSize float, SpaceUsedPerc float, Status bit)
insert #tmplogspc EXEC ('dbcc sqlperf(logspace)')
--select * from #tmplogspc create table #tmpdbspc (DBname sysname, ldfuse float,ldf float,mdfuse float,mdf float,Status bit)
insert #tmpdbspc select DatabaseName,Logsize*SpaceUsedPerc*10.24,0,0,0,0 from #tmplogspc while (exists (select 1 from #tmpdbspc where Status =0))
begin
select top 1 @dbname = DBname  from #tmpdbspc where Status =0
set @sqlstr='select @ldf=size* '+ ltrim(@PageSize)+' from '+@dbname+'.dbo.sysfiles where groupid = 0' 
exec sp_executesql @sqlstr,N' @ldf float output',@ldf output 
set @sqlstr='select @mdf=size* '+ ltrim(@PageSize)+' from '+@dbname+'.dbo.sysfiles where groupid = 1' 
exec sp_executesql @sqlstr,N' @mdf float output',@mdf output
update #tmpdbspc set ldf=@ldf,mdf=@mdf,Status=1 where DBname=@dbname
end create table #tmpmdfspc (Fileid int, FileGroup int, TotalExtents int, UsedExtents int, Name sysname, FileName nchar(520))
while (exists (select 1 from #tmpdbspc where Status =1))
begin
select top 1 @dbname = DBname  from #tmpdbspc where Status =1
set @sqlstr='use '+@dbname+'  insert into #tmpmdfspc EXEC (''dbcc showfilestats'')'
exec sp_executesql @sqlstr
update #tmpdbspc set Status=0 where DBname=@dbname
end update #tmpdbspc set mdfuse = (select UsedExtents*64 from #tmpmdfspc where #tmpmdfspc.Name = #tmpdbspc.DBname)
update #tmpdbspc set mdfuse = (select UsedExtents*64  from #tmpmdfspc where #tmpmdfspc.Name = 'tempdev') where (DBname='tempdb' and mdfuse is null)
update #tmpdbspc set mdfuse = (select UsedExtents*64  from #tmpmdfspc where #tmpmdfspc.Name = 'modeldev') where (DBname='model' and mdfuse is null)
update #tmpdbspc set mdfuse = (select UsedExtents*64  from #tmpmdfspc where #tmpmdfspc.Name = 'MSDBData') where (DBname='msdb' and mdfuse is null)
if exists (select 1 from #tmpdbspc where DBname='AdventureWorksDW')
begin
update #tmpdbspc set mdfuse = (select UsedExtents*64  from #tmpmdfspc where #tmpmdfspc.Name = 'AdventureWorksDW_Data') where (DBname='AdventureWorksDW' and mdfuse is null)
update #tmpdbspc set mdfuse = (select UsedExtents*64  from #tmpmdfspc where #tmpmdfspc.Name = 'AdventureWorks_Data') where (DBname='AdventureWorks' and mdfuse is null)
end drop table #tmpmdfspc
drop table #tmplogspc select * from #tmpdbspc drop table #tmpdbspc
end查询当前SQLSERVER上面所有数据库的空间使用情况,mdf-数据文件分配空间,ldf-日志文件分配空间,mdfuse,ldfuse已使用的空间,单位是k