The database owner SID recorded in the master database differs from the database owner SID

JDPeckham picture JDPeckham · Sep 12, 2012 · Viewed 100.2k times · Source

When I try to install tSQLt onto an existing database i get the following error:

The database owner SID recorded in the master database differs from the database owner SID recorded in database ''. You should correct this situation by resetting the owner of database '' using the ALTER AUTHORIZATION statement.

Answer

JohnnyM picture JohnnyM · Nov 1, 2012

This problem can arise when a database restored from a backup and the SID of the database owner does not match the owners SID listed in the master database. Here is a solution that uses the "ALTER AUTHORIZATION" statement recommended in the error message:

DECLARE @Command VARCHAR(MAX) = 'ALTER AUTHORIZATION ON DATABASE::[<<DatabaseName>>] TO 
[<<LoginName>>]' 

SELECT @Command = REPLACE(REPLACE(@Command 
            , '<<DatabaseName>>', SD.Name)
            , '<<LoginName>>', SL.Name)
FROM master..sysdatabases SD 
JOIN master..syslogins SL ON  SD.SID = SL.SID
WHERE  SD.Name = DB_NAME()

PRINT @Command
EXEC(@Command)