Changing a 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 that a Windows account QUERYWORKS\aterra
. QUERYWORKS\aterra
has been created in your test VM.
Note
See Appendix D, Creating a SQL Server VM.
If you don't already have one, create a TestDB
database by following the steps the Creating a database recipe.
How to do it...
Open the PowerShell console by going to Start | Accessories | Windows PowerShell | Windows PowerShell ISE.
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 = "KERRIGAN" $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName
Add the following script and run it:
#create database handle $dbName = "TestDB" $db = $server.Databases[$dbName] #display current owner $db.Owner #change owner...