Reading the SQL 2005 instance and installation directory from a DOS batch file - Jon Galloway

Reading the SQL 2005 instance and installation directory from a DOS batch file

SQL 2005 installs each instance to a numbered directory based on the order installed: MSSQL.1, MSSQL.2, etc. That makes scripting a little tricky. Fortunately, you can find them in the registry.

The install path for the SQL 2005 database server is here:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\SQL2005\Setup\SQLPath

You can look up specific instances in the the Instance Names registry node. For instance, to find the SQL2005 instance, you'd look at this key:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL\SQL2005

Looking up registry values in a DOS batch file is a little tricky. Fortunately, Robert VanderWoude has a great tip for reading registry values via creative use of the FOR /F command.

So, with all that out of the way, we can read the SQL Server instance with this line:

FOR /F "tokens=2* delims= " %%A IN ('REG QUERY "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL" /v SQL2005') DO SET SQLINSTANCE=%%B

and the SQL Server base installation directory with this:

FOR /F "tokens=2* delims= " %%A IN ('REG QUERY "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\SQL2005\Setup" /v SQLPath') DO SET DATADIRECTORY=%%B\Data

Why would you want to read that kind of stuff in a batch file? Well, to write a Batch files to check SQL 2005 (MDF) files in and out of Subversion source control, or course.

Published Saturday, October 28, 2006 10:19 PM by Jon Galloway

Comments

# re: Reading the SQL 2005 instance and installation directory from a DOS batch file

Is there any way to determine an instance through a T-SQL query?

Thursday, May 17, 2007 1:17 PM by Will Hutton

# re: Reading the SQL 2005 instance and installation directory from a DOS batch file

Didn't find this path(HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL\SQL2005) in registry to find the sql sever instance.

Monday, April 21, 2008 1:46 AM by baddy

# re: Reading the SQL 2005 instance and installation directory from a DOS batch file

I got the following error

%%A was unexpected at this time

Thursday, May 06, 2010 3:29 AM by Test

# re: Reading the SQL 2005 instance and installation directory from a DOS batch file

Ditto on not finding the key in the registry.  I have Microsoft SQL Server 2005 - 9.00.4035.00

Wednesday, August 18, 2010 9:05 AM by Jean-Pierre Fouche

Leave a Comment

(required) 
(required) 
(optional)
(required)