We have a lot of DBUsers in our database. We have to clean up all those users from the database. When I tried to drop the user from the DB it failed due to the following error
Msg 15138, Level 16, State 1, Line 2 The database principal owns a schema in the database, and cannot be dropped.
So I found the solution for this i.e I changed the ownership of the schema to dbo
. Now I can drop the user by using below script
SELECT name FROM sys.schemas WHERE principal_id = USER_ID('myUser')
ALTER AUTHORIZATION ON SCHEMA::SchemaName TO dbo
GO
DROP USER myUser
But I want to drop a number of users so I need to generate generalized script. I am using SQL Server 2008
You can get a list of the schemas using an SSMS or T-SQL query. To do this in SSMS, you would connect to the SQL instance, expand the SQL database and view the schemas under the security folder. Alternatively, you could use the sys. schemas to get a list of database schemas and their respective owners.
This will give you a complete list of schemas against the users which own them:
SELECT db.name AS [DB User], s.name AS [Schema]
FROM sys.database_principals db
JOIN sys.schemas s ON s.principal_id = db.principal_id
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