How to get current instance name from T-SQL

后端 未结 8 1013
天命终不由人
天命终不由人 2021-01-30 05:18

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

相关标签:
8条回答
  • 2021-01-30 05:21

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

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

    0 讨论(0)
  • 2021-01-30 05:22

    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

    0 讨论(0)
  • 2021-01-30 05:23

    I found this:

    EXECUTE xp_regread
            @rootkey = 'HKEY_LOCAL_MACHINE',
            @key = 'SOFTWARE\Microsoft\Microsoft SQL Server',
            @value_name = 'InstalledInstances'
    

    That will give you list of all instances installed in your server.


    The ServerName property of the SERVERPROPERTY function and @@SERVERNAME return similar information. The ServerName property provides the Windows server and instance name that together make up the unique server instance. @@SERVERNAME provides the currently configured local server name.

    And Microsoft example for current server is:

    SELECT CONVERT(sysname, SERVERPROPERTY('servername'));
    

    This scenario is useful when there are multiple instances of SQL Server installed on a Windows server, and the client must open another connection to the same instance used by the current connection.

    0 讨论(0)
  • 2021-01-30 05:30

    To get the list of server and instance that you're connected to:

    select * from Sys.Servers
    

    To get the list of databases that connected server has:

    SELECT * from sys.databases;
    
    0 讨论(0)
  • 2021-01-30 05:34

    another method to find Instance name- Right clck on Database name and select Properties, in this part you can see view connection properties in left down corner, click that then you can see the Instance name.

    0 讨论(0)
  • 2021-01-30 05:35

    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)

    0 讨论(0)
提交回复
热议问题