Skip to content

Change All Database Owners to SA

A cursor-driven script that reassigns the owner of every user database on the server to sa.

Published Dec 5, 2005

After a restore or a migration you often end up with databases owned by some random login from the source server. This script walks every user database (skipping master, tempdb and model) and runs sp_changedbowner with @map = false to make sa the owner again.

SET NOCOUNT ON;
USE master
GO

DECLARE @tSQL VarChar(MAX)
DECLARE @DatabaseName sysname

DECLARE DatabaseList CURSOR FAST_FORWARD FOR
	SELECT
		name
	FROM
		sys.databases
	WHERE
		name not in ('master', 'tempdb', 'model')
OPEN DatabaseList
FETCH FROM DatabaseList INTO @DatabaseName

WHILE(@@FETCH_STATUS = 0)
BEGIN--WHILE
	----------------------------------------------------------------------------------------------------------------------------------

	SET @tSQL =
		'exec [' + @DatabaseName + '] .dbo.sp_changedbowner @loginame = N''sa'', @map = false'
	EXEC(@tSQL)

	----------------------------------------------------------------------------------------------------------------------------------
	FETCH FROM DatabaseList INTO @DatabaseName
END--WHILE

CLOSE DatabaseList DEALLOCATE DatabaseList
An unhandled error has occurred. Reload 🗙