How do I list all the databases for a given sql server 08 instance using sqlcmd?
            Asked
            
        
        
            Active
            
        
            Viewed 7.9k times
        
    4 Answers
47
            sqlcmd -E -S SERVER\INSTANCE -Q "sp_databases"
Notes:
- -E: Use a trusted connection ("Windows authentication"). Replace by- -U username -P passwordfor SQL Server authentication.
- -S SERVER\INSTANCE: The instance of SQL Server to which to connect. If you don't know the name of your instance, you can use- sqlcmd -Lto get a list.
- -Q: The query to execute. The uppercase- Qcauses sqlcmd to exit after executing the query.
 
    
    
        Heinzi
        
- 167,459
- 57
- 363
- 519
39
            
            
        To elaborate with more detail for the sqlcmd newbie:
C:\> sqlcmd -S <the_server_name>
1> select name from sys.databases
2> go
 
    
    
        Shaun Luttin
        
- 133,272
- 81
- 405
- 467
- 
                    1Where do I find out what the server name is? Is there a command to list all the servers? – Felix Eve Aug 28 '18 at 07:48
- 
                    @FelixEve: https://stackoverflow.com/q/141154/87698 – Heinzi Jul 29 '20 at 07:19
32
            
            
        EXEC sp_databases
or
SELECT NAME FROM sys.sysdatabases
or
EXEC sp_msForEachDB 'PRINT ''?''';
 
    
    
        D'Arcy Rittich
        
- 167,292
- 40
- 290
- 283
- 
                    Up voted for options but accepted Heinzi because it includes the sqlcmd aspect. Thanks! – Dane O'Connor Jan 18 '10 at 17:32
- 
                    5I'm a newb and may be stating the obvious here, but I had to do 'go' after the EXEC line like this `1>EXEC sp_databases2>go – barlop Jul 01 '15 at 20:15` 
 
    