日期:2014-05-17  浏览次数:20641 次

SQL Server语句获得数据库及磁盘信息
1.怎样用SQL语句得到Database文件的大小?(mdf/ldf或ndf)
2.怎样用SQL语句得到database文件所在磁盘空间的大小及磁盘空闲空间大小?如同数据名称右键--报表--标准报表--Disk usage   
3.怎样用SQL语句得到数据库中各表的记录数,预留空间大小 数据空间大小 索引空间大小 空闲空间大小?
如同数据名称右键--报表--标准报表--Disk usage by table
4.怎样用SQL语句每个表中记录的条数、预留空间大小、使用空间大小? 如同数据名称右键--报表--标准报表--Disk usage by Partition

谢谢!

------解决方案--------------------
1.怎样用SQL语句得到Database文件的大小?(mdf/ldf或ndf)
当前数据库:SELECT * FROM sys.database_files
2.怎样用SQL语句得到database文件所在磁盘空间的大小及磁盘空闲空间大小?如同数据名称右键--报表--标准报表--Disk usage   
xp_fixeddrives其他的暂时没现成脚本
------解决方案--------------------

-- 1.怎样用SQL语句得到Database文件的大小?(mdf/ldf或ndf)
select file_id,name,type_desc,size*8/1024 'FileSize(MB)' from [数据库名].sys.database_files


-- 2.怎样用SQL语句得到database文件所在磁盘空间的大小及磁盘空闲空间大小?如同数据名称右键--报表--标准报表--Disk usage
select file_id,name,type_desc,size*8/1024 'FileSize(MB)' from [数据库名].sys.database_files

exec xp_fixeddrives

exec xp_cmdshell 'fsutil volume diskfree C:'


-- 3.怎样用SQL语句得到数据库中各表的记录数,预留空间大小 数据空间大小 索引空间大小 空闲空间大小?如同数据名称右键--报表--标准报表--Disk usage by table
exec sp_MSforeachtable "exec sp_spaceused '?'"
 

-- 4.怎样用SQL语句每个表中记录的条数、预留空间大小、使用空间大小? 如同数据名称右键--报表--标准报表--Disk usage by Partition
exec sp_MSforeachtable "exec sp_spaceused '?'"

------解决方案--------------------
dbcc showcontig
------解决方案--------------------
引用:
有怎样的SQL可以得sp_spaceused一样的两个记录集数据呢(字段如下)?
 
记录集1、database_name,database_size,unallocated space
记录集2、reserved,data,index_size,unused 


先建个存储过程:



create procedure dbo.proc_spaceused 
@flag int = 1
as  

declare @objname nvarchar(776) = null

declare @id int   -- The object id that takes up space  
  ,@type character(2) -- The object type.  
  ,@pages bigint   -- Working variable for size calc.  
  ,@dbname sysname  
  ,@dbsize bigint  
  ,@logsize bigint  
  ,@reservedpages  bigint  
  ,@usedpages  bigint  
  ,@rowCount bigint  
  

/*  
**  Check to see that the objname is local.  
*/  
if @objname IS NOT NULL  
begin  
  
  select @dbname = db_name()  
  
 /*  
 **  Try to find&n