CRM 2011 Automated Deployments – Backup Databases

Gayan Perera, 17 March 2013

Another time consuming task of deploying software updates is backing up existing application files, configuration files, databases etc etc which adds to the overall deployment time. These tasks can be automated.

In this blog post we’ll look at automating the backup of CRM 2011 SQL databases before a deployment.

You’ll need to backup the following CRM databases:

• MSCRM_CONFIG
• *_MSCRM

SQL command to backup a database is:

backup database <database name>
      to disk ='d:\backups\sql\<database name_timestamp>.bak' 
      with format, 
      name ='Full backup of <database name>'

Take a look at the link below to backup a database via PowerShell. http://social.technet.microsoft.com/wiki/contents/articles/900.how-to-sql-server-databases-backup-with-powershell.aspx

To backup the database using a console app/C# use the code below.

using (SqlConnection conn = new SqlConnection(this.ConnectionString))
{
    string path = Path.Combine(this.BackupDirectory, string.Format("{0}_{1:yyyyMMdd_HHmmss}.bak", this.DatabaseName, DateTime.Now));

    SqlCommand cmd = new SqlCommand(
        string.Format(@"backup database {0} to disk ='{1}' with format, name ='Full backup of {0}'",
            this.DatabaseName, path), conn);

    cmd.CommandTimeout = 120;

    conn.Open();

    cmd.ExecuteNonQuery();

    conn.Close();
} 

Enjoy!