SQL: Get Database Name From Physical Name

Here’s a SQL Function to get name of the database from it’s physical full name.

This function can be used in conjunction with RESTORE FILELISTONLY which can generate physicalname,  the parameter of this function, from a database’s backup file.

You can read more about RESTORE FILELISTONLY here.

create function get_db_name_from_physical_name
(@physicalname varchar(500))
returns varchar

declare @dbName as varchar(500)

select @dbName =  DB_NAME(database_id) from sys.master_files where name = @physicalname

return @dbName