41

How can I get all the database names in a sql server instance using tsql?

5 Answers 5

76
SELECT * FROM sys.databases
Sign up to request clarification or add additional context in comments.

Comments

17

----SQL SERVER 2005 System Procedures

EXEC sp_databases
EXEC sp_helpdb

----SQL 2000 Method still works in SQL Server 2005

SELECT name
FROM sys.databases
SELECT name
FROM sys.sysdatabases

----SQL SERVER Un-Documented Procedure

EXEC sp_msForEachDB 'PRINT ''?'''

to know more about database : http://blog.sqlauthority.com/2007/05/12/sql-server-2005-list-all-the-database/

1 Comment

Please note that there is an issue with the stored procedure sp_msForEachDB... it fails for database names containing a dot.
7

this should work on pretty much any version of sql server

USE master;
SELECT NAME FROM sysdatabases;

[edit : it could be SELECT NAME FROM sys.databases too, microsoft's website says both and i'm not on my windows box to test, sorry!]

you could also use (sql 2005 only)

USE master;
EXEC sp_databases;

1 Comment

In case someone is looking for Sybase ASE (tried on 15.7), it's sysdatabases.
1

And for practical use added couple of common filters:

  select    database_id, [name] database_name                    
    from  master.sys.databases
    WHERE state <> 6                            -- skip offline
      AND database_id > 4                       -- skip system dbs
      AND HAS_DBACCESS([name]) = 1              -- with User Access

Comments

0

SQL 2000

use master
select name from sysdatabases

or (no need for use master, includes database_size)

exec sp_databases

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.