tags:

views:

354

answers:

4

I want to get a list of all of the user databases from an mssql server instance. What's the best way to do this?

I know I can select from sys.databases, but I don't see any way to filter out system databases besides hardcoding a list of names to exclude.

I need the script to work on 2000/2005 and 2008.

If the approach I listed above is the only way to go, what are list of names I should exclude? I don't know if 2005 or 2008 added any new system databases off the top of my head.

A: 

Not sure if you can offhand. One note -- on 2k you'll have to use master.dbo.sysdatabases and not master.sys.databases (which doesn't exist in 2k).

Joe
Is there a way the script can tell what version of SQL server it's being executed on and branch?
select @@version is one way to do that
MatthewMartin
+2  A: 

As nasty as it sounds to hardcode things. The names and number of system databases has been fairly consistent for several versions of SQL. However, if that is too unpleasant you could semi-hardcode them into a table and then plug that into your query.

JohnFx
A: 
select * from INFORMATION_SCHEMA.SCHEMATA 
where catalog_name not in('master', 'tempdb', 'msdb','model','Resource')

Information_Schema should be your first thought when thinking about sql that references system objects and needs to work with more than one version of SQL Server. Other solutions include SQL-SMO (not a t-sql solution, but is cross version compatible)

MatthewMartin
This appears to only return information about the schema in the current database. I want a list of all of the databases on the entire server.
remember that this will give you many rows per DB on sql 2005 and up, you also get all the schemas
SQLMenace
+2  A: 

This works in 2005, not 100% sure about the other versions but I think it will fly. It's a bit of a hack but might get you what you need:

 select * from sys.databases where len(owner_sid)>1
brendan
I tested it on my installation of SQL2K8 and it worked fine. Seems kinda hacky, but it did return the correct result.
JohnFx
Definately "hacky" and there is no way to ensure this would work in future versions of SQL.
brendan