Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generalized query to find whether the database user owns a schema

Tags:

sql

sql-server

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

like image 935
Jibu P C_Adoor Avatar asked Feb 07 '11 12:02

Jibu P C_Adoor


People also ask

How do I find the schema of a user in SQL Server?

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.


1 Answers

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
like image 163
dataduck Avatar answered Oct 26 '22 16:10

dataduck