By using this site, you agree to the Privacy Policy and Terms of Use.
Forums › SQL Server DBA Discussion › SQL Server Scripts › SQL Script for Changing Database Ownership to ‘sa’ for all User Databases
This SQL script is designed to change the ownership of all user databases in a SQL Server instance to the ‘sa’ (system administrator) account. It’s useful for database administrators who need to standardize database ownership or reset it for any reason.
This script changes the ownership of all user databases to the ‘sa’ account:
declare @sql varchar(200), @name varchar(200)
declare cur cursor for
select name from sys.databases
where name not in ('master', 'tempdb', 'model', 'msdb')
open cur
fetch next from cur into @name
while @@FETCH_STATUS = 0
begin
set @sql = 'ALTER AUTHORIZATION ON DATABASE::' + @name + ' TO [sa];'
print @sql
exec(@sql)
fetch next from cur into @name
end
close cur
deallocate cur
GO
Let’s break down what each part of the script does:
@sql
: This variable will store the dynamically generated SQL command for each database.@name
: This variable will hold the name of each database as the cursor processes them.cur
is declared to iterate through the names of all databases, excluding the system databases (‘master’, ‘tempdb’, ‘model’, ‘msdb’).@name
variable.WHILE @@FETCH_STATUS = 0
loop ensures that the script processes each database returned by the cursor.ALTER AUTHORIZATION
.PRINT
) for logging or debugging purposes and executed (using EXEC
).GO
command signifies the end of the batch in SQL Server.As always, it’s advisable to test scripts like this in a non-production environment before running them on your production server.