您的位置:首页 > 数据库

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

2010-05-18 18:18 471 查看
----------------------------------------------------------------------------

---- 本文为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语句如下:

declare @drivename char(1)
select @drivename=left(filename,1) from sysfiles where fileid=  1
if not exists(select 1 from tempdb.dbo.sysobjects where name like '#FreeSpace%' and type='U')
  create table #FreeSpace(
    Drive char(1),
    MB_Free int
    )
else
      truncate table #FreeSpace
      
insert into #FreeSpace 
exec xp_fixeddrives
select MB_Free from #FreeSpace where Drive = @drivename
go





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

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变量有可能得到不唯一的值。可以考虑用游标来实现。





欢迎拍砖!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐