Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to query the system databases in SQL server without using the names?

When doing a query over several databases in SQL server (2005+) I find it sometimes necesary to exclude the system database (master, model, tempdb, msdb and distribution)

Is there any OTHER way to filter these besides

where name not in (''master', 'model', 'tempdb', 'msdb', 'distribution')

I've looked at sys.databases and master.dbo.sysdatabases (not the same!)

[UPDATE] an example query which I use to look for databases that have logshipping enabled

select d.name, p.last_backup_date, s.secondary_server, s.secondary_database
from sys.databases d
    left outer join msdb..log_shipping_primary_databases p on p.primary_database = d.name
    left outer join msdb..log_shipping_primary_secondaries s on s.primary_id = p.primary_id
where name not in ('model','master','tempdb','distribution','msdb')
order by d.name

[UPDATE] This seems to be the 'least bad' way, unless someone else has a better way?

SELECT * FROM 
master.sys.databases AS dtb 
WHERE (dtb.database_id < 5 or dtb.is_distributor = 1)
like image 379
edosoft Avatar asked Aug 03 '10 13:08

edosoft


People also ask

Can you name the system databases in SQL Server?

SQL Server mainly contains four System Databases (master,model,msdb,tempdb). Each of them is used by SQL Server for Separate purposes. From all the databases, master database is the most important database.

What is the query to list all the databases?

To do that we will be using the below given commands: CREATE TABLE [database_name.] table_name ( pk_column data_type PRIMARY KEY, column_1 data_type NOT NULL, column_2 data_type, ..., table_constraints ); If we do not mention the name of the database then the default USE database is selected for the creation of tables.

How do I get a list of user databases in SQL Server?

First, move to “Object Explorer” and expand the database that you want. Next, under the database, expand the “Security” directory. Now, under Security, expand the “Users” option. This will display a list that contains all the users created in that database.


1 Answers

I ran SQL Profiler and refreshed the system databases node in management studio. It uses the query

...FROM
master.sys.databases AS dtb
WHERE
(CAST(case when dtb.name in ('master','model','msdb','tempdb') 
then 1 else dtb.is_distributor end AS bit)=1)

So I guess you could combine the dbid and is_distributor checks.

like image 128
Martin Smith Avatar answered Nov 15 '22 07:11

Martin Smith