从 tcp 端口号获取 SQL 服务器实例名称

Getting SQL Server instance name from tcp port number

我有一个场景,其中我使用 -q 选项更改 SQL 服务器实例的排序规则。命令如下:

 sqlservr.exe -m -T4022 -T3659 -s"SQLexpress" -q"SQL_Latin1_General_CP1_CI_AI"

上面的命令完美运行,我的实例名称为“.\SQLExpress”。但是如果我想使用TCP端口号的实例名,比如“.,52407”,那么我该如何执行上面的命令,因为我得到以下错误:

SQL Server

Your SQL Server installation is either corrupt or has been tampered with (Error: Instance name exceeds maximum length). Please uninstall then re-run setup to correct this problem

我想从这个端口号中获取实例名称来解决这个问题。是否可以通过任何查询从 TCP 端口号获取实例名称?或者有没有其他方法可以通过TCP端口号执行上面的命令?

下面一段代码可以处理上述情况:

If($ServerInstanceName -like "*,*")
{
Write-Host "SQL Server Instance Name containts TCP Port Number"
$SQLQuery=@"
           SET NOCOUNT ON
           Declare @key Varchar(100), @PortNumber varchar(100)
           if charindex('\',CONVERT(varchar(200), 
           SERVERPROPERTY('servername')),0<>0
           begin
             set @key = 'SOFTWARE\MICROSOFT\Microsoft SQL Server\'+@@servicename+'\MSSQLServer\Supersocketnetlib\TCP'
           end
           else
           begin
             set @key = 'SOFTWARE\MICROSOFT\MSSQLServer\MSSQLServer\Supersocketnetlib\TCP'
           end
           EXEC master..xp_regread @rootkey='HKEY_LOCAL_MACHINE', @key=@key,@value_name='Tcpport',@value=@PortNumber OUTPUT
           SELECT CONVERT(varchar(200), SERVERPROPERTY('servername')) AS ServerName
         "@
$ServerInstanceName = (Invoke-Sqlcmd -ServerInstance 
$ServerInstanceName -Database 'master' -Query $SQLQuery).ServerName

Write-Host "Compatible ServerName (without TCP Port) to change its Collation:" $ServerInstanceName