How do I change the default database owner for new databases in SQL Server?



  • I had cause to change my computer name (it’s running in a virtual machine). I have an existing SQLExpress instance which was installed prior to the rename.

    There are some features which fail because new databases are still created with the old owner. More specifically, when I try to create a new database diagram, I get the below error.

    Could not obtain information about Windows NT group/user 'OLDNAME\user', error code 0x534. (Microsoft SQL Server, Error: 15404).

    I used the following instructions to rename the server:

    sp_dropserver 'OLDNAME\SQLEXPRESS';
    GO
    sp_addserver 'NEWNAME\SQLEXPRESS','local';
    GO
    --  Restart Server
    SELECT @@SERVERNAME;    --  NEWNAME\SQLEXPRESS
    

    However, this did not affect the default owner for new databases. They are still being created with the owner as OLDNAME\user, who no longer exists.

    I know how to change the owner of an existing database, after creation. But, how can I get new databases to have the correct owner to begin with?



  • The default owner is going to be whoever creates the database. In your case, it sounds like you're using a local computer account as a windows login for SQL Server. So, the login name is in the form of OLDNAME\user; however, you would like new databases to be created with NEWNAME\user as the owner.

    Changes to Windows accounts are not propagated to SQL Server, so the old login name will persist until you manually change it. However, the login continues work because the SID is how SQL Server makes reference to it when authenticating the account.

    To fix this issue you'll need to use the https://docs.microsoft.com/en-us/sql/t-sql/statements/alter-login-transact-sql?view=sql-server-ver15 command to change the login name from OLDNAME\user to NEWNAME\user.

    ALTER LOGIN [OLDNAME\user] WITH NAME = [NEWNAME\user]
    

    If you need to change the owner of an existing database, you can use ALTER AUTHORIZATION. I would recommend changing the database owner to someone other than a real user, such as [sa].

    ALTER AUTHORIZATION ON DATABASE::
        TO \
    

    Another option would be to use EXECUTE AS LOGIN = 'owner_to_be', just ahead of the statement to be executed to create the database.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2