SHARE
Facebook X Pinterest WhatsApp

Script to Get Dynamic Port on Which the SQL Server Instance Listens

Oct 2, 2002


As every SQL Server DBA might be aware, the default port for SQL Server on which it listens is 1433. But this holds only for the
default instance. In a multi-instance environment, the port allocation is dynamic and is potentially different every time SQL Server is restarted. This script can be used to find the dynamic port of an instance, by scanning the registry.

This script gets the current instance name on the fly and needs NO customization. The script supports both SQL Server 7.x and SQL Server 2000.

Author: Vijay Anisetti

-- This script will get the listening port of the 
-- SQL Server, useful for multiple instance servers
-- Vijay Anisetti

CREATE TABLE #GetPort
(
token varchar(100),
value varchar(20))
go

DECLARE @inst varchar(200)
DECLARE @inst1 varchar(100)
IF(charindex('',@@servername) > 0) 
BEGIN
  SELECT @inst = substring(@@servername,charindex('',@@servername),50)
  SELECT @inst = 'SOFTWAREMicrosoftMicrosoft SQL
Server'+@inst+'MSSQLServerSuperSocketNetLibTcp'
  SELECT @inst1 = 'TcpDynamicPorts'
END
 ELSE
BEGIN
  SELECT @inst =
'SOFTWAREMicrosoftMSSQLServerClientSuperSocketNetLibTcp'
  SELECT @inst1 = 'DefaultPort'
END

INSERT #GetPort
    EXEC master..xp_regread 'HKEY_LOCAL_MACHINE', @inst, @inst1 

SELECT value FROM #GetPort
DROP TABLE #GetPort

Back to Database Journal Home

Recommended for you...

What Backups Do I Have?
Gregory Larsen
May 12, 2021
Improving the Performance of a Table Variable using Optimizer Hint RECOMPILE
Gregory Larsen
Apr 1, 2021
TYPE Definition Change in Oracle 21c
Tip 74 – Changing Cost Threshold for Parallelism
Gregory Larsen
Feb 24, 2021
Database Journal Logo

DatabaseJournal.com publishes relevant, up-to-date and pragmatic articles on the use of database hardware and management tools and serves as a forum for professional knowledge about proprietary, open source and cloud-based databases--foundational technology for all IT systems. We publish insightful articles about new products, best practices and trends; readers help each other out on various database questions and problems. Database management systems (DBMS) and database security processes are also key areas of focus at DatabaseJournal.com.

Property of TechnologyAdvice. © 2025 TechnologyAdvice. All Rights Reserved

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.