views:

170

answers:

3

How to get server name through code if SQL Server (Standard Edition) is installed.

We pass the server name while creating a connection string to connect SQL Server. Can we retrieve this value through code?

string sqlConnectionString = string.Format(
"user id={0};password={1};server={2};Trusted_Connection=no;database=TestDB;
connection timeout={3}",
dirDBinfo.UserName, dirDBinfo.Password, "ServerName", dirDBinfo.TimeOut);
+3  A: 

I'm not sure I understand what you want.

If you already have a connection string, and you are trying to extract the server name from it for use elsewhere, you can reverse-engineer it like so:

var parser = new SqlConnectionStringBuilder(connectionString);
var serverName = parser.DataSource;

If you are constructing your connection string for the first time, then:

  1. If you know that you want to connect to the SQL Server on the machine that your client code is executing on, then just use (local) for the server name. If the SQL Server has an instance name, then specify it like this: (local)\myinstancename.
  2. If you don't know in advance what server to connect to, then it's up to you to obtain that information from somewhere else.
Christian Hayter
I agree - it sounds like Ashish is trying to get the application to guess which server to use, which it simply can't do. Other than picking the default local instance via `(local)` the only other sensible option is to TELL the code which server to use. How you do that is up to you.
PD
A: 

Is the server on the local computer?
If so, set the server name to localhost.
If not, use SqlDataSourceEnumerator.


Also, instead of building a connection string using String.Format, you should use a SqlConnectionStringBuilder. This will handle values with semicolons.

For example:

var builder = new SqlConnectionStringBuilder();

builder.UserID = dirDBinfo.UserName;
builder.Password = dirDBinfo.Password;
builder.Server= "localhost";
builder.UserID = dirDBinfo.UserName;
builder["Trusted_Connection"] = "no";
builder.Database = "TestDB"
builder.ConnectTimeout = dirDBinfo.TimeOut;
SLaks
localhost only works if it's not a named instance
Russell Steen
A: 

Can't you just execute SELECT @@SERVERNAME against this connection?

DmitryK
no; he's trying to build a connection string.
SLaks
so we are still building our connection string? In this case what is the logic that determines which SQL server to choose? If it is local, then as you said - just use localhost. But I thought we already had server name passed and now we need to retrieve it somehow in the code...
DmitryK
As I understand the question, that's what he's asking.
SLaks