Retrieving a list of databases from SQL Server

This post is part of a series about my experiences building a PHP app for Windows Server 2008 and IIS 7 for the European WinPHP Challenge 2009 which is sponsored by iBuildings, Microsoft and Leaseweb.

I need to get a list of databases from SQL Server for the currently logged in user. Initially, I found a built in function sp_databases. This looked promising, until I discovered that it didn't work for my user. I'm pretty sure that it's related to permissions. The user just has db_owner on a specific database and nothing else. (Mainly as I don't know how to set anything else!)

A bit of googling provided enabled me to develop this SQL statement:


SELECT namecollation_name
FROM sys.databases
WHERE name NOT IN ('master''tempdb''model''msdb');

This works, but gives me a list of all (non-system) databases, but doesn't tell me which ones I have permission to actually access.

I'm sure there's a better way, but I discovered that if I try to use a database, then I get an error message back, so a simple foreach loop solved my problem:


$validDatabases = array();
foreach($databases as $name) {
    $sql "USE [$name]";
    try {
        $this->_db->query($sql);
    } catch (Exception $e) {
        // failed to access the database - ignore it
        continue;
    }
    $validDatabases[] = $name;
}

Now... this is inelegant. Surely there's a better way?!

On the plus side, it works ;)

3 Responses to “Retrieving a list of databases from SQL Server”

  1. 1 tuomas

    select * from information_schema.tables is also quite easy way...

  2. 2 Rob...

    tuomas,

    Thanks! I will try that :)

    Regards,

    Rob...

  3. 3 Sascha Lichtenegger

    Select name collate Latin1_General_CI_AS from [Servernamehere].master.dbo.sysdatabases

The views expressed in these comments are not the views of the publisher. However, we believe in the rights of others to express their legitimate views and concerns. Any legitimate complaint emailed to rob@akrabat.com will be seriously considered and the post reviewed as desirable and necessary.