Search code examples
c#sql-server-2012smoalwayson

SMO Equivalent to SET HADR OFF


In SMO (C#), what is the equivalent to...

ALTER DATABASE db SET HADR OFF;

I've looked in the documentation for both the Database and AvailabilityDatabase classes and nothing is really jumping out at me.

The end goal here is to drop a database that is a member of an Availability Group. Currently, we are doing this by first turning HADR off and then dropping the database on all secondary servers, and then, on the primary server, removing the database from the Availability Group and dropping the database there.


Solution

  • Here is the process I've settled on for using SMO to drop a database that is joined to an AlwaysOn Availability Group...

    Server primaryServer = new Server();
    AvailabilityDatabase pDb = primaryServer.AvailabilityGroups[agName].AvailabilityDatabases[dbName];
    pDb.SuspendDataMovement();
    while (!pDb.IsSuspended)
    {
      Thread.Sleep(1000);
      pDb.Refresh();
    }
    
    foreach (var secondary in secondaryServers)
    {
      AvailabilityDatabase sDb = secondary.AvailabilityGroups[agName].AvailabilityDatabases[dbName];
      sDb.SuspendDataMovement();
      while (!sDb.IsSuspended)
      {
        Thread.Sleep(1000);
        sDb.Refresh();
      }
    
      sDb.LeaveAvailabilityGroup(); // this appears to be the equivalent of SET HADR OFF
    
      Database db = secondary.Databases[dbName];
      db.UserAccess = DatabaseUserAccess.Single;
      secondary.KillAllProcesses(dbName);
      db.Drop();
    }
    
    pDb.Drop();
    
    Database db = primaryServer.Databases[dbName];
    db.UserAccess = DatabaseUserAccess.Single;
    primaryServer.KillAllProcesses(dbName);
    db.Drop();