Is there a way to obtain a unique database identifier (such as a GUID) from a SQL 2005 database?
I found this article: http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.database.databaseguid%28v=sql.90%29.aspx
However, I need to be able to obtain the DatabaseGuid from T-SQL instead of VB.
EDIT: I am trying to uniquely determine the database for which I am connected. Through code I manually sync records between SQL Compact and SQL Server. Right now my users are in a test environment and when they are pointed to production SQL in the future I will need to re-sync entire tables instead of relying on rowversion. The rowversions will be different on the production server and if I am able to detect a database GUID change, I can re-sync the entire table.
Thanks in advance.
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 drs
ON 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With