For a non-LocalDb SQL Server, I can SELECT SERVERPROPERTY('ServerName')
to get the name of the server and the instance that I'm running on. For a LocalDb server, however, I get SERVERNAME\LOCALDB#SOMEHASH
. How can I get the local instance name?
SOLUTION:
The solution for getting the instance, working on both LocalDB and "normal" SQL Server instances:
DECLARE @serverName NVARCHAR(151)
IF SERVERPROPERTY('IsLocalDb') = 1
SELECT @serverName = 'np:\\.\pipe\' + CONVERT(NVARCHAR(128), SERVERPROPERTY('InstanceName')) + '\tsql\query'
ELSE
SELECT @serverName = CONVERT(NVARCHAR(128), SERVERPROPERTY('ServerName'))
Some background that I should have mentioned in the original question: We have a configuration database for our application. Among other things, it stores connection strings. For developer machines and integration tests, we want to be able to generate a database with a script, and have the connection string refer to the local instance. Thus, I need to have a working connection string (which LOCALDB#SOMEHASH
is not). Since there is some spread in edition of database server, I needed something that could handle both cases.