Programmatically Change the default path for SQL Server Database creation

The extended stored procedure "xp_instance_regwrite" helps you read/write from the registry. You can use this stored procedure to programmatically change the path where the data files for a new SQL Server database gets created by default. Here’s how to use this stored procedure

USE [master]
GO
EXEC xp_instance_regwrite
N'HKEY_LOCAL_MACHINE',
N'Software\Microsoft\MSSQLServer\MSSQLServer',
N'DefaultData',
REG_SZ,
N'D:\MyDatabases'
GO

EXEC xp_instance_regwrite
N'HKEY_LOCAL_MACHINE',
N'Software\Microsoft\MSSQLServer\MSSQLServer',
N'DefaultLog',
REG_SZ,
N'D:\MyDatabases'
GO

Note: After running this query, a folder called ‘MyDatabases’ should exist in D drive before a new database is created, else you will get an error.


About The Author

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

2 comments:

Anonymous said...

didn't work dude........am using sql server 2008 and no 'mydatabases' folder created in 'd:'.. :-(

Anonymous said...

I think it's the wording of the poster's comments. The implication is that you need to create the folder, or you'll get an error.