27

I need a T-SQL query for a list of all databases in SQL Server 2008 showing

  • the name of the database and
  • the location of the .mdf and .ldf files.
4
  • Please use the table, sys.database_files Nov 21, 2014 at 8:32
  • @MehdiHaghshenas If you spend 2 minutes on Google, mssql get all databases and locations returned 26 million results.
    – Jaques
    Nov 21, 2014 at 8:49
  • 2
    ironically, this question is now the third result when googling the exact search phrase suggested above
    – rdans
    Apr 18, 2016 at 11:26
  • 7
    Voting to reopen. It does not matter how much effort the OP put in it; it's now a high-ranking result on Google and apparently helps a lot of people.
    – Heinzi
    Apr 25, 2016 at 14:13

3 Answers 3

56
SELECT
    db.name AS DBName,
    type_desc AS FileType,
    Physical_Name AS Location
FROM
    sys.master_files mf
INNER JOIN 
    sys.databases db ON db.database_id = mf.database_id

enter image description here

1
  • 4
    Instead of joining to databases table, you can SELECT DB_NAME(database_id) AS DBName
    – sam yi
    Jul 19, 2017 at 14:24
8

enter image description here

select 
    d.name as 'database',
    mdf.physical_name as 'mdf_file',
    ldf.physical_name as 'log_file'
from sys.databases d
inner join sys.master_files mdf on 
    d.database_id = mdf.database_id and mdf.[type] = 0
inner join sys.master_files ldf on 
    d.database_id = ldf.database_id and ldf.[type] = 1
1
  • I don't like this solution because it gets complicated if there are many mdf/log files per database. May 12, 2017 at 9:48
-4

Try this query:

SELECT name [Database Name], physical_name [File Location],size *(8.0 / 1024) /1024 [Size in GBs]
FROM sys.master_files
1
  • While this answers the question, this is basically a repeat of other answers. In this case the proper way to go about this is upvote other answers (once you have sufficient reputation), not repeat another answer.
    – TT.
    Sep 14, 2017 at 10:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.