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

强颜欢笑 提交于 2019-11-26 17:13:57

问题


I know that so far (until MSSQL 2005 at least), system databases are master, model, msdb and tempdb.

Thing is, as far as I can tell, this is not guaranteed to be preserved in the future. And neither the sys.databases view nor the sys.sysdatabases view tell me if a database is considered as a system database.

Is there someplace where this information (whether a database is considered a system database or not) can be obtained?


回答1:


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




回答2:


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




回答3:


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

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




回答4:


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



回答5:


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 :)



来源:https://stackoverflow.com/questions/1819095/sql-server-how-to-tell-if-a-database-is-a-system-database

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