Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
cplusplus
// build the connection string
TCHAR ComputerNameBuffer[MAX_COMPUTERNAME_LENGTH + 1];
DWORD ComputerNameBufferLength = MAX_COMPUTERNAME_LENGTH + 1;
GetComputerName(ComputerNameBuffer, &ComputerNameBufferLength);
CString ConnectionString = _T("Provider=SQLOLEDB;")
                           _T("Integrated Security=SSPI;")
                           _T("Initial Catalog=MyDataBase;")
                           _T("Data Source=");
ConnectionString += ComputerNameBuffer;
ConnectionString += _T("\\MyServerInstance;"); // need this to be a variable
How can I programmatically get the name of MyServerInstance?

Thanks


Solution:

I ended up using the SQLBrowseConnect[^] function through the CodeProject article SQL Server and Database Enumerator[^].
cplusplus
CString GetServer()
{
    CString Server = _T("");
    CSQLInfoEnumerator SQLInfoEnumerator;
    SQLInfoEnumerator.EnumerateSQLServers();
    for (INT_PTR i = 0; i < SQLInfoEnumerator.m_szSQLServersArray.GetSize(); ++i)
    {
        SQLInfoEnumerator.EnumerateDatabase(SQLInfoEnumerator.m_szSQLServersArray[i], _T(""), _T(""));
        for (INT_PTR j = 0; j < SQLInfoEnumerator.m_szSQLServerDatabaseArray.GetSize(); ++j)
        {
            if (SQLInfoEnumerator.m_szSQLServerDatabaseArray[j] == _T("MyDataBase"))
            {
                Server = SQLInfoEnumerator.m_szSQLServersArray[i];
                break;
            }
        }
    }
    return Server;
}
Posted
Updated 8-Jan-11 10:05am
v5
Comments
Yusuf 8-Jan-11 22:40pm    
I like when people post their solution. +5

go through the below link this may helps you

Locate SQL Server instances on the local network[^]
 
Share this answer
 
Comments
Hiren solanki 6-Jan-11 4:14am    
Good one rajesh, +5
Rajesh Anuhya 6-Jan-11 4:14am    
Thank You
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900