3

I would like to identify if the SQL Server I'm connecting to is on the local machine or not. I know there are plenty of ways to identify the server\instance names of a SQL Server when connecting to it, but there are so many different ways a server name might be specified, I don't want to do the comparison myself between IP Addresses, machine names, (local), LocalHost, ., etc.

Is there something in SQL Server (any versions 2000+) where I can check if the instance is on the local machine or not without doing a comparison of my own?

4
  • 1
    Duplicate of stackoverflow.com/questions/886543/… Commented Jan 7, 2013 at 13:45
  • For 2005+ maybe SELECT client_net_address FROM sys.dm_exec_connections WHERE session_id= @@SPID. Haven't looked into whether that would be reliable or not. Commented Jan 7, 2013 at 13:52
  • 1
    possible duplicate of How to tell if SQL Server is local or remote? That one gives you an alternative to @@SERVERNAME Commented Jan 7, 2013 at 15:07
  • @MartinSmith: Definitely not a duplicate of that question: The OP of that other question wants to compare host names (see "edit 1" in question body), while the OP of the present question wants to avoid doing exactly that. Commented Oct 7, 2014 at 7:13

2 Answers 2

4
SELECT Case when HOST_NAME()=
       Case When CharIndex('\',@@SERVERNAME)=0 then @@SERVERNAME else LEFT(@@SERVERNAME,CharIndex('\',@@SERVERNAME)-1) end
       then 'local' else 'remote' end

since @@SERVERNAME is defined on installation and could have been changed (even by sp_addserver) you would prefer:

SELECT Case when HOST_NAME()=SERVERPROPERTY('MachineName') then 'local' else 'remote' end
Sign up to request clarification or add additional context in comments.

5 Comments

So far I've tested with MyMachineName, (local), localhost, ., 192.168.1.100, 192.168.1.100, 1433, and it works great. Now to test on a named instance...
Did not work on a named instance MyMachineName\Instance - returns remote
@Jerry Dodge Can't reproduce what's HOST_NAME() and @@SERVERNAME output?
Uhmmm... very confused here, @@SERVERNAME is returning the name of a completely different machine, which I'm obviously not connected to ... ?????
Ohhhhhh the server name which it's returning in @@SERVERNAME is my OLD machine name - I've changed the machine name since then. Strange why this would still return the old machine name?
0
SELECT CASE WHEN CAST(SERVERPROPERTY('MachineName') AS VARCHAR(100)) = CAST(HOST_NAME() AS VARCHAR(100)) THEN 'LOCAL' 
ELSE 'REMOTE' 
END

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.