Changing DB ownership to sa account for all databases not SA

As we know, when we create database on SQL Server instance, SQL Server engine sets the login that created the database as the default database owner. This gives the user full control on the database, meaning he/she can do whatever they like on that particular database. According to the SQL Server security best practice document, we should grant login with the least amount of privileges. Therefore, it is recommended to set built-in sa account as an owner of all databases on SQL Server instance. This will make database and server more secure.

How to identify the ownership of the system and user databases on SQL Server instance?

You can use SQL Server Management Studio to view the database owner. Follow these steps to view the database owner using SQL Server 2014 Management Studio:

In SQL Server Management Studio, connect to an instance of the SQL Server Database Engine with Object Explorer.
In Object Explorer, right-click the database for which you want to check the database ownership, and then click Properties.
This opens the database property window, showing you the general database information and ownership details.


Below is the quick script I wrote, which can be used to identify the user database where the owner is not sa. This script also gives you ALTER AUTHORIZATION Transact DCL command for each database to transfer its ownership to sa account:



USE [master];
GO

SELECT [name] AS [DBName], SUSER_SNAME( [owner_sid] ) AS [ExistingOwner]
,N'ALTER AUTHORIZATION ON DATABASE::' + QUOTENAME( [name] ) + ' TO '
+ QUOTENAME((SELECT [name] FROM [sys].[sql_logins] WHERE [sid] = 0x01)) AS [ScriptToChangeDBOwner]
FROM [sys].[databases]
WHERE [database_id] > 4
AND [owner_sid] <> 0x01
AND [state_desc] = 'ONLINE';
GO

Comments

Popular posts from this blog

How to mass update all or some sql server agent job step commands

SQL Monitoring for Blocking and Locking Capture and Log to table with sp_WhoIsActive or sp_BlitzWho

SQL Server General Index Naming Convention