SQL Server: Get All Database Names

[1 minute read]

Just a simple script that returns the names of all databases in a given SQL Server instance.

IEnumerable<string> GetAllDatabaseNames(string serverName)
{
	var connectionString = string.Format("Data Source={0};Integrated Security=True", serverName);
	using (var connection = new SqlConnection(connectionString))
	{
		try
		{
			connection.Open();
		}
		catch (SqlException)
		{
			return null;
		}

		var commandBehavior = CommandBehavior.CloseConnection | CommandBehavior.SingleResult;
		using (var command = new SqlCommand("Select * from Sys.Databases", connection))
		using (var reader = command.ExecuteReader(commandBehavior))
		{

			var databaseNames = new List&lt;string&gt;();

			while (reader.Read())
				databaseNames.Add(reader.GetString(0));

			databaseNames.Sort();
			return databaseNames;
		}
	}