DevPinoy.org
A Filipino Developers Community
   
Programmatically List All Databases In A SQL Server

There are alot of ways to accomplish this. The simplest one is to use the sp_databases procedure. Here's some example that uses this stored procedure in conjunction with ADO.NET to consume the returned data.

//######################################
//C# EXAMPLE
//######################################

[code language="C#"]

//using SqlAdapter and DataTable
using (SqlDataAdapter adapter = new SqlDataAdapter("sp_databases", connectionString))
{
    adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
    DataTable dataTable = new DataTable();

    adapter.Fill(dataTable);

    foreach (DataRow dataRow in dataTable.Rows)
    {
        Console.WriteLine(dataRow["DATABASE_NAME"]);
    }
}

//using SqlCommand and SqlReader
using (SqlCommand sqlCommand = new SqlCommand("sp_databases", new SqlConnection(connectionString)))
{
    sqlCommand.CommandType = CommandType.StoredProcedure;
    sqlCommand.Connection.Open();
    SqlDataReader sqlReader = sqlCommand.ExecuteReader();
   
    while (sqlReader.Read())
    {
        Console.WriteLine(sqlReader["DATABASE_NAME"]);
    }

    sqlReader.Close();
    sqlCommand.Connection.Close();
}

[/code]

'######################################
'VB.NET EXAMPLE
'######################################

[code language="VB.NET"]

'using SqlAdapter and DataTable
Using adapter As SqlDataAdapter = New SqlDataAdapter("sp_databases", connectionString)

 adapter.SelectCommand.CommandType = CommandType.StoredProcedure

 Dim table As New DataTable()

 adapter.Fill(table)

 For Each dr As DataRow In table.Rows
         Console.WriteLine(dr("DATABASE_NAME"))
 Next

End Using


'using SqlAdapter and DataTable
Using sqlCommand As SqlCommand = New SqlCommand("sp_databases", New SqlConnection(connectionString)))

 sqlCommand.CommandType = CommandType.StoredProcedure

 sqlCommand.Connection.Open()
 Dim sqlReader As SqlDataReader = sqlCommand.ExecuteReader()

 While (sqlReader.Read())
  Console.WriteLine(sqlReader("DATABASE_NAME"))
 End While

 sqlReader.Close()
 sqlCommand.Connection.Close()

End Using

[/code]


Posted 06-07-2006 2:16 PM by keithrull
Filed under:

Comments

cvega wrote re: Programmatically List All Databases In A SQL Server
on 06-07-2006 7:49 PM
That's a nice one. Have you got any working sample on how to enumerate databases using the SQLDMO/SQLSMO (thus without using connectionString)?.

-chris
Copyright DevPinoy 2005-2008