4

How did removing an empty schema and changing the default schema remove db_owner role from a database user?

I determined to clean up the extra schemas that have been created over the years. Some schemas were created by default and have the same name as a SQL Database Login. I searched for schemas that did not contain any objects with this query:

SELECT 
    db_name() AS DatabaseName
    ,ds.SCHEMA_NAME AS SchemaName
    ,du.name AS UserName
    ,'USE  ' + db_name() + '; ALTER USER [' + ds.SCHEMA_NAME + '] WITH DEFAULT_Schema=dbo; drop schema if exists [' + ds.SCHEMA_NAME + ']; ' as Fix
FROM INFORMATION_SCHEMA.SCHEMATA ds
JOIN sys.database_principals du ON du.name = ds.SCHEMA_NAME
    AND du.default_schema_name = ds.SCHEMA_NAME
    AND ds.SCHEMA_OWNER = du.name
WHERE NOT EXISTS (
        SELECT 1
        FROM sys.objects o
        JOIN sys.schemas ss ON ss.schema_id = o.schema_id
        WHERE ss.name = ds.SCHEMA_NAME
        )
    AND ds.SCHEMA_NAME NOT IN (
        'dbo'
        ,'guest'
        ,'sys'
        ,'INFORMATION_SCHEMA'
        )

Then used this query (as an example) to clean them up:

USE  SecondaryDatabase; 
ALTER USER [User2] WITH DEFAULT_Schema=dbo; 
drop schema if exists [User2]; 

I first changed the default schema to the default "dbo". Then I removed the schema that had the same name as the user.

Removing the schema or changing the default schema removed the db_owner role from User2. The change our vendor made to fix it was to grant the db_owner role to User2.

I cannot understand how removing a schema that had no objects in it and changing the default schema could change this user's permissions. Any ideas?

What I have done and researched so far:

ElRojo
  • 169
  • 8

1 Answers1

2

Restored the servers and re-ran the same script. Was not able to reproduce the problem. There must have been other factors at play.

David from Microsoft answered the question (see comment to question):

There's no direct way removing a schema would do that.

ElRojo
  • 169
  • 8