Sqlserver
 sql >> Base de Dados >  >> RDS >> Sqlserver

Obter lista de banco de dados depende do servidor escolhido


É assim que você obtém uma lista de nomes de servidores na rede:
List<String> ServerNames = new List<String>();

 SqlDataSourceEnumerator servers = SqlDataSourceEnumerator.Instance;
 DataTable serversTable = servers.GetDataSources();

     foreach (DataRow row in serversTable.Rows) {
            string serverName = row[0].ToString();

             try {

                if (row[1].ToString() != "") {

                            serverName += "\\" + row[1].ToString();

                }


              }
              catch {


              }

              ServerNames.Add(serverName);
      }

Para obter uma lista de bancos de dados do servidor selecionado:
List<String> databases = new List<String>();

SqlConnectionStringBuilder connection = new SqlConnectionStringBuilder();

 connection.DataSource = SelectedServer;
 // enter credentials if you want
 //connection.UserID = //get username;
// connection.Password = //get password;
 connection.IntegratedSecurity = true;

 String strConn = connection.ToString();

 //create connection
  SqlConnection sqlConn = new SqlConnection(strConn);

//open connection
sqlConn.Open();

 //get databases
DataTable tblDatabases = sqlConn.GetSchema("Databases");

//close connection
sqlConn.Close();

//add to list
foreach (DataRow row in tblDatabases.Rows) {
      String strDatabaseName = row["database_name"].ToString();

       databases.Add(strDatabaseName);


}