Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Copy production database to stage or test environment using PowerShell or TSQL

Scenario: when your test environment need a fresh Copy of the data from production or any other scenario when fresh data is needed on another Database you might find yourself seeking a quick and easy solution.

Solution Using TSQL:
when you connect to any of the databases on the server you can copy the database to another database on the same server.

CREATE DATABASE [ProdDB_TSQLFresh] AS COPY OF ProdDB;
DROP DATABASE ProdDB_TSQLCopy;
ALTER DATABASE ProdDB_TSQLFresh MODIFY NAME = ProdDB_TSQLCopy;

Solution Using PowerShell:
"Removing old copy..."
Remove-AzureRmSqlDatabase -ResourceGroupName "ResourceGroupName" -ServerName "ServerName" -DatabaseName "DatabaseName"
"Start Copy... Please wait ... "
New-AzureRmSqlDatabaseCopy -ResourceGroupName "ResourceGroupName" `
-ServerName "ServerName" `
-DatabaseName "SourceDatabaseName" `
-CopyResourceGroupName "DestinationResourceGroupName" `
-CopyServerName "DestinationServerName" `
-CopyDatabaseName "DestinationDatabaseName"
" !Done! "

Automation:
How to automate the process to run on a regular basis?

we recommend using Azure Automation to schedule these commands to run.

follow the instructions here to run it as a PowerShell script or Invoke-SQLCMD to run the T-SQL statements

if you choose the PowerShell option use this piece of code to authenticate with your run-as account:
(This code is in your newly created automation account in the samples runbooks)

$connectionName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Add-AzureRmAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
}
}

Share the post

Copy production database to stage or test environment using PowerShell or TSQL

×

Subscribe to Msdn Blogs | Get The Latest Information, Insights, Announcements, And News From Microsoft Experts And Developers In The Msdn Blogs.

Get updates delivered right to your inbox!

Thank you for your subscription

×