Creating schemas without DBO permission

Comments 0

Share to social media

One result of having the correct care with the access permissions in our databases is the need to avoid the DBO permission even to the users responsible for the database model.

Using the database roles such as ddl_admin or even in more grainy ways it’s easy to achieve this goal.

However, it’s more complex when we would like to use schemas in the database model. The creator of the schema becomes its owner and the existence of several schema owners in the model creates a problem we call ‘broken ownership chain’, a truly hell to DBA’s.

One possible solution would be ask to every schema creator to give the ownership of their schemas to the DBO user, all schemas will be owned by DBO. However, even the members of ddl_admin database role hasn’t enough permission to give the ownership of schemas to the DBO.

The solution for this problem is create a DDL trigger to intercept the creation of schemas and change the ownership of the schema to the DBO.

The trigger will be like this :

CREATE TRIGGER chkschema ON DATABASE WITH
execute AS
  ‘dbo’ FOR create_schema AS
DECLARE @EventData xml = eventdata();
declare @owner sysname
SELECT @owner=@EventData.value(‘(/EVENT_INSTANCE/OwnerName)[1]’,‘sysname’)
IF @owner<>‘dbo’
BEGIN
  DECLARE @sql varchar(500)
  DECLARE @sch sysname
  SELECT @sch=@EventData.value(‘(/EVENT_INSTANCE/SchemaName)[1]’,‘sysname’)
  SELECT @sql=‘alter authorization on schema::’ + @sch + ‘ to dbo’
  EXEC(@sql)
END

Once the trigger is created, everytime a user creates a new schema the ownership of the schema will be changed to DBO user.

You can also create this trigger inside the model database, so every new database created on the server will already be created with the trigger.

Load comments

About the author

Dennes Torres

See Profile

Dennes Torres is a Data Platform MVP and Software Architect living in Malta who loves SQL Server and software development and has more than 20 years of experience. Dennes can improve Data Platform Architectures and transform data in knowledge. He moved to Malta after more than 10 years leading devSQL PASS Chapter in Rio de Janeiro and now is a member of the leadership team of MMDPUG PASS Chapter in Malta organizing meetings, events, and webcasts about SQL Server. He is an MCT, MCSE in Data Platforms and BI, with more titles in software development. You can get in touch on his blog https://dennestorres.com or at his work https://dtowersoftware.com