Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current instance name from T-SQL

How can I get the SQL Server server and instance name of the current connection, using a T-SQL script?

like image 249
Guillermo Gutiérrez Avatar asked Aug 06 '13 00:08

Guillermo Gutiérrez


People also ask

How do I find the current server name in SQL Server?

Open up SQL Server Configuration Manager (search for it in the Start menu). Click on SQL Server Services . The instance name of SQL Server is in parenthesis inline with SQL Server service. If it says MSSQLSERVER, then it's the default instance.

How do I get a list of SQL Server instances?

To list all the SQL instances, navigate to the root directory and run the Get-Childitem to get the list. Note: The path SQLSERVER:\SQL\<ServerName> has all the installed SQL instances of the listed server.


3 Answers

Just found the answer, in this SO question (literally, inside the question, not any answer):

SELECT @@servername

returns servername\instance as far as this is not the default instance

SELECT @@servicename

returns instance name, even if this is the default (MSSQLSERVER)

like image 131
Guillermo Gutiérrez Avatar answered Oct 20 '22 02:10

Guillermo Gutiérrez


How about this:

EXECUTE xp_regread @rootkey='HKEY_LOCAL_MACHINE',
                   @key='SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQl',
                   @value_name='MSSQLSERVER'

This will get the instance name as well. null means default instance:

SELECT SERVERPROPERTY ('InstanceName')

http://technet.microsoft.com/en-us/library/ms174396.aspx

like image 31
Beno Avatar answered Oct 20 '22 04:10

Beno


SELECT @@servername will give you data as server/instanceName

To get only the instanceName you should run select @@ServiceName query .

like image 11
Shirishkumar Bari Avatar answered Oct 20 '22 04:10

Shirishkumar Bari