Obtaining a unique database identifier for SQL Server 2005 and later Obtaining a unique database identifier for SQL Server 2005 and later database database

Obtaining a unique database identifier for SQL Server 2005 and later


Whatever means SMO uses to get the database guid, you should be able to do the same. If you have problems figuring out what is SMO doing, you can use profiler to monitor what t executes and figure it out.

In this case probably SMO reads the database_guid value from sys.database_recovery_status:

Used to relate all the database files of a database together. All files must have this GUID in their header page for the database to start as expected. Only one database should ever have this GUID, but duplicates can be created by copying and attaching databases. RESTORE always generates a new GUID when you restore a database that does not yet exist.


For others who are looking for a query to return the GUID of a database:

SELECT d.name, drs.database_guid, d.group_database_id FROM sys.databases d JOIN sys.database_recovery_status drsON d.database_id = drs.database_id

It returns the database name, database GUID and GUID of this database in availability group. If database is not in AG, the last value returns null. This works in SQL Server 2016.


I don't know which GUID SMO returns, but you could use

select service_broker_guid from sys.databases

which is != Guid.Empty for all databases except master and model.

I found that not all databases have a NOT NULL sys.database_recovery_status.database_guid, as was suggested by Remus.

Tests done on SQL2008