2

Can u people Help me How to get the sqlserver name used by sharepoint programatically?? is there any such api provided like i have installed sharepoint on the sqlnamed instance. How to get the sqlservername.

Thanks in Advance...

Cute
  • 13,643
  • 36
  • 96
  • 112

2 Answers2

5

This code should help you and you need to run this code from the SharePoint Server or WFE server.

        public String GetSharePointSQLServerName()
    {
        String sServerName = "notFound";
        foreach (var item in SPFarm.Local.Servers)
        {
            foreach (var svc in item.ServiceInstances)
            {
                 if (svc is SPDatabaseServiceInstance)
                {
                    SPDatabaseServiceInstance s = svc as SPDatabaseServiceInstance;                        
                    sServerName = item.DisplayName+"\\"+s.Instance;
                }
            }             
        }
        return sServerName;
    }
Kusek
  • 5,384
  • 2
  • 25
  • 49
  • Here I am getting the server name as "Demo-64-Test".But i have installed sqlserver as Named instance. "Demo-64-Test\SQLNamed".I have to get this one. – Cute Nov 09 '09 at 04:23
  • @Kusek:Thnks It Helps me.But i have a Doubt.If i Installed The sqlserver as Default one then it gives the Default instance only??is is possible with above code?? – Cute Nov 09 '09 at 06:38
  • HI it is not getting the instance name in server farm??? is thee is other way to do this ??/ – Cute Nov 19 '09 at 13:31
  • @Cute: I have updated the Answer already to get the Instance of the DB Server. – Kusek Nov 20 '09 at 10:16
  • the same i have used but i am not getting it says the role as invalid for the machine whre my named sqlserver insatnce is installed in server farm – Cute Nov 20 '09 at 10:59
  • @Cute: I came across here by your question. I am also facing same issue. probably you could solved this issue. I have added my question : http://stackoverflow.com/questions/7244370/sharepoint-2010-topology-with-this-issue here. so can you please guide me. I am using sharepoint 2010. – Red Swan Aug 30 '11 at 14:00
0

So what is if you do not have a named database instance?

better you use this:

var serverNames = from server in SPFarm.Local.Servers
                  from service in server.ServiceInstances
                  where service is SPDatabaseServiceInstance
                  let dbInstance = (SPDatabaseServiceInstance) service
                  select dbInstance.NormalizedDataSource;

If you have multiple names for your sql server (like aliases) the returned collection will have multiple entries. Just take the first of the collection.

Doomdrake
  • 11
  • 1