I liked the query from @waitForPete because it checks if the schema has anything in it, and drops it if no.
obviously that is not what you always want but it has its uses too.
this is my query to print out the schemas that are owned by a user that you want to drop, so you can drop that particular user:
I have wrapped the query inside a cursor just so it gives me the print of the script.
I do also check if the schema exists, in case I am applying this script to a different database or the same database after a restore.
PRINT ' '
PRINT ' '
PRINT '-------------------------------------------------------------------'
PRINT '-- Server and DB: ' + @@servername + '.' + db_name()
PRINT '-- script to apply permissions.'
PRINT '-- Marcelo Miorelli v.17-Jul-2024'
PRINT '-- ' + 'These permissions were taken on ' + DateName( weekday , GETDATE()) + ',' + CONVERT(VARCHAR(30),GETDATE(),113)
PRINT '-------------------------------------------------------------------'
PRINT ' '
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SET NOCOUNT ON
DECLARE
@DatabaseUserName [sysname],
@errStatement [varchar](8000),
@msgStatement [varchar](8000),
@DatabaseUserID [smallint],
@ServerUserName [sysname],
@RoleName [varchar](8000),
@SchemaName [varchar](8000),
@MEmberName [varchar](800),
@ObjectID [int],
@ObjectName [varchar](261)
PRINT 'PRINT ' + '''--Server and DB:'' + @@servername + ''.'' + db_name()'
PRINT 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED'
PRINT 'SET NOCOUNT ON'
PRINT ''
PRINT '-- ——— CHANGE SCHEMA OWNER TO DBO ————————————–'
DECLARE _Dschemas
CURSOR LOCAL FORWARD_ONLY READ_ONLY
FOR
SELECT the_script FROM
(
SELECT schema_name = s.name
,s.principal_id
,schema_owner = USER_NAME(s.principal_id)
,the_script = 'IF EXISTS(SELECT * FROM sys.schemas s WITH(NOLOCK) WHERE quotename(s.name) = '
+ '''[' + s.name + ']'' COLLATE SQL_Latin1_General_CP1_CI_AS)'
+ ' ALTER AUTHORIZATION ON SCHEMA::' + quotename(s.name)
+ ' TO [dbo]'
FROM sys.schemas s WITH (NOLOCK)
INNER JOIN sys.database_principals dp WITH (NOLOCK)
ON s.principal_id = dp.principal_id
WHERE 1=1
AND dp.is_fixed_role = 0
AND s.principal_id > 4
) Radhe
OPEN _Dschemas FETCH NEXT FROM _Dschemas INTO @msgStatement
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @msgStatement
FETCH NEXT FROM _Dschemas INTO @msgStatement
END
CLOSE _Dschemas
DEALLOCATE _Dschemas
careful, always check on which server and database you are, see the first line I have printed, this is very important.
stay away from live servers, unless you really need to be there.
wrap everything into begin transaction and rollback or
-- commit transaction