Space Used for database files

  • In EM, you can display the space used for each database files (.MDF, .NDF, .LDF) using Task Pad. Is there a way to find the space used for each database file of a database using transact-sql ?

    Thanks,

    Jimmy

  • sp_helpfile will show you the files sizes.

    --
    Adam Machanic
    whoisactive

  • I tested. But sp_helpfile only provides allocated space.

  • Grasshoper - Thanks for the reply. I think you misunderstood what I want. Sp_Spaceused does not provide space used for a given .MDF or .LDF file.

  • I just found out an undocumented command that provides the info I need:

    DBCC ShowFileStats

    and space used = UsedExtents * 64.0 / 1024.0

  • Try SELECT * FROM SYSFILES

    may help u

  • Why not see what EM fires - set up a profiler trace on a db and then use EM to display the db in TaskPad view - it'll show you exactly what EM fires - all T-SQL commands (including dbcc showfilestats).

  • For getting actual file used if you are using single file you can use command

     

    dbcc sqlperf(logspace)

  • We have a job that runs and populates a table and we query the table to generate a weekly report.  The job executes the following statement...

    insert into yourDB.dbo.yourTableName (db, fileID, filesize)

     exec sp_MSforeachdb @command1 =

      'select db_name(dbid), sf.fileid, sf.size

      from sysdatabases sd, ?..sysfiles sf

      where db_name(dbid) = ''?'''

  • FILEPROPERTY will return used space. Use the following code to get the total size (MB) and the used space (MB) for each file in the current db:

     DECLARE @bytesperpage dec(18,0)

     , @pagesperMB dec(18,3)

     -- get number of bytes per page

     SELECT @bytesperpage = low

     FROM master.dbo.spt_values

     WHERE number = 1 and type = 'E'

     -- get number of page for 1 MB

     SELECT @pagesperMB = 1048576 / @bytesperpage

                                  

     SELECT a.name AS LogicalFileName,

      CASE WHEN groupid=0 THEN 1 ELSE 0 END AS IsLogFile,

      CAST(a.size/@pagesperMB as dec(16,3)) as FileSizeMB,

      CAST(CAST(FILEPROPERTY(a.name,'SpaceUsed') as int)/@pagesperMB as dec(16,3)) AS UsedSpaceMB

     FROM sysfiles a

     

     

  • Thank you all for the help.

    Grasshoper - Your solution using FILEPROPERTY function is the best ! Please allow me to futher simplify as followed:

    SELECT FILEPROPERTY(DbFileLogicalName, 'Spaceused') * 8.0 / 1024.0

    Thank you so much,

    Jimmy

Viewing 11 posts - 1 through 10 (of 10 total)

You must be logged in to reply to this topic. Login to reply