Last active
September 7, 2023 08:42
-
-
Save dhmacher/9c2838f364071a5d92c386a183b948ec to your computer and use it in GitHub Desktop.
Make sa the owner of all databases (and add the former owner to the db_owner role)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DECLARE @sql nvarchar(max)=N''; | |
SELECT @sql=@sql+N' | |
USE '+QUOTENAME(db.[name])+N'; | |
IF (USER_ID('+QUOTENAME(sp.[name], N'''')+N') IS NULL) | |
CREATE USER '+QUOTENAME(sp.[name])+N' FOR LOGIN '+QUOTENAME(sp.[name])+N'; | |
ALTER ROLE [db_owner] ADD MEMBER '+QUOTENAME(sp.[name])+N'; | |
ALTER AUTHORIZATION ON DATABASE::'+QUOTENAME(db.[name])+N' TO '+QUOTENAME(SUSER_NAME(0x01))+N';' | |
FROM sys.databases AS db | |
INNER JOIN sys.server_principals AS sp ON sp.[sid]=db.owner_sid | |
WHERE db.owner_sid!=0x01; | |
PRINT @sql; | |
---EXECUTE sys.sp_executesql @sql; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment