I can tell if a SQL Server TDE Master Key exists with this T-SQL query:
if not exists (SELECT name FROM sys.symmetric_keys WHERE symmetric_key_id = 101) begin
-- Master Key does not exist. Create one here.
end;
Is there a query to determine whether a database key exists for [mydb]? For example:
use [mydb];
if .... begin
-- database encryption key does not exist. Create one here
end;
You're looking for
sys.dm_database_encryption_keys
. From the docs:Also, it's a server-level view, so no need to run it in the context of your user database (though it's fine if you do; you can run it anywhere on the server). Something like this should work