what are registry settings to enable TCP on SQL Se

2019-05-02 10:07发布

问题:

I want to programatically enable TCP connections on SQL Server. I believe we can achieve this by modifying registry entries and restarting SQL Server service. What registry should I edit?

回答1:

Unless you have a good reason for modifying the registry directly, I suggest you consider using WMI. WMI will provide you with a more version agnostic implementation. WMI can be accessed through the System.Management namespace. You could have code that looks something like this.

public void EnableSqlServerTcp(string serverName, string instanceName)
{
    ManagementScope scope =
            new ManagementScope(@"\\" + serverName +
                                @"\root\Microsoft\SqlServer\ComputerManagement");
    ManagementClass sqlService =
            new ManagementClass(scope,
                                new ManagementPath("SqlService"), null);
    ManagementClass serverProtocol =
            new ManagementClass(scope,
                                new ManagementPath("ServerNetworkProtocol"), null);

    sqlService.Get();
    serverProtocol.Get();

    foreach (ManagementObject prot in serverProtocol.GetInstances())
    {
        prot.Get();
        if ((string)prot.GetPropertyValue("ProtocolName") == "Tcp" &&
            (string)prot.GetPropertyValue("InstanceName") == instanceName)
        {
            prot.InvokeMethod("SetEnable", null);
        }
    }

    uint sqlServerService = 1;
    uint sqlServiceStopped = 1;
    foreach (ManagementObject instance in sqlService.GetInstances())
    {
        if ((uint)instance.GetPropertyValue("SqlServiceType") == sqlServerService &&
            (string)instance.GetPropertyValue("ServiceName") == instanceName)
        {
            instance.Get();
            if ((uint)instance.GetPropertyValue("State") != sqlServiceStopped)
            {
                instance.InvokeMethod("StopService", null);
            }
            instance.InvokeMethod("StartService", null);
        }
    }
}

This code assumes a project reference to System.Management.dll and the following using statement:

using System.Management;

The Sql Protocols blog has an article that goes into some detail as to what the above code is doing.

Note: If a firewall is blocking the port(s) you will still be unable to access the server via TCP.



回答2:

Take a look at HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQLServer\SuperSocketNetLib\Tcp hive. There are keys like Enabled, ListenOnAllIPs and a list of IP addresses to listen on.