代码实现SQL SERVER TCP/IP协议配置
SET NOCOUNT ON DECLARE @Root NVARCHAR(1000) ,@Path NVARCHAR(1000) ,@TcpPort NVARCHAR(100) SET @Root = 'HKEY_LOCAL_MACHINE' SET @Path = 'SoftwareMicrosoftMSSQLServerMSSQLServerSuperSocketNetLibTcp' SET @TcpPort = '2433' PRINT N'TcpPort ' + @TcpPort EXEC xp_instance_regwrite @Root, @Path, N'Enabled', REG_DWORD, 1 -- 启用TCP/IP协议 EXEC xp_instance_regwrite @Root, @Path, N'ListenOnAllIPs', REG_DWORD, 0 --禁止全部监听 DECLARE @t TABLE (KeyName NVARCHAR(1000)) INSERT INTO @t EXEC xp_instance_regenumkeys @Root, @Path -- IP1、IP2、IP3...IPALL DECLARE @CurrentKey NVARCHAR(200) ,@CurrentPath NVARCHAR(1000) ,@CurrentIP NVARCHAR(1000) ,@Enabled INT DECLARE C CURSOR FAST_FORWARD FOR SELECT KeyName FROM @t OPEN C FETCH NEXT FROM C INTO @CurrentKey WHILE @@fetch_status = 0 BEGIN SET @CurrentPath = @Path + '' + @CurrentKey EXEC xp_instance_regwrite @Root, @CurrentPath, N'TcpPort', REG_SZ, @TcpPort EXEC xp_instance_regwrite @Root, @CurrentPath, N'TcpDynamicPorts', REG_SZ, N'' IF @CurrentKey != 'IPALL' BEGIN EXEC xp_instance_regread @Root, @CurrentPath, N'IpAddress', @CurrentIP OUT SET @Enabled = CASE WHEN @CurrentIP LIKE '10.%' OR @CurrentIP LIKE '172.[123][0-9].%' OR @CurrentIP LIKE '192.168.%' OR @CurrentIP = '127.0.0.1' THEN 1 ELSE 0 END -- 只启用内网IP PRINT @CurrentKey + ' - ' + @CurrentIP + ' - ' + CASE WHEN @Enabled = 1 THEN 'Enable' ELSE 'Disable' END EXEC xp_instance_regwrite @Root, @CurrentPath, N'Active', REG_DWORD, @Enabled EXEC xp_instance_regwrite @Root, @CurrentPath, N'Enabled', REG_DWORD, @Enabled END FETCH NEXT FROM C INTO @CurrentKey; END CLOSE C; DEALLOCATE C;