views:

33

answers:

2

In SQL Server Management Studio, there is an option to set the default database path for a given instance:

alt text

This works. When I say

CREATE DATABASE test

it gets created in the path I specify, E:\data. Great.

But how do I get this path in T-SQL (for use in setup scripts)?

Contrary to what many pages say, there is no registry key (on my machine) for DefaultData or DefaultLog. I am running SQL Server 2005 Express on XP 64.

This value has got to be stored somewhere. Where?

+1  A: 

Use SYS.DATABASE_FILES:

SELECT df.physical_name
  FROM SYS.DATABASE_FILES df

SYS.DATABASE_FILES.type_desc

  • ROWS = mdf location, includes mdf filename
  • LOG = ldf location, includes ldf filename
OMG Ponies
Thanks for the reply. I didn't mention, I've also seen this suggested. For me, it returns the original default DB location, **C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\master.mdf**
harpo
+2  A: 

Do you have access to SQL Profiler?

I don't have SQL 2005 Express installed but when I view that properties page on my machine with Profiler running I can see where SQL Server retrieves it from on my SQL 2008 instance.

declare @SmoDefaultFile nvarchar(512)

exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', 
 N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultData', 
  @SmoDefaultFile OUTPUT

select ISNULL(@SmoDefaultFile,N'') AS [DefaultFile]

Edit: The above also works for me on SQL Server 2005 Developer edition but only after I changed the default path to something other than the default.

Martin Smith
By the way, the technique of using the profiler to watch the value is very clever!
harpo
Thanks, this works, on my XP machine, my Vista machine, and a 2008 instance on Windows 7. (Note that the instance needs to be restarted for the default location to take effect). Also, this code will return an empty string if the original default location is being used, so a really robust solution would have to read both. Strangely, this subtree does not appear in the Registry Editor. Fortunately, I don't care about such mysteries at the moment. Thanks again!
harpo