现在的位置: 首页 > 综合 > 正文

得到SQLSERVER 2005 数据库的当前数据库中的数据文件所在磁盘的剩余空间

2013年09月05日 ⁄ 综合 ⁄ 共 2063字 ⁄ 字号 评论关闭

----------------------------------------------------------------------------

---- 本文为andkylee个人原创,请在尊重作者劳动成果的前提下进行转载;

---- 转载务必注明原始出
:
http://blog.csdn.net/andkylee

--- 2010-05-18 18:29:45


---- 关键字:  sqlcmd sqlserver2005 sysfiles xp_fixeddrives 磁盘剩余空间

----------------------------------------------------------------------------

 

在csdn论坛上看到有人问,如何获取指定数据库所在磁盘的磁盘剩余空间。http://topic.csdn.net/u/20100518/16/70cae8d3-a9de-4e45-9f49-fe8b00d8ba74.html?seed=1945596721&r=65529065#r_65529065

 

解决的思路是,通过sysfiles系统表找到数据库所属数据文件所在的物理路径,从数据文件的物理路径中提取所在磁盘盘符(第一个字母),最后用扩展存储过程xp_fixeddrives来获得磁盘驱动器的剩余空间(MB Bytes)。

 

 

SQL语句如下:

 

我的测试环境是的结果如下:

1> declare @drivename char(1)
2> select @drivename=left(filename,1) from sysfiles where fileid=  1
3>
4> if not exists(select 1 from tempdb.dbo.sysobjects where name like '#FreeSpace
%' and type='U')
5>   create table #FreeSpace(
6>     Drive char(1),
7>     MB_Free int
8>     )
9> else
10>       truncate table #FreeSpace
11>
12> insert into #FreeSpace
13> exec xp_fixeddrives
14>
15> select MB_Free from #FreeSpace where Drive = @drivename
16> go

(3 行受影响)
MB_Free
-----------
      18905

(1 行受影响)
1>
2>
3> select filename from sysfiles
4> go
filename

--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------
D:/Program Files/Microsoft SQL Server/MSSQL.1/MSSQL/DATA/master.mdf

D:/Program Files/Microsoft SQL Server/MSSQL.1/MSSQL/DATA/mastlog.ldf

(2 行受影响)
1> xp_fixeddrives
2> go
drive MB 可用空间
----- -----------
C           26562
D           18905
E           22517

(3 行受影响)

 

 

 

上面的sql语句和csdn上帖子的发帖人要求的有点差距,

第一:指定数据库,这点很容易。直接select filename from <your_db_name>.dbo.sysfiles即可。

第二:某个数据库的数据文件可能跨越两个及以上不同的物理磁盘;所以@drivename变量有可能得到不唯一的值。可以考虑用游标来实现。

 

 

欢迎拍砖!

抱歉!评论已关闭.