如何从T-SQL获取当前实例名称
如何使用T-SQL脚本获取当前连接的SQL Server服务器和实例名称?
刚刚find答案,在这个SO问题 (字面上,在问题内,没有任何答案):
SELECT @@servername
返回servername \实例,只要这不是默认实例
SELECT @@servicename
返回实例名称,即使这是默认值(MSSQLSERVER)
这个怎么样:
EXECUTE xp_regread @rootkey='HKEY_LOCAL_MACHINE', @key='SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQl', @value_name='MSSQLSERVER'
这将获得实例名称。 null
表示默认实例:
SELECT SERVERPROPERTY ('InstanceName')
SELECT @@servername
会给你数据作为server/instanceName
要只获取instanceName
你应该运行select @@ServiceName
查询。
我find了这个:
EXECUTE xp_regread @rootkey = 'HKEY_LOCAL_MACHINE', @key = 'SOFTWARE\Microsoft\Microsoft SQL Server', @value_name = 'InstalledInstances'
这将给你所有的实例安装在您的服务器的列表。
SERVERPROPERTY
函数的ServerName
属性和@@SERVERNAME
返回类似的信息。ServerName
属性提供了一起构成唯一服务器实例的Windows服务器和实例名称。@@SERVERNAME
提供当前configuration的本地服务器名称。
而当前服务器的微软例子是:
SELECT CONVERT(sysname, SERVERPROPERTY('servername'));
如果在Windows服务器上安装了多个SQL Server实例,并且客户端必须打开与当前连接使用的同一实例的另一个连接,则此scheme很有用。
为什么只停留在实例名称? 您可以使用以下方法清点您的SQL Server环境:
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