Monday, March 8, 2010

List of online databases in SQL Server sysdatabases table

While I was working on a requirement to pull out list of databases which are only ONLINE and not in state like "Restoring..." or "Standby" ...

We have a state_desc column in sysdatabases but that shows ONLINE even for Standby database which will make your BACKUP to fail if you are using the output to take BACKUP.

Here is the query to get list of 100% PURE ONLINE databases:

SELECT name FROM master.dbo.sysdatabases WHERE

status & 32 <> 32 AND -- loading state

status & 64 <> 64 AND -- pre recovery state

status & 128 <> 128 AND -- recovering state

status & 512 <> 512 AND -- offline state

status & 1024 <> 1024 AND -- read only mode

status & 2048 <> 2048 AND -- dbo use only

status & 4096 <> 4096 AND -- single user mode

status & 32768 <> 32768 -- Emergeny state