SQL Server: How to tell if a database is a system database?

浪子不回头ぞ 提交于 2019-11-28 00:51:54
Jimmy

Just dived into Microsoft.SqlServer.Management.Smo.Database object (which is provided by Microsoft itself!) They simply do this using following statement:

CAST(case when dtb.name in ('master','model','msdb','tempdb') 
   then 1 
   else dtb.is_distributor end AS bit) AS [IsSystemObject]

In short: if a database is named master, model, msdb or tempdb, it IS a system db; it is also a system db, if field is_distributor = 1 in the view sys.databases.

Hope this helps

Jimmy

You can rely on the DB_ID() function <= 4

You'd have to work very hard to change this...

SQL Server Management Studio uses this

if you expand "System Databases" in "Object Explorer" (seen from wireshark):

SELECT dtb.name AS [Database_Name]
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)

For the sake of simplicity I removed irrelevant columns, removed orderby and replaced @_msparam_0 variable by its value 1

Soheil Bakhshi

owner_sid is equal to 0x01 just for system databases. So you can use it to recognise if the database is a system DB or not.

select * from sys.databases
where owner_sid != 0x01

no there's no such option AFAIK. i guess you could check the id the sys.databases.owner_sid = 0x01.

i don't think you have to worry about MS changing the system db names. if they did theat you wouldn't have to worry about it for at least 20 years :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!