如何使用T-SQL脚本获取SQL Server服务器和当前连接的实例名称?
Answers:
刚刚在这个SO问题中找到了答案(从字面上看,在问题内部,没有任何答案):
SELECT @@servername
如果不是默认实例,则返回servername \ instance
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
query。
我找到了这个:
EXECUTE xp_regread
@rootkey = 'HKEY_LOCAL_MACHINE',
@key = 'SOFTWARE\Microsoft\Microsoft SQL Server',
@value_name = 'InstalledInstances'
这将为您提供服务器中安装的所有实例的列表。
该函数的
ServerName
属性SERVERPROPERTY
与@@SERVERNAME
返回相似的信息。该ServerName
属性提供Windows服务器和实例名称,它们共同构成唯一的服务器实例。@@SERVERNAME
提供当前配置的本地服务器名称。
Microsoft当前服务器的示例是:
SELECT CONVERT(sysname, SERVERPROPERTY('servername'));
当Windows服务器上安装了多个SQL Server实例,并且客户端必须打开另一个连接到当前连接所使用的同一实例时,此方案非常有用。
为什么只停止实例名称?您可以通过以下方式清点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
要获取您连接到的服务器和实例的列表:
select * from Sys.Servers
要获取连接的服务器具有的数据库列表:
SELECT * from sys.databases;
SELECT @@SERVERNAME
产生使用连接所需的结果sqlcmd -S
。如果它是默认的MSSQLSERVER实例,则必须-S-参数中未指定它。这是2017年14.0.2002.14开发版,64位。