Configure SQL Server Always On availability groups with synchronous commit using a distributed network name Stay organized with collections Save and categorize content based on your preferences.
Microsoft SQL ServerAlways On availability groups let you replicate databases across multiple SQL Server Enterprise instances.
Similar toSQL Server Failover Cluster Instances,Always On availability groups use Windows Server Failover Clustering (WSFC) toimplement high availability. However, the two features differ in the followingways:
| Always On availability groups | Failover cluster instances | |
|---|---|---|
| Scope of fail-over | Group of databases | Instance |
| Storage | Not shared | Shared |
For a more detailed comparison, seeComparison of failover cluster instances and availability groups.
Always On availability groups supportmultiple availability modes.This tutorial shows how you can deploy Always On availability groups insynchronous commit mode to implement high availability for one or more databases.
In the setup, you will create three VM instances. Two VM instances,node-1 andnode-2 serve as cluster nodes and run SQL Server.A third VM instance,witness, is used to achieve aquorumin a failover scenario.The three VM instances are distributed over three zones and share a common subnet.
Using a SQL Server Always On availability group, an example database,bookshelf,is synchronously replicated across the two SQL Server instances.
In an on-premises Windows cluster environment,Address Resolution Protocol (ARP) announcementstriggerIP address failover.Google Cloud, however, disregards ARP announcements. Consequently, you must implement one of the following two options: using an internal load balancer and a distributed network name (DNN).
The article assumes that you have already deployed Active Directory on Google Cloudand that you have basic knowledge of SQL Server, Active Directory, and Compute Engine.For more information about Active Directory on Google Cloud,see sectionBefore you begin.
Using a SQL Server Always On availability group, an example database,bookshelf,is synchronously replicated across the two SQL Server instances. A distributednetwork name (DNN) listener in front of the cluster provides a single endpointfor SQL Server clients.
For more information about DNN, seeConfigure a DNN listener for an availability group.
This diagram includes the following:
- Two VM instances in the same region and different zones for the failovercluster called
node-1andnode-2. One hosts the primary replica of theSQL Server database while the other node hosts the secondary replica. - A third VM called
witnessserves as a file share witness to provide atie-breaking vote and achieve a quorum for failover. - A DNN listener in front of the cluster provides a single endpoint for SQLServer clients.
Objectives
- Deploy a WSFC comprising two SQL Server VM instances, and a third VM instancethat acts as a file share witness.
- Create an availability group with synchronous commit.
- Configure adistributed network name (DNN) to route traffic to your availability group with SQL Server
- Verify that the setup is working by simulating a failover.
Costs
This tutorial uses billable components of Google Cloud,including:
Use thepricing calculator to generate a cost estimate based on your projected usage.
Before you begin
To complete the tasks in this tutorial, ensure the following:
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
- Create a project: To create a project, you need the Project Creator role (
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission.Learn how to grant roles.
Verify that billing is enabled for your Google Cloud project.
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
- Create a project: To create a project, you need the Project Creator role (
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission.Learn how to grant roles.
Verify that billing is enabled for your Google Cloud project.
- You have an Active Directory domain with at least one domain controller. You can create anActive Directory domain using Managed Microsoft AD. Alternatively, you can deploy acustom Active Directory environment on Compute Engine and set up aprivate DNS forwarding zone that forwards DNS queries to your domain controllers.
- You have an Active Directory user that has permission to join computers to the domain and can sign in by using RDP. If you're using Managed Microsoft AD, you can use the
setupadminuser. For more information about Active Directory user account provisioning, seeActive Directory user account provisioning - A Google Cloud project and a Virtual Private Cloud (VPC) with connectivity to your Active Directory domain controllers.
- A subnet to use for the Windows Server Failover Cluster VM instances.
Prepare your project and network
To deploy your SQL Server Always On availability groups, you must prepare yourGoogle Cloud project and VPC for the deployment. The following sections discusshow you can do this in detail.
Configure your project and region
To prepare your Google Cloud project for the deployment of SQL Server Always Onavailability groups, do the following:
In the Google Cloud console, openCloud Shell by clicking theActivate Cloud Shell
button.
Initialize the following variables.
VPC_NAME=
VPC_NAMESUBNET_NAME=SUBNET_NAMEReplace the following:
VPC_NAME: name of your VPCSUBNET_NAME: name of your subnet
Set your defaultproject ID.
gcloud config set project
PROJECT_IDReplace
PROJECT_IDwith the ID of your Google Cloud project.Set your default region.
gcloud config set compute/region
REGIONReplace
REGIONwith the ID of theregion you want to deploy in.
Create firewall rules
To allow clients to connect to the SQL Server and the communication between thecluster nodes you need to create several firewall rules. You can usenetwork tagsto simplify the creation of these firewall rules, as follows:
- The two cluster nodes are annotated with the
wsfc-nodetag. - All servers (including the
witness) are annotated with thewsfctag.
To create firewall rules that use these network tags, use the following steps:
- Return to your existing Cloud Shell session.
Create firewall rules to allow traffic between cluster nodes.
SUBNET_CIDR=$(gcloud compute networks subnets describe $SUBNET_NAME --format=value\('ipCidrRange'\))gcloud compute firewall-rules create allow-all-between-wsfc-nodes \ --direction=INGRESS \ --action=allow \ --rules=tcp,udp,icmp \ --enable-logging \ --source-tags=wsfc \ --target-tags=wsfc \ --network=$VPC_NAME \ --priority 10000gcloud compute firewall-rules create allow-sql-to-wsfc-nodes \ --direction=INGRESS \ --action=allow \ --rules=tcp:1433 \ --enable-logging \ --source-ranges=$SUBNET_CIDR \ --target-tags=wsfc-node \ --network=$VPC_NAME \ --priority 10000
Create VM instances
Create and deploy two VM instances for the failover cluster. At any point in time,one of these VMs hosts the primary replica of the SQL Server databasewhile the other node hosts the secondary replica. The two VM instances must:
- have failover clustering and SQL Server installed.
- haveCompute Engine WSFC support enabled.
You use aSQL Server premium imagewhich has SQL Server 2022 preinstalled.
Note: If you plan to bring your own licenses for SQL Server by using theLicense Mobility program,select Windows Server base images for these nodes and install SQL Serverusing your own product keys.To provide a tie-breaking vote and achieve a quorum for the failover scenario,deploy a third VM that serves as afile share witness using the following steps:
- Return to your existing Cloud Shell session.
Create aspecialized scriptfor the WSFC nodes. This script installs the necessary Windows features andcreates firewall rules for WSFC and SQL Server.
cat << "EOF" > specialize-node.ps1$ErrorActionPreference = "stop"# Install required Windows featuresInstall-WindowsFeature Failover-Clustering -IncludeManagementToolsInstall-WindowsFeature RSAT-AD-PowerShell# Open firewall for WSFCnetsh advfirewall firewall add rule name="Allow WSFC health check" dir=in action=allow protocol=TCP localport=59998# Open firewall for SQL Servernetsh advfirewall firewall add rule name="Allow SQL Server" dir=in action=allow protocol=TCP localport=1433# Open firewall for SQL Server replicationnetsh advfirewall firewall add rule name="Allow SQL Server replication" dir=in action=allow protocol=TCP localport=5022# Format data diskGet-Disk | Where partitionstyle -eq 'RAW' | Initialize-Disk -PartitionStyle MBR -PassThru | New-Partition -AssignDriveLetter -UseMaximumSize | Format-Volume -FileSystem NTFS -NewFileSystemLabel 'Data' -Confirm:$false# Create data and log folders for SQL Servermd d:\Datamd d:\LogsEOF
Create the VM instances. On the two VMs that serve as cluster nodes,attach an additional data disk and enable the Windows Server Failover Clusteringby setting the metadata key
enable-wsfctotrue:REGION=$(gcloud config get-value compute/region)ZONE1=
ZONE1ZONE2=ZONE2ZONE3=ZONE3PD_SIZE=200MACHINE_TYPE=n2-standard-8gcloud compute instances create node-1 \ --zone $ZONE1 \ --machine-type $MACHINE_TYPE \ --subnet $SUBNET_NAME \ --image-family sql-ent-2022-win-2022 \ --image-project windows-sql-cloud \ --tags wsfc,wsfc-node \ --boot-disk-size 50 \ --boot-disk-type pd-ssd \ --boot-disk-device-name "node-1" \ --create-disk=name=node-1-datadisk,size=$PD_SIZE,type=pd-ssd,auto-delete=no \ --metadata enable-wsfc=true \ --metadata-from-file=sysprep-specialize-script-ps1=specialize-node.ps1gcloud compute instances create node-2 \ --zone $ZONE2 \ --machine-type $MACHINE_TYPE \ --subnet $SUBNET_NAME \ --image-family sql-ent-2022-win-2022 \ --image-project windows-sql-cloud \ --tags wsfc,wsfc-node \ --boot-disk-size 50 \ --boot-disk-type pd-ssd \ --boot-disk-device-name "node-2" \ --create-disk=name=node-2-datadisk,size=$PD_SIZE,type=pd-ssd,auto-delete=no \ --metadata enable-wsfc=true \ --metadata-from-file=sysprep-specialize-script-ps1=specialize-node.ps1gcloud compute instances create "witness" \ --zone $ZONE3 \ --machine-type e2-medium \ --subnet $SUBNET_NAME \ --image-family=windows-2022 \ --image-project=windows-cloud \ --tags wsfc \ --boot-disk-size 50 \ --boot-disk-type pd-ssd \ --metadata sysprep-specialize-script-ps1="add-windowsfeature FS-FileServer"ReplaceZONE1,ZONE2,ZONE3 based onthe zones you are using.
Note: Depending on yourperformance requirements,consider using a machine type larger thann2-standard-8for the WSFCnodes. Considerdisabling Simultaneous multithreading (SMT)for potential savings on licensing costs.Note: For the purpose of this tutorial, and to fit within the defaultregional SSD Persistent Disk quota, the size of the disks attached to eachVM is smaller than it would be in a production environment. For betterperformance and to accommodate a larger database, increase thesize of each disk.To join the three VM instances to Active Directory, do the following for each ofthe three VM instances:
Monitor the initialization process of the VM by viewing its serial port output.
gcloud compute instances tail-serial-port-output
NAMEReplace
NAMEwith the name of the VM instance.Wait for a few minutes until you see the output
Instance setup finished,then press Ctrl+C. At this point, the VM instance is ready to be used.Create a username and passwordfor the VM instance.
Connect to the VM by using Remote Desktopand sign in using the username and password created in the previous step.
Right-click theStart button (or pressWin+X) and clickWindows PowerShell (Admin).
Note: In this guide, we used Powershell 5.1.Confirm the elevation prompt by clickingYes.
Join the computer to your Active Directory domain and restart.
Add-Computer -Domain
DOMAIN -RestartReplace
DOMAINwith the DNS name of your Active Directory domain.Enter the credentials of an account that has permissions to join a VM tothe domain
Wait for the VM to restart. You have now joined the VM instance to theActive Directory.
Deploying the failover cluster
You can now use the VM instances to deploy a Windows Server Failover Cluster and SQLServer. The following sections discuss how you can do this in detail.
Preparing SQL Server
Create a new user account in Active Directory for SQL Server using the followingsteps.
- Connect to
node-1by using Remote Desktop.Sign in with your domain user account. - Right-click theStart button (or pressWin+X) and clickWindows PowerShell (Admin).
- Confirm the elevation prompt by clickingYes.
Create a domain user account for SQL server and the SQL agent and assigna password:
Note: If you use Managed AD, append$Credential = Get-Credential -UserName sql_server -Message 'Enter password'New-ADUser ` -Name "sql_server" ` -Description "SQL Admin account." ` -AccountPassword $Credential.Password ` -Enabled $true -PasswordNeverExpires $true
-Path "OU=Cloud,DC=example,DC=org"to the command to create the user in theCloudorganizational units (OU).Ensure that the value of the path is the output of the following command:Get-ADOrganizationalUnit -Filter "Name -eq 'Cloud'" | Select-Object -ExpandProperty DistinguishedName
To configure SQL Server, perform the following steps on bothnode-1 andnode-2, use the following steps:
- OpenSQL Server Configuration Manager.
- In the navigation pane, selectSQL Server Services.
- In the list of services, right-clickSQL Server (MSSQLSERVER) and selectProperties.
UnderLog on as, change the account as follows:
- Account name:
DOMAIN\sql_serverwhereDOMAINis the NetBIOS name of your Active Directory domain. - Password: Enter the password you chose previously.
- Account name:
ClickOK.
When prompted to restart SQL Server, selectYes.
SQL Server now runs under a domain user account.
Warning: Make sure you've completed the previous configuration steps on bothVM instances, otherwise setting up the Always On availability group will fail.Create file shares
Create two file shares on the VM instancewitness so that it canstore SQL Server backups and act as a file share witness:
- Connect to
witnessbyusing Remote Desktop.Sign in with your domain user account. - Right-click theStart button (or pressWin+X) and clickWindows PowerShell (Admin).
- Confirm the elevation prompt by clickingYes.
Create a witness file share and grant yourself and the two cluster nodesaccess to the file share.
New-Item "C:\QWitness" –type directoryicacls C:\QWitness\ /grant 'node-1$:(OI)(CI)(M)'icacls C:\QWitness\ /grant 'node-2$:(OI)(CI)(M)'New-SmbShare ` -Name QWitness ` -Path "C:\QWitness" ` -Description "SQL File Share Witness" ` -FullAccess $env:username,node-1$,node-2$
Create another file share to store backups and grant SQL Server full access:
New-Item "C:\Backup" –type directoryNew-SmbShare ` -Name Backup ` -Path "C:\Backup" ` -Description "SQL Backup" ` -FullAccess $env:USERDOMAIN\sql_server
Create the failover cluster
To create the failover cluster, use the following steps:
- Return to the Remote Desktop session on
node-1. - Right-click theStart button (or pressWin+X) and clickWindows PowerShell (Admin).
- Confirm the elevation prompt by clickingYes.
Create a new cluster.
Note: Whencomputer objects are created outside the containerNew-Cluster ` -Name sql-cluster ` -Node node-1,node-2 ` -NoStorage ` -ManagementPointNetworkType Distributed
Computers(in anOU), the permissionCreate Computer objectsmust be delegatedto the cluster's computer account in the OU.Return to the PowerShell session on
witnessand grant the virtualcomputer object of the cluster permission to access the file share.icacls C:\QWitness\ /grant 'sql-cluster$:(OI)(CI)(M)'Grant-SmbShareAccess ` -Name QWitness ` -AccountName 'sql-cluster$' ` -AccessRight Full ` -Force
Return to the PowerShell session on
node-1and configure the clusterto use the file share onwitnessas a cluster quorum.Set-ClusterQuorum -FileShareWitness \\witness\QWitness
Verify that the cluster was created successfully.
Test-Cluster
You might see some warnings that can be safely ignored:
WARNING: System Configuration - Validate All Drivers Signed: The test reported some warnings..WARNING: Network - Validate Network Communication: The test reported some warnings..WARNING:Test Result:HadUnselectedTests, ClusterConditionallyApprovedTesting has completed for the tests you selected. You should review the warnings in the Report. A cluster solution issupported by Microsoft only if you run all cluster validation tests, and all tests succeed (with or without warnings).
You can also launch the Failover Cluster Manager MMC snap-in to review thecluster's health by running
cluadmin.msc.If you're using Managed AD, add the computer account used by the Windows clusterto theCloud Service Domain Join Accounts group so that it can joincomputers to the domain.
Add-ADGroupMember ` -Identity "Cloud Service Domain Join Accounts" ` -Members sql-cluster$
Enable Always On availability groups on both nodes.
Enable-SqlAlwaysOn -ServerInstance node-1 -ForceEnable-SqlAlwaysOn -ServerInstance node-2 -Force
Resolve-DnsName -Name sql-cluster Powershell command.Creating an availability group
You now create a sample databasebookshelf, include it in a new availabilitygroup namedbookshelf-ag and configure high availability.
Creating a database
Create a new database. For the purpose of this tutorial, the database doesn'tneed to contain any data.
- Return to the Remote Desktop session on
node-1. - Open theSQL Server Management Studio.
- In theConnect to server dialog, verify the server name is set to
node-1and selectConnect. - In the menu, selectFile > New > Query with current connection.
Paste the following SQL script into the editor:
-- Create a sample databaseCREATE DATABASE bookshelf ON PRIMARY ( NAME = 'bookshelf', FILENAME='d:\Data\bookshelf.mdf', SIZE = 256MB, MAXSIZE = UNLIMITED, FILEGROWTH = 256MB)LOG ON ( NAME = 'bookshelf_log', FILENAME='d:\Logs\bookshelf.ldf', SIZE = 256MB, MAXSIZE = UNLIMITED, FILEGROWTH = 256MB)GOUSE [bookshelf]SET ANSI_NULLS ONSET QUOTED_IDENTIFIER ONGO-- Create sample tableCREATE TABLE [dbo].[Books] ( [Id] [bigint] IDENTITY(1,1) NOT NULL, [Title] [nvarchar](max) NOT NULL, [Author] [nvarchar](max) NULL, [PublishedDate] [datetime] NULL, [ImageUrl] [nvarchar](max) NULL, [Description] [nvarchar](max) NULL, [CreatedById] [nvarchar](max) NULL, CONSTRAINT [PK_dbo.Books] PRIMARY KEY CLUSTERED ([Id] ASC) WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]GO-- Create a backupEXEC dbo.sp_changedbowner @loginame = 'sa', @map = false; ALTER DATABASE [bookshelf] SET RECOVERY FULL; GO BACKUP DATABASE bookshelf to disk = '\\witness\Backup\bookshelf.bak' WITH INITGO
The script creates a new database with a single table and performs aninitial backup to
witness.SelectExecute to run the SQL script.
Configure high availability
You can now configure high availability for the availability group using eitherT-SQL or Server Management Studio.
Using T-SQL
To configure high availability for the availability group using T-SQL, use thefollowing steps:
Connect to
node-1and then execute the following script to create thebookshelf-agavailability group. Note: In theCREATE LOGIN [
NET_DOMAIN\sql_server] FROM WINDOWS;GOUSE [bookshelf];CREATE USER [NET_DOMAIN\sql_server] FOR LOGIN [NET_DOMAIN\sql_server];GOUSE [master];CREATE ENDPOINT bookshelf_endpoint STATE=STARTED AS TCP (LISTENER_PORT=5022) FOR DATABASE_MIRRORING (ROLE=ALL);GOGRANT CONNECT ON ENDPOINT::[bookshelf_endpoint] TO [NET_DOMAIN\sql_server]GONET_DOMAIN\sql_serverlogin and user,NET_DOMAINis the NetBIOS name of your Active Directory domain.Connect to
node-2and execute the following script. Note: In theCREATE LOGIN [
NET_DOMAIN\sql_server] FROM WINDOWS;GOCREATE ENDPOINT bookshelf_endpoint STATE=STARTED AS TCP (LISTENER_PORT=5022) FOR DATABASE_MIRRORING (ROLE=ALL);GOGRANT CONNECT ON ENDPOINT::[bookshelf_endpoint] TO [NET_DOMAIN\sql_server]GONET_DOMAIN\sql_serverlogin and user,NET_DOMAINis the NetBIOS name of your Active Directory domain.On
node-1and then execute the following script to create thebookshelf-agavailability group.USE master;GOCREATE AVAILABILITY GROUP [bookshelf-ag]WITH (AUTOMATED_BACKUP_PREFERENCE = SECONDARY,CLUSTER_TYPE = WSFC,DB_FAILOVER = ON)FOR DATABASE [bookshelf]REPLICA ON N'node-1' WITH ( ENDPOINT_URL = 'TCP://node-1:5022', AVAILABILITY_MODE = SYNCHRONOUS_COMMIT, FAILOVER_MODE = AUTOMATIC, BACKUP_PRIORITY = 50, SEEDING_MODE = AUTOMATIC, SECONDARY_ROLE(ALLOW_CONNECTIONS = NO) ), N'node-2' WITH ( ENDPOINT_URL = 'TCP://node-2:5022', AVAILABILITY_MODE = SYNCHRONOUS_COMMIT, FAILOVER_MODE = AUTOMATIC, BACKUP_PRIORITY = 50, SEEDING_MODE = AUTOMATIC, SECONDARY_ROLE(ALLOW_CONNECTIONS = NO) );GO
Connect to
node-2and then execute the following script to join thesecondary replica to the availability group and enable automatic seeding.USE master;GOALTER AVAILABILITY GROUP [bookshelf-ag] JOIN;ALTER AVAILABILITY GROUP [bookshelf-ag] GRANT CREATE ANY DATABASE;
Check the status of the availability group.
SELECT * FROM sys.dm_hadr_availability_group_states;GO
You should see
synchronization_health_descasHEALTHY.
Using SQL Server Management Studio
To configure high availability for the availability group using SQL ServerManagement Studio, use the following steps:
- In theObject Explorer window, right-clickAlways On High Availabilityand then selectNew Availability Group Wizard.
- On theSpecify Options page, set the availability group name to
bookshelf-ag, then selectNext. - On theSelect Databases page, select the
bookshelfdatabase,then selectNext. On theSpecify Replicas page, select theReplicas tab.
- SelectAdd replica.
In theConnect to server dialog, enter the server name
node-2andselectConnect.The list of availability replicas now contains SQL Server instances,
node-1andnode-2.Set theAvailability mode toSynchronous commit for both instances.
SetAutomatic failover toEnabled for both instances.
SelectNext.
On theSelect Data Synchronization page, selectAutomatic Seeding.
On theValidation page, verify that all checks are successful. You canignore the availability group listener check.
On theSummary page, selectFinish.
On theResults page, selectClose.
Configure a DNN listener for the availability group
A DNN listener serves as a single endpoint for SQL Server clients. To configurea DNN listener, use the following steps:
- Return to the PowerShell session on
node-1. Execute the following script to create a DNN listener.
$Ag='bookshelf-ag' $Port='
DNN_PORT' $Dns='DNN_NAME' # create the DNN resource with the port as the resource name Add-ClusterResource -Name $Port -ResourceType "Distributed Network Name" -Group $Ag # set the DNS name of the DNN resource Get-ClusterResource -Name $Port | Set-ClusterParameter -Name DnsName -Value $Dns # start the DNN resource Start-ClusterResource -Name $Port # add the Dependency from availability group resource to the DNN resource Set-ClusterResourceDependency -Resource $Ag -Dependency "[$Port]" # restart the availability group resource Stop-ClusterResource -Name $Ag Start-ClusterResource -Name $AgReplace
DNN_PORTwith the DNN listener port. The DNN listener port must be configured with a unique port. For more information, seePort considerations.Replace
DNN_NAMEwith the DNN listener name.Create firewall rules for DNN listener port on both
node-1andnode-2.netsh advfirewall firewall add rule name="Allow DNN listener" dir=in action=allow protocol=TCP localport=
DNN_PORT
Test the failover
You are now ready to test if the failover works as expected:
- Return to the PowerShell session on
witness. Run the following script.
while ($True){ $Conn = New-Object System.Data.SqlClient.SqlConnection $Conn.ConnectionString = "Server=DNN_NAME,DNN_PORT;Integrated Security=true;Initial Catalog=master" $Conn.Open() $Cmd = New-Object System.Data.SqlClient.SqlCommand $Cmd.Connection = $Conn $Cmd.CommandText = "SELECT SERVERPROPERTY('ServerName')" $Adapter = New-Object System.Data.SqlClient.SqlDataAdapter $Cmd $Data = New-Object System.Data.DataSet $Adapter.Fill($Data) | Out-Null $Data.Tables[0] + (Get-Date -Format "MM/dd/yyyy HH:mm:ss") Start-Sleep -Seconds 2}Replace
DNN_NAMEwith the DNN listener name andDNN_PORTwith the DNN listener port.Every 2 seconds, the script connects to SQL Server by using the availabilitygroup listener, and queries the server name.
Leave the script running.
Return to the Remote Desktop session on
node-1to trigger a failover.- InSQL Server Management Studio, navigate toAlways OnHigh Availability > Availability Groups > bookshelf-ag (Primary) andright-click the node.
- SelectFailover.
- On theSelect new primary replica page, verify that
node-2is selectedas new primary replica and that theFailover readiness columnindicatesNo data loss. Then selectNext. - On theConnect to replica page, selectConnect.
- In theConnect to server dialog, verify that the server name is
node-2andclickConnect. - SelectNext and thenFinish.
- On theResults page, verify that the failover was successful.
Return to the PowerShell session on
witness.Observe the output of the running script and notice that the server namechanges from
node-1tonode-2as a result of the failover.Stop the script by pressing
Ctrl+C.
Clean up
After you finish the tutorial, you can clean up the resources that you created so that they stop using quota and incurring charges. The following sections describe how to delete or turn off these resources.
Deleting the project
The easiest way to eliminate billing is to delete the project that you created for the tutorial.
To delete the project:
What's next
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-15 UTC.