HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

One of the Database Ownerhas been Removed and corresponding property changes in sql server

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
theownerhasremovedserversqlbeendatabaseonepropertychanges

Problem

A database has been created on SQL 2008 by a user named user1 ,on dec 2013.Today ,we are going to remove that user(/owner) from the server.What will be the owner property of the database show then?

Solution

You have to change the ownership of each database that that user owns before you can delete the user.

Change ownership using SSMS or you can use T-SQL

use database_name
EXEC sp_changedbowner 'newowner'


Following query allows you to query all databases owned by a particular login.

use master
select database_id, name, suser_sname(owner_sid) from sys.databases where suser_sname(owner_sid) = 'logintoremove'


You could then use this information to bulk update ownership.

use master
DECLARE @name VARCHAR (50) -- database name
DECLARE @oldOwner VARCHAR (50)
DECLARE @newOwner VARCHAR (50)

SET @oldOwner = 'oldownerlogin'
SET @newOwner = 'newownerlogin'

BEGIN
    DECLARE db_cursor CURSOR FOR
    select name from sys.databases where suser_sname(owner_sid) = @oldOwner
END

OPEN db_cursor 
FETCH NEXT FROM db_cursor INTO @name 

WHILE @@FETCH_STATUS = 0 
BEGIN 
    BEGIN
        EXEC(
            'USE '+@name +';

            EXEC sp_changedbowner ''' +@newOwner+ '''
            ' )
        END

    FETCH NEXT FROM db_cursor INTO @name
END 

CLOSE db_cursor 
DEALLOCATE db_cursor

Code Snippets

use database_name
EXEC sp_changedbowner 'newowner'
use master
select database_id, name, suser_sname(owner_sid) from sys.databases where suser_sname(owner_sid) = 'logintoremove'
use master
DECLARE @name VARCHAR (50) -- database name
DECLARE @oldOwner VARCHAR (50)
DECLARE @newOwner VARCHAR (50)

SET @oldOwner = 'oldownerlogin'
SET @newOwner = 'newownerlogin'

BEGIN
    DECLARE db_cursor CURSOR FOR
    select name from sys.databases where suser_sname(owner_sid) = @oldOwner
END

OPEN db_cursor 
FETCH NEXT FROM db_cursor INTO @name 

WHILE @@FETCH_STATUS = 0 
BEGIN 
    BEGIN
        EXEC(
            'USE '+@name +';

            EXEC sp_changedbowner ''' +@newOwner+ '''
            ' )
        END

    FETCH NEXT FROM db_cursor INTO @name
END 

CLOSE db_cursor 
DEALLOCATE db_cursor

Context

StackExchange Database Administrators Q#60292, answer score: 10

Revisions (0)

No revisions yet.