Failed to clean up temporary user/login.  The database principal owns a database role and cannot be dropped Failed to clean up temporary user/login.  The database principal owns a database role and cannot be dropped

Failed to clean up temporary user/login. The database principal owns a database role and cannot be dropped

When creating an image or clone database using SQL Clone, the user can modify the image or clone using a T-SQL Script.  The SQL Clone Agent creates a temporary user with low privileges to execute the T-SQL script.

If the T-SQL script contains code to create a new role as per this T-SQL command:

CREATE ROLE [db_MyNewRole];

After applying the T-SQL modification, the temporary user will be dropped.  Unfortunately this will fail, as the temporary user will own the role created, generating the error:

Failed to clean up temporary user/login. The database principal owns a database role and cannot be dropped

2024-07-09 11:00:20.649 +01:00 [Information] CreateCloneRequestEvent (clone name: "Guitar_315346") Operation 30353 started
2024-07-09 11:00:25.054 +01:00 [Information] SqlDatabaseAttacher: Started to attach database Guitar_315346
2024-07-09 11:00:25.247 +01:00 [Information] SqlDatabaseAttacher: Finished attaching database Guitar_315346
2024-07-09 11:00:25.297 +01:00 [Information] Starting to run SQL Script "Create_Role.sql"
2024-07-09 11:00:25.542 +01:00 [Information] Finished running "Create_Role.sql"
2024-07-09 11:00:25.564 +01:00 [Error] Failed to clean up temporary user/login "SqlClone_LowPriv_1433858831_zosd"
Microsoft.Data.SqlClient.SqlException (0x80131904): The database principal owns a database role and cannot be dropped.

To resolve this error, include the AUTHORIZATION keyword to set an owner for the role created, which will then allow the temporary user to be deleted.  In this example, the owner is set to be dbo:

CREATE ROLE [db_MyNewRole] AUTHORIZATION [dbo];