Changing database owner
This recipe shows how to programmatically change a SQL Server database owner.
Getting ready
This task assumes you have created a database called TestDB
, and a Windows account QUERYWORKS\srogers
. QUERYWORKS\srogers
has been created in our test VM.
Note
For more information, see Appendix B, Create a SQL Server VM.
If you don't have it, create the database TestDB
by following the steps in the Creating a database recipe.
How to do it...
Let's look at the steps involved in changing a database owner:
Open PowerShell ISE as administrator.
Import the SQLPS module and create a new SMO Server Object:
#import SQL Server module Import-Module SQLPS -DisableNameChecking #replace this with your instance name $instanceName = "localhost" $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName
Add the following script and run:
#create database handle $dbName = "TestDB" $db = $server.Databases[$dbName] #display current owner $db.Owner #change owner...