SQL Clone
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 


Changing db owner script


Changing db owner script

Author
Message
mazzz
mazzz
SSChasing Mays
SSChasing Mays (651 reputation)SSChasing Mays (651 reputation)SSChasing Mays (651 reputation)SSChasing Mays (651 reputation)SSChasing Mays (651 reputation)SSChasing Mays (651 reputation)SSChasing Mays (651 reputation)SSChasing Mays (651 reputation)

Group: General Forum Members
Points: 651 Visits: 2661
Hi DHeath

If you manage 20+ servers, you might want to look into Powershell. I manage 100 of the blighters, and powershell has made my life a lot easier!

Check out this script below, which should do what you want. All you need is a textfile AllServers.txt with your server names in:


SERVERA
SERVERA\INST
SERVERB
...



The script (in this case I use a SQL authenticated login, but of course you can use Windows authentication as well):
EDIT: NB this has only been tested on my local SQL installation!

cls
# load assemblies
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlEnum")
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum")
[Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo")

$userName = "sqldba"
$password = "P@$$w0rd"

# file errors will get sent to
$errorfile = "C:\errors_ChangeDBOwner.txt"
New-Item -itemType file $errorfile -force | Out-Null

# file output will get sent to
$outputfile = "C:\ChangeDBOwner.txt"
New-Item -itemType file $outputfile -force | Out-Null

# loop through all SQL Servers
$servers = Get-Content "c:\AllServers.txt"
try
{
foreach($srvname in $servers){
$srv = New-Object Microsoft.SqlServer.Management.Smo.Server ($srvname)
$srv.ConnectionContext.NonPooledConnection = "True"
# login using SQL authentication, supplying the username and password
$srv.ConnectionContext.LoginSecure=$false;
$srv.ConnectionContext.set_Login($userName)
$srv.ConnectionContext.Password = $password

$sa = $srv.Logins["sa"]
foreach($db in $srv.Databases)
{
if(!$db.IsSystemObject)
{
$db.SetOwner($sa.Name)
}
}
$srv.ConnectionContext.Disconnect()
}
}
catch{
$err = $Error[0].Exception
while ( $err.InnerException )
{
$err = $err.InnerException
}
$srv.Name + " - " + $db.Name + " : " + "TRAPPED: " + $err.Message | Out-File -append -filePath $errorfile
$err
}






I use scripts based on this template for all sorts of handy things - checking for failed jobs on all servers, bringing back information on database settings for all servers/databases...
It's well worth a look, IMO

------------------------------------------------------------------------
Bite-sized fiction (with added teeth)
DHeath
DHeath
SSC-Addicted
SSC-Addicted (417 reputation)SSC-Addicted (417 reputation)SSC-Addicted (417 reputation)SSC-Addicted (417 reputation)SSC-Addicted (417 reputation)SSC-Addicted (417 reputation)SSC-Addicted (417 reputation)SSC-Addicted (417 reputation)

Group: General Forum Members
Points: 417 Visits: 650
Hey mazzz,

Thanks a lot and may have to look at the Powershell avenue as well. The script you provided looks to be very useful. Thanks again

DHeath
abo_moaaz
abo_moaaz
SSC Journeyman
SSC Journeyman (83 reputation)SSC Journeyman (83 reputation)SSC Journeyman (83 reputation)SSC Journeyman (83 reputation)SSC Journeyman (83 reputation)SSC Journeyman (83 reputation)SSC Journeyman (83 reputation)SSC Journeyman (83 reputation)

Group: General Forum Members
Points: 83 Visits: 317
excellent script, just used it to change hundreds of DBs. :-)



mauriciorpp
mauriciorpp
SSC-Enthusiastic
SSC-Enthusiastic (176 reputation)SSC-Enthusiastic (176 reputation)SSC-Enthusiastic (176 reputation)SSC-Enthusiastic (176 reputation)SSC-Enthusiastic (176 reputation)SSC-Enthusiastic (176 reputation)SSC-Enthusiastic (176 reputation)SSC-Enthusiastic (176 reputation)

Group: General Forum Members
Points: 176 Visits: 257
I know this topic is a bit old, but I have a different script to share. In this case, it will only change the db owner when a SPECIFIC LOGIN owns the database. It will not change others. It is easy to make it change everything that is "<> 'sa'" too (just change the where condition on the select). It will work on all databases from the current instance.

/*  http://thelonelydba.wordpress.com
-- list bases owned by specific login. script to change below.
SELECT name, SUSER_SNAME(owner_sid) owner
FROM sys.databases
where SUSER_SNAME(owner_sid) = 'user_to_remove'
*/
DECLARE @sql nvarchar(4000);
DECLARE @BigSQL nvarchar(4000);
DECLARE @dbName varchar(100);

declare cbases cursor fast_forward for
SELECT name
FROM sys.databases
where SUSER_SNAME(owner_sid) = 'user_to_remove'
open cbases
fetch next from cbases into @dbName
while @@FETCH_STATUS = 0
begin
SET @sql = N'exec sp_changedbowner ''''sa''''';
SET @BigSQL = N'USE [' + @dbName + ']; EXEC sp_executesql N''' + @sql + '''';
--print @BigSQL
EXEC (@BigSQL)
fetch next from cbases into @dbName
end
close cbases
deallocate cbases



Regards,
Mauricio

http://thelonelydba.wordpress.com/
dwithroder
dwithroder
Mr or Mrs. 500
Mr or Mrs. 500 (583 reputation)Mr or Mrs. 500 (583 reputation)Mr or Mrs. 500 (583 reputation)Mr or Mrs. 500 (583 reputation)Mr or Mrs. 500 (583 reputation)Mr or Mrs. 500 (583 reputation)Mr or Mrs. 500 (583 reputation)Mr or Mrs. 500 (583 reputation)

Group: General Forum Members
Points: 583 Visits: 598
i execute this against my central management servers:

EXEC sys.sp_MSforeachdb '
IF (SELECT owner_sid FROM sys.databases WHERE name = ''?'') <> 1
ALTER AUTHORIZATION ON DATABASE::? TO [SA]
'
kshurtl
kshurtl
Grasshopper
Grasshopper (16 reputation)Grasshopper (16 reputation)Grasshopper (16 reputation)Grasshopper (16 reputation)Grasshopper (16 reputation)Grasshopper (16 reputation)Grasshopper (16 reputation)Grasshopper (16 reputation)

Group: General Forum Members
Points: 16 Visits: 97
This is the proper syntax for the sp_MSforeachdb. I've tested this successfully in SQL 2008 R2, but it should be good for 2005 on up.


EXEC sp_MSforeachdb
'
EXEC [?].[dbo].sp_changedbowner @loginame = N''sa'', @map = ''false''
'

You can also add or remove selectively. The below shows NOT IN and will change all databases except those listed, but you can of course use IN instead if you only want to change a specific few that you know the names of:

EXEC sp_MSforeachdb
'
IF ''?'' NOT IN (''master'',''msdb'',''model'',''tempdb'')
EXEC [?].[dbo].sp_changedbowner @loginame = N''sa'', @map = ''false''
'
Jon.Morisi
Jon.Morisi
Ten Centuries
Ten Centuries (1.2K reputation)Ten Centuries (1.2K reputation)Ten Centuries (1.2K reputation)Ten Centuries (1.2K reputation)Ten Centuries (1.2K reputation)Ten Centuries (1.2K reputation)Ten Centuries (1.2K reputation)Ten Centuries (1.2K reputation)

Group: General Forum Members
Points: 1191 Visits: 1142
You could just add some string concatenation to build the statements you need to run off of this:

select name, suser_sname(owner_sid) as owner, [Put your string concatenation here] AS [Statement to Run]
FROM sys.databases
where suser_sname(owner_sid) <> 'sa'
and database_id > 4

You could even run this from registered servers and get it all dumped in one go.

HTH,
Jon
kshurtl
kshurtl
Grasshopper
Grasshopper (16 reputation)Grasshopper (16 reputation)Grasshopper (16 reputation)Grasshopper (16 reputation)Grasshopper (16 reputation)Grasshopper (16 reputation)Grasshopper (16 reputation)Grasshopper (16 reputation)

Group: General Forum Members
Points: 16 Visits: 97
This will show errors for "Cannot change owner..." as mentioned above for the master, model, tempdb, and distribution databases, but it will run and successfully update all other databases despite the error. If you want to code around it to avoid the errors, or logically only update the databases that aren't already 'sa' you can do so.

EXEC sp_MSforeachdb
'
EXEC [?].[dbo].sp_changedbowner @loginame = N''sa'', @map = ''false''
'


gfoxxy93
gfoxxy93
Valued Member
Valued Member (59 reputation)Valued Member (59 reputation)Valued Member (59 reputation)Valued Member (59 reputation)Valued Member (59 reputation)Valued Member (59 reputation)Valued Member (59 reputation)Valued Member (59 reputation)

Group: General Forum Members
Points: 59 Visits: 104
Modify this powershell script to loop through an array of servers and then db list.

$SQLAdminUser = 'AdminUser'
$SQLAdminPwd = get-content "PathToSecuredCredentials.txt" | convertto-securestring

$srvConn = New-Object('Microsoft.SqlServer.Management.Common.ServerConnection') ('ServerName', $SQLAdminUser, $SQLAdminPwd)
$srv = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $srvConn

$srv.Databases | where{$_.Name -eq 'DatabaseName'} |
foreach {
$_.SetOwner('sa')
$_.Alter();
}
Go


Permissions

You can't post new topics.
You can't post topic replies.
You can't post new polls.
You can't post replies to polls.
You can't edit your own topics.
You can't delete your own topics.
You can't edit other topics.
You can't delete other topics.
You can't edit your own posts.
You can't edit other posts.
You can't delete your own posts.
You can't delete other posts.
You can't post events.
You can't edit your own events.
You can't edit other events.
You can't delete your own events.
You can't delete other events.
You can't send private messages.
You can't send emails.
You can read topics.
You can't vote in polls.
You can't upload attachments.
You can download attachments.
You can't post HTML code.
You can't edit HTML code.
You can't post IFCode.
You can't post JavaScript.
You can post emoticons.
You can't post or upload images.

Select a forum

































































































































































SQLServerCentral


Search