How to get current instance name from T-SQL

后端 未结 8 1023
天命终不由人
天命终不由人 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:35

    Just to add some clarification to the registry queries. They only list the instances of the matching bitness (32 or 64) for the current instance.

    The actual registry key for 32-bit SQL instances on a 64-bit OS is:

    HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server
    

    You can query this on a 64-bit instance to get all 32-bit instances as well. The 32-bit instance seems restricted to the Wow6432Node so cannot read the 64-bit registry tree.

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

    Why stop at just the instance name? You can inventory your SQL Server environment with following:

    SELECT  
        SERVERPROPERTY('ServerName') AS ServerName,  
        SERVERPROPERTY('MachineName') AS MachineName,
        CASE 
            WHEN  SERVERPROPERTY('InstanceName') IS NULL THEN ''
            ELSE SERVERPROPERTY('InstanceName')
        END AS InstanceName,
        '' as Port, --need to update to strip from Servername. Note: Assumes Registered Server is named with Port
        SUBSTRING ( (SELECT @@VERSION),1, CHARINDEX('-',(SELECT @@VERSION))-1 ) as ProductName,
        SERVERPROPERTY('ProductVersion') AS ProductVersion,  
        SERVERPROPERTY('ProductLevel') AS ProductLevel,
        SERVERPROPERTY('ProductMajorVersion') AS ProductMajorVersion,
        SERVERPROPERTY('ProductMinorVersion') AS ProductMinorVersion,
        SERVERPROPERTY('ProductBuild') AS ProductBuild,
        SERVERPROPERTY('Edition') AS Edition,
        CASE SERVERPROPERTY('EngineEdition')
            WHEN 1 THEN 'PERSONAL'
            WHEN 2 THEN 'STANDARD'
            WHEN 3 THEN 'ENTERPRISE'
            WHEN 4 THEN 'EXPRESS'
            WHEN 5 THEN 'SQL DATABASE'
            WHEN 6 THEN 'SQL DATAWAREHOUSE'
        END AS EngineEdition,  
        CASE SERVERPROPERTY('IsHadrEnabled')
            WHEN 0 THEN 'The Always On Availability Groups feature is disabled'
            WHEN 1 THEN 'The Always On Availability Groups feature is enabled'
            ELSE 'Not applicable'
        END AS HadrEnabled,
        CASE SERVERPROPERTY('HadrManagerStatus')
            WHEN 0 THEN 'Not started, pending communication'
            WHEN 1 THEN 'Started and running'
            WHEN 2 THEN 'Not started and failed'
            ELSE 'Not applicable'
        END AS HadrManagerStatus,
        CASE SERVERPROPERTY('IsSingleUser') WHEN 0 THEN 'No' ELSE 'Yes' END AS InSingleUserMode,
        CASE SERVERPROPERTY('IsClustered')
            WHEN 1 THEN 'Clustered'
            WHEN 0 THEN 'Not Clustered'
            ELSE 'Not applicable'
        END AS IsClustered,
        '' as ServerEnvironment,
        '' as ServerStatus,
        '' as Comments
    
    0 讨论(0)
提交回复
热议问题