You are on page 1of 210

Contents

Database Mirroring Endpoint


Endpoint Areas
Transport Security for Database Mirroring and Always On Availability Groups
Create a Database Mirroring Endpoint for Windows Authentication (Transact-SQL)
Set Up Login Accounts for Database Mirroring or Always On Availability Groups
Allow Network Access to a Database Mirroring Endpoint Using Windows
Authentication
Use Certificates for a Database Mirroring Endpoint (Transact-SQL)
Allow a Database Mirroring Endpoint to Use Certificates for Outbound Connections
(Transact-SQL)
Allow a Database Mirroring Endpoint to Use Certificates for Inbound Connections
(Transact-SQL)
Database Mirroring
Prerequisites, Restrictions, and Recommendations for Database Mirroring
Database Mirroring Operating Modes
Change Transaction Safety in a Database Mirroring Session (Transact-SQL)
Database Mirroring Witness
Quorum: How a Witness Affects Database Availability
Add a Database Mirroring Witness Using Windows Authentication (Transact-SQL)
Add or Replace a Database Mirroring Witness (SQL Server Management Studio)
Remove the Witness from a Database Mirroring Session (SQL Server)
Role Switching During a Database Mirroring Session
Manually Fail Over a Database Mirroring Session (Transact-SQL)
Manually Fail Over a Database Mirroring Session (SQL Server Management Studio)
Force Service in a Database Mirroring Session (Transact-SQL)
Estimate the Interruption of Service During Role Switching
Possible Failures During Database Mirroring
Mirroring States (SQL Server)
Setting Up Database Mirroring
Prepare a Mirror Database for Mirroring
Set Up an Encrypted Mirror Database
Set Up a Mirror Database to Use the Trustworthy Property (Transact-SQL)
Specify a Server Network Address (Database Mirroring)
Establish a Database Mirroring Session Using Windows Authentication (SQL Server
Management Studio)
Start the Configuring Database Mirroring Security Wizard (SQL Server
Management Studio)
Include Witness Server (Configure Database Mirroring Security Wizard)
Choose Servers to Configure (Configure Database Mirroring Security Wizard)
Principal Server Instance (Configure Database Mirroring Security Wizard)
Mirror Server Instance (Configure Database Mirroring Security Wizard)
Witness Server Instance (Configure Database Mirroring Security Wizard)
Service Accounts (Configure Database Mirroring Security Wizard)
Establish a Database Mirroring Session Using Windows Authentication (Transact-
SQL)
Example: Setting Up Database Mirroring Using Windows Authentication (Transact-
SQL)
Example: Setting Up Database Mirroring Using Certificates (Transact-SQL)
Troubleshoot Database Mirroring Configuration
Connect Clients to a Database Mirroring Session
Pausing and Resuming Database Mirroring
Pause or Resume a Database Mirroring Session (SQL Server)
Removing Database Mirroring
Remove Database Mirroring (SQL Server)
Upgrading Mirrored Instances
Monitoring Database Mirroring
Use Warning Thresholds and Alerts on Mirroring Performance Metrics
Start Database Mirroring Monitor (SQL Server Management Studio)
Database Mirroring Monitor Overview
Register Mirrored Database
Database Mirroring Monitor (Status Page)
Database Mirroring History
Database Mirroring Monitor (Warnings Page)
Set Warning Thresholds
View the State of a Mirrored Database (SQL Server Management Studio)
Database Mirroring: Interoperability and Coexistence
Database Mirroring and SQL Server Failover Cluster Instances
Database Mirroring and Log Shipping
Database Mirroring and Full-Text Catalogs
Database Mirroring and Database Snapshots
Database Mirroring and Replication
The Database Mirroring Endpoint (SQL Server)
8/3/2018 • 4 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server (Windows only) Azure SQL Database Azure SQL Data
Warehouse Parallel Data Warehouse
To participate in Always On availability groups or database mirroring a server instance requires its own,
dedicated database mirroring endpoint. This endpoint is a special-purpose endpoint that is used exclusively to
receive connections from other server instances. On a given server instance, every Always On availability groups
or database mirroring connection to any other server instance uses a single database mirroring endpoint.
Database mirroring endpoints use Transmission Control Protocol (TCP ) to send and receive messages between
the server instances participating database mirroring sessions or hosting availability replicas. The database
mirroring endpoint listens on a unique TCP port number.

NOTE
Client connections to a principal server or primary replica do not use the database mirroring endpoint.

NOTE
The database mirroring feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new
development work, and plan to modify applications that currently use database mirroring to use Always On availability
groups instead.

Server Network Address


The network address of a server instance (its server network address or Endpoint URL) contains the port number
of its endpoint, as well as the system and domain name of its host computer. The port number uniquely identifies
a specific server instance.
The following figure illustrates how two server instances on the same server are uniquely identified. The server
network addresses of both server instances contain the same system name, MYSYSTEM , and domain name,
Adventure-Works.MyDomain.com . To enable the system to route connections to a server instance, a server network
address includes the port number associated with the mirroring endpoint of a particular server instance.
By default, an instance of SQL Server does not contain a database mirroring endpoint. These must be created
manually as part of setting up a database mirroring session. The system administrator must create a separate
endpoint in each server instance that is to participate in database mirroring. Note that if more than one server
instance on a given computer requires a database mirroring endpoint, specify a different port number for each
endpoint.

IMPORTANT
If the computer running SQL Server has a firewall, the firewall configuration must allow both incoming and outgoing
connections for the port specified in the endpoint.

For database mirroring and Always On availability groups, authentication and encryption are configured on the
endpoint. For more information, see Transport Security for Database Mirroring and Always On Availability
Groups (SQL Server).

IMPORTANT
Do not reconfigure an in-use database mirroring endpoint. The server instances use each other's endpoints to learn the
state of the other systems. If the endpoint is reconfigured, it might restart, which can appear to be an error to the other
server instances. This is particularly important for automatic failover mode, in which reconfiguring the endpoint on a
partner could cause a failover to occur.

Determining the Authentication Type for a Database Mirroring


Endpoint
It is important to understand that the SQL Server service accounts of your server instances determine what type
of authentication you can use for your database mirroring endpoints, as follows:
If every server instance is running under a domain service account, you can use Windows Authentication
for your database mirroring endpoints. If all the server instances run as the same domain user account,
the correct user logins exist automatically in both master databases. This simplifies the security
configuration for the availability databases and is recommended.
If any server instances that are hosting the availability replicas for an availability group run as different
accounts, the login each account must be created in master on the other server instance. Then, that login
must be granted CONNECT permissions to connect to the database mirroring endpoint of that server
instance. For more information, Set Up Login Accounts for Database Mirroring or Always On Availability
Groups (SQL Server).
If your server instances use Windows Authentication, you can create database mirroring endpoints by
using Transact-SQL, PowerShell, or the New Availability Group Wizard.

NOTE
If a server instance that is to host an availability replica lacks a database mirroring endpoint, the New Availability
Group Wizard can automatically create a database mirroring endpoint that uses Windows Authentication. For more
information, see Use the Availability Group Wizard (SQL Server Management Studio).

If any server instance is running under a built-in account, such as Local System, Local Service, or Network
Service, or a nondomain account, you must use certificates for endpoint authentication. If you are using
certificates for your database mirroring endpoints, your system administrator must configure each server
instance to use certificates on both outbound and inbound connections.
There is no automated method for configuring database mirroring security using certificates. You will
need to use either CREATE ENDPOINT Transact-SQL statement or the New-SqlHadrEndpoint
PowerShell cmdlet. For more information, see CREATE ENDPOINT (Transact-SQL ). For information
about enabling certificate authentication on a server instance, see Use Certificates for a Database
Mirroring Endpoint (Transact-SQL ).

Related Tasks
To Configure a Database Mirroring Endpoint
Create a Database Mirroring Endpoint for Windows Authentication (Transact-SQL )
Use Certificates for a Database Mirroring Endpoint (Transact-SQL )
Allow a Database Mirroring Endpoint to Use Certificates for Outbound Connections (Transact-
SQL )
Allow a Database Mirroring Endpoint to Use Certificates for Inbound Connections (Transact-SQL )
Specify a Server Network Address (Database Mirroring)
Specify the Endpoint URL When Adding or Modifying an Availability Replica (SQL Server)
Use the Availability Group Wizard (SQL Server Management Studio)
To View Information About the Database Mirroring Endpoint
sys.database_mirroring_endpoints (Transact-SQL )

See Also
Transport Security for Database Mirroring and Always On Availability Groups SQL Server)
Troubleshoot Database Mirroring Configuration (SQL Server)
sys.dm_hadr_availability_replica_states (Transact-SQL )
sys.dm_db_mirroring_connections (Transact-SQL )
Transport Security - Database Mirroring - Always On
Availability
6/12/2018 • 5 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
Transport security involves authentication and, optionally, encryption of messages exchanged between the
databases. For database mirroring and Always On availability groups, authentication and encryption are
configured on the database mirroring endpoint. For an introduction to database mirroring endpoints, see The
Database Mirroring Endpoint (SQL Server).
In this Topic:
Authentication
Data Encryption
Related Tasks

Authentication
Authentication is the process of verifying that a user is who the user claims to be. Connections between database
mirroring endpoints require authentication. Connection requests from a partner or witness, if any, must be
authenticated.
The type of authentication used by a server instance for database mirroring or Always On availability groups is a
property of the database mirroring endpoint. Two types of transport security are available for database mirroring
endpoints: Windows Authentication (the Security Support Provider Interface (SSPI)) and certificate-based
authentication.
Windows Authentication
Under Windows Authentication, each server instance logs in to the other side using the Windows credentials of
the Windows user account under which the process is running. Windows Authentication might require some
manual configuration of login accounts, as follows:
If the instances of SQL Server run as services under the same domain account, no extra configuration is
required.
If the instances of SQL Server run as services under different domain accounts (in the same or trusted
domains), the login of each account must be created in master on each of the other server instances, and
that login must be granted CONNECT permissions on the endpoint.
If the instances of SQL Server run as the Network Service account, the login of the each host computer
account (DomainName\ComputerName$) must be created in master on each of the other servers, and
that login must be granted CONNECT permissions on the endpoint. This is because a server instance
running under the Network Service account authenticates using the domain account of the host computer.

NOTE
For an example of setting up a database mirroring session using Windows Authentication, see Example: Setting Up
Database Mirroring Using Windows Authentication (Transact-SQL).
Certificates
In some situations, such as when server instances are not in trusted domains or when SQL Server is running as a
local service, Windows Authentication is unavailable. In such cases, instead of user credentials, certificates are
required to authenticate connection requests. The mirroring endpoint of each server instance must be configured
with its own locally created certificate.
The encryption method is established when the certificate is created. For more information, see Allow a Database
Mirroring Endpoint to Use Certificates for Outbound Connections (Transact-SQL ). Carefully manage the
certificates that you use.
A server instance uses the private key of its own certificate to establish its identity when setting up a connection.
The server instance that receives the connection request uses the public key of the sender's certificate to
authenticate the sender's identity. For example, consider two server instances, Server_A and Server_B. Server_A
uses its private key to encrypt the connection header before sending a connection request to Server_B. Server_B
uses the public key of Server_A's certificate to decrypt the connection header. If the decrypted header is correct,
Server_B knows that the header was encrypted by Server_A, and the connection is authenticated. If the
decrypted header is incorrect, Server_B knows that the connection request is inauthentic and refuses the
connection.

Data Encryption
By default, a database mirroring endpoint requires encryption of data sent over mirroring connections. In this
case, the endpoint can connect only to endpoints that also use encryption. Unless you can guarantee that your
network is secure, we recommend that you require encryption for your database mirroring connections.
However, you can disable encryption or make it supported, but not required. If encryption is disabled, data is
never encrypted and the endpoint cannot connect to an endpoint that requires encryption. If encryption is
supported, data is encrypted only if the opposite endpoint either supports or requires encryption.

NOTE
Mirroring endpoints created by SQL Server Management Studio are created with encryption either required or disabled. To
change the encryption setting to SUPPORTED, use the ALTER ENDPOINT Transact-SQL statement. For more information,
see ALTER ENDPOINT (Transact-SQL).

Optionally, you can control the encryption algorithms that can be used by an endpoint, by specifying one of the
following values for the ALGORITHM option in a CREATE ENDPOINT statement or ALTER ENDPOINT
statement:

ALGORITHM VALUE DESCRIPTION

RC4 Specifies that the endpoint must use the RC4 algorithm. This
is the default.

** Warning *\* The RC4 algorithm is deprecated. This feature


will be removed in a future version of Microsoft SQL Server.
Do not use this feature in new development work, and
modify applications that currently use this feature as soon as
possible. We recommend that you use AES.

AES Specifies that the endpoint must use the AES algorithm.

AES RC4 Specifies that the two endpoints will negotiate for an
encryption algorithm with this endpoint giving preference to
the AES algorithm.
ALGORITHM VALUE DESCRIPTION

RC4 AES Specifies that the two endpoints will negotiate for an
encryption algorithm with this endpoint giving preference to
the RC4 algorithm.

If connecting endpoints specify both algorithms but in different orders, the endpoint accepting the connection
wins.

NOTE
The RC4 algorithm is only supported for backward compatibility. New material can only be encrypted using RC4 or
RC4_128 when the database is in compatibility level 90 or 100. (Not recommended.) Use a newer algorithm such as one of
the AES algorithms instead. In SQL Server 2012 (11.x)and higher versions, material encrypted using RC4 or RC4_128 can
be decrypted in any compatibility level.
Though considerably faster than AES, RC4 is a relatively weak algorithm, while AES is a relatively strong algorithm.
Therefore, we recommend that you use the AES algorithm.

For information about the Transact-SQL syntax for specifying encryption, see CREATE ENDPOINT (Transact-
SQL ).

Related Tasks
To configure transport security for a database mirroring endpoint
Create a Database Mirroring Endpoint for Windows Authentication (Transact-SQL )
Establish a Database Mirroring Session Using Windows Authentication (SQL Server Management
Studio)
Create a Database Mirroring Endpoint for Windows Authentication (Transact-SQL )
Allow a Database Mirroring Endpoint to Use Certificates for Outbound Connections (Transact-SQL )

See Also
Choose an Encryption Algorithm
ALTER ENDPOINT (Transact-SQL )
DROP ENDPOINT (Transact-SQL )
Security Center for SQL Server Database Engine and Azure SQL Database
Manage Metadata When Making a Database Available on Another Server Instance (SQL Server)
The Database Mirroring Endpoint (SQL Server)
sys.database_mirroring_endpoints (Transact-SQL )
sys.dm_db_mirroring_connections (Transact-SQL )
Troubleshoot Database Mirroring Configuration (SQL Server)
Troubleshoot Always On Availability Groups Configuration (SQL Server)
Create a Database Mirroring Endpoint for Windows
Authentication (Transact-SQL)
6/12/2018 • 6 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
This topic describes how to create a database mirroring endpoint that uses Windows Authentication in SQL
Server 2017 by using Transact-SQL. To support database mirroring or Always On availability groups each
instance of SQL Server requires a database mirroring endpoint. A server instance can have only one database
mirroring endpoint, which has a single port. A database mirroring endpoint can use any port that is available on
the local system when the endpoint is created. All database mirroring sessions on a server instance listen on that
port, and all incoming connections for database mirroring use that port.

IMPORTANT
If a database mirroring endpoint exists and is already in use, we recommend that you use that endpoint. Dropping an in-
use endpoint disrupts existing sessions.

In This Topic
Before you begin: Security
To create a database mirroring endpoint, using: Transact-SQL

Before You Begin


Security
The authentication and encryption methods of the server instance are established by the system administrator.

IMPORTANT
The RC4 algorithm is deprecated. This feature will be removed in a future version of Microsoft SQL Server. Do not use this
feature in new development work, and modify applications that currently use this feature as soon as possible. We
recommend that you use AES.

Permissions
Requires CREATE ENDPOINT permission, or membership in the sysadmin fixed server role. For more
information, see GRANT Endpoint Permissions (Transact-SQL ).

Using Transact-SQL
To Create a Database Mirroring Endpoint That Uses Windows Authentication
1. Connect to the instance of SQL Server on which you want to create a database mirroring endpoint.
2. From the Standard bar, click New Query.
3. Determine if a database mirroring endpoint already exists by using the following statement:
SELECT name, role_desc, state_desc FROM sys.database_mirroring_endpoints;

IMPORTANT
If a database mirroring endpoint already exists for the server instance, use that endpoint for any other sessions
you establish on the server instance.

4. To use Transact-SQL to create an endpoint to use with Windows Authentication, use a CREATE
ENDPOINT statement. The statement takes the following general form:
CREATE ENDPOINT <endpointName>
STATE=STARTED
AS TCP ( LISTENER_PORT = <listenerPortList> )
FOR DATABASE_MIRRORING
(
[ AUTHENTICATION = WINDOWS [ <authorizationMethod> ]
]
[ [,] ENCRYPTION = REQUIRED
[ ALGORITHM { <algorithm> } ]
]
[,] ROLE = <role>
)
where
<endpointName> is a unique name for the database mirroring endpoint of the server instance.
STARTED specifies that the endpoint is to be started and to begin listening for connections. A
database mirroring endpoint typically is created in the STARTED state. Alternatively, you can start a
session in a STOPPED state (the default) or DISABLED state.
<listenerPortList> is a single port number (nnnn) on which you want the server to listen for
database mirroring messages. Only TCP is allowed; specifying any other protocol causes an error.
A port number can be used only once per computer system. A database mirroring endpoint can
use any port that is available on the local system when the endpoint is created. To identify the ports
currently being used by TCP endpoints on the system, use the following Transact-SQL statement:

SELECT name, port FROM sys.tcp_endpoints;

IMPORTANT
Each server instance requires one and only one unique listener port.

For Windows Authentication, the AUTHENTICATION option is optional, unless you want the
endpoint to use only NTLM or Kerberos to authenticate connections. <authorizationMethod>
specifies the method used to authenticate connections as one of the following: NTLM, KERBEROS,
or NEGOTIATE. The default, NEGOTIATE, causes the endpoint to use the Windows negotiation
protocol to choose either NTLM or Kerberos. Negotiation enables connections with or without
authentication, depending on the authentication level of the opposite endpoint.
ENCRYPTION is set to REQUIRED by default. This means that all connections to this endpoint
must use encryption. However, you can disable encryption or make it optional on an endpoint. The
alternatives are as follows:

VALUE DEFINITION

DISABLED Specifies that data sent over a connection is not


encrypted.

SUPPORTED Specifies that the data is encrypted only if the


opposite endpoint specifies either SUPPORTED or
REQUIRED.

REQUIRED Specifies that data sent over a connection must be


encrypted.

If an endpoint requires encryption, the other endpoint must have ENCRYPTION set to either
SUPPORTED or REQUIRED.
<algorithm> provides the option of specifying the encryption standards for the endpoint. The
value of <algorithm> can be one following algorithms or combinations of algorithms: RC4, AES,
AES RC4, or RC4 AES.
AES RC4 specifies that this endpoint will negotiate for the encryption algorithm, giving preference
to the AES algorithm. RC4 AES specifies that this endpoint will negotiate for the encryption
algorithm, giving preference to the RC4 algorithm. If both endpoints specify both algorithms but in
different orders, the endpoint accepting the connection wins.

NOTE
The RC4 algorithm is deprecated. This feature will be removed in a future version of Microsoft SQL Server.
Do not use this feature in new development work, and modify applications that currently use this feature
as soon as possible. We recommend that you use AES.

<role> defines the role or roles that the server can perform. Specifying ROLE is required.
However, the role of the endpoint is relevant only for database mirroring. For Always On
availability groups, the role of the endpoint is ignored.
To allow a server instance to serve as one role for one database mirroring session and different
role for another session, specify ROLE=ALL. To restrict a server instance to being either a partner
or a witness, specify ROLE=PARTNER or ROLE=WITNESS, respectively.

NOTE
For more information about Database Mirroring options for different editions of SQL Server, see Features
Supported by the Editions of SQL Server 2016.

For a complete description of the CREATE ENDPOINT syntax, see CREATE ENDPOINT (Transact-
SQL ).
NOTE
To change an existing endpoint, use ALTER ENDPOINT (Transact-SQL).

Example: Creating Endpoints to Support for Database Mirroring (Transact-SQL )


The following example creates database mirroring endpoints for the default server instances on three separate
computer systems:

ROLE OF SERVER INSTANCE NAME OF HOST COMPUTER

Partner (initially in the principal role) SQLHOST01\.

Partner (initially in the mirror role) SQLHOST02\.

Witness SQLHOST03\.

In this example, all three endpoints use port number 7022, though any available port number would work. The
AUTHENTICATION option is unnecessary, because the endpoints use the default type, Windows Authentication.
The ENCRYPTION option is also unnecessary, because the endpoints are all intended to negotiate the
authentication method for a connection, which is the default behavior for Windows Authentication. Also, all of
the endpoints require the encryption, which is the default behavior.
Each server instance is limited to serving as either a partner or a witness, and the endpoint of each server
expressly specifies which role (ROLE=PARTNER or ROLE=WITNESS ).

IMPORTANT
Each server instance can have only one endpoint. Therefore, if you want a server instance to be a partner in some sessions
and the witness in others, specify ROLE=ALL.

--Endpoint for initial principal server instance, which


--is the only server instance running on SQLHOST01.
CREATE ENDPOINT endpoint_mirroring
STATE = STARTED
AS TCP ( LISTENER_PORT = 7022 )
FOR DATABASE_MIRRORING (ROLE=PARTNER);
GO
--Endpoint for initial mirror server instance, which
--is the only server instance running on SQLHOST02.
CREATE ENDPOINT endpoint_mirroring
STATE = STARTED
AS TCP ( LISTENER_PORT = 7022 )
FOR DATABASE_MIRRORING (ROLE=PARTNER);
GO
--Endpoint for witness server instance, which
--is the only server instance running on SQLHOST03.
CREATE ENDPOINT endpoint_mirroring
STATE = STARTED
AS TCP ( LISTENER_PORT = 7022 )
FOR DATABASE_MIRRORING (ROLE=WITNESS);
GO

Related Tasks
To Configure a Database Mirroring Endpoint
Create a Database Mirroring Endpoint for Always On Availability Groups (SQL Server PowerShell)
Use Certificates for a Database Mirroring Endpoint (Transact-SQL )
Allow a Database Mirroring Endpoint to Use Certificates for Outbound Connections (Transact-
SQL )
Allow a Database Mirroring Endpoint to Use Certificates for Inbound Connections (Transact-SQL )
Specify a Server Network Address (Database Mirroring)
Specify the Endpoint URL When Adding or Modifying an Availability Replica (SQL Server)
To View Information About the Database Mirroring Endpoint
sys.database_mirroring_endpoints (Transact-SQL )

See Also
ALTER ENDPOINT (Transact-SQL )
Choose an Encryption Algorithm
CREATE ENDPOINT (Transact-SQL )
Specify a Server Network Address (Database Mirroring)
Example: Setting Up Database Mirroring Using Windows Authentication (Transact-SQL )
The Database Mirroring Endpoint (SQL Server)
Set Up Login Accounts - Database Mirroring Always
On Availability
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
For two server instances to connect to each other's database mirroring endpoint point, the login account of each
instance requires access to the other instance. Also, each login account requires connect permission to the
Database Mirroring endpoint of the other instance.
The impact of this requirement depends on whether the server instances run as the same domain user account:
If the server instances run as the same domain user account, the correct user logins exist automatically in
both master databases. This simplifies the security configuration for Database Mirroring and Always On
Availability Groups.
If the server instances run as different user accounts, user logins on the server instance that hosts the
principal server or primary replica must be manually reproduced on the server instance that hosts the
mirror server or on every server instance that hosts a secondary replica. For more information, see Create
a Login for a Different Account and Grant Connect Permission, later in this topic.

IMPORTANT
To create a more secure environment, consider using separate domain accounts for each server instance.

Create a Login for a Different Account


If two server instances run as different accounts, the system administrator must use the CREATE LOGIN Transact-
SQL statement to create a login for the startup service account of the remote instance for each server instance.
For more information, see CREATE LOGIN (Transact-SQL ).

IMPORTANT
If you run SQL Server under a non-domain account, you must use certificates. For more information, see Use Certificates for
a Database Mirroring Endpoint (Transact-SQL).

For example, for the server instance sqlA, which runs under loginA, to connect to the server instance sqlB, which
runs under loginB, loginA must exist on sqlB, and loginB must exist on sqlA. In addition, for a database mirroring
session that includes a witness server instance (sqlC ) and in which the three server instances run under different
domain accounts, the following logins must be created:

ON INSTANCE... CREATE LOGINS FOR AND GRANT CONNECTION PERMISSION TO ...

sqlA sqlB and sqlC

sqlB sqlA and sqlC

sqlC sqlA and sqlB


NOTE
It is possible to connect with the network service account by using the machine account instead of a domain user. If the
machine account is used, it must be added as a user on the other server instance.

Grant Connect Permission


Once a login has been created on a server instance, the login must be granted permission to connect to the
database mirroring endpoint of the server instance. The system administrator grants the connect permission using
a GRANT Transact-SQL statement. For more information, see GRANT (Transact-SQL ).

Related Tasks
Create a Login
Allow Network Access to a Database Mirroring Endpoint Using Windows Authentication (SQL Server).
Use Certificates for a Database Mirroring Endpoint (Transact-SQL )

See Also
The Database Mirroring Endpoint (SQL Server)
Troubleshoot Database Mirroring Configuration (SQL Server)
Troubleshoot Always On Availability Groups Configuration (SQL Server)
Database Mirroring - Allow Network Access -
Windows Authentication
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
Using Windows Authentication for connecting the database mirroring endpoints of two instances of SQL Server
requires manual configuration of login accounts under the following conditions:
If the instances of SQL Server run as services under different domain accounts (in the same or trusted
domains), the login of each account must be created in master on each of the remote server instances and
that login must be granted CONNECT permissions on the endpoint.
If the instances of SQL Server run as the Network Service account, the login of the each host computer
account (DomainName\ComputerName$) must be created in master on each of the remote server
instances and that login must be granted CONNECT permissions on the endpoint. This is because a server
instance running under the Network Service account authenticates using the domain account of the host
computer.

NOTE
Ensure that an endpoint exists for each of the server instances. For more information, see Create a Database Mirroring
Endpoint for Windows Authentication (Transact-SQL).

To configure logins for Windows Authentication


1. For the user account of each instance of SQL Server, create a login on the other instances of SQL Server.
Use a CREATE LOGIN statement with the FROM WINDOWS clause.
For more information, see Create a Login.
2. Also, to ensure that the login user has access to the endpoint, use the GRANT statement to grant connect
permissions on the endpoint to the login. Note that granting connect permissions to the endpoint is
unnecessary if the user is an Administrator.
For more information, see Grant a Permission to a Principal.

Example
The following Transact-SQL example creates a SQL Server login for a user account named Otheruser that
belongs to a domain called Adomain . The example then grants this user connect permissions to a pre-existing
database mirroring endpoint named Mirroring_Endpoint .

USE master;
GO
CREATE LOGIN [Adomain\Otheruser] FROM WINDOWS;
GO
GRANT CONNECT on ENDPOINT::Mirroring_Endpoint TO [Adomain\Otheruser];
GO
See Also
Overview of Always On Availability Groups (SQL Server)
Database Mirroring (SQL Server)
Transport Security for Database Mirroring and Always On Availability Groups (SQL Server)
The Database Mirroring Endpoint (SQL Server)
Use Certificates for a Database Mirroring Endpoint
(Transact-SQL)
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
To enable certificate authentication for database mirroring on a given server instance, the system administrator
must configure each server instance to use certificates on both outbound and inbound connections. Outbound
connections must be configured first.

NOTE
All mirroring connections on a server instance use a single database mirroring endpoint, and you must specify the
authentication method of the server instance when you create the endpoint. Therefore, you can use only one form of
authentication per server instance for database mirroring.

Configuring Outbound Connections


Follow these steps on each server instance that you are configuring for database mirroring:
1. In the master database, create a database master key.
2. In the master database, create an encrypted certificate on the server instance.
3. Create an endpoint for the server instance using its certificate.
4. Back up the certificate to a file and securely copy it to the other system or systems.
You must complete these steps for each partner and the witness, if there is one.
For more information, see Allow a Database Mirroring Endpoint to Use Certificates for Outbound
Connections (Transact-SQL ).

Configuring Inbound Connections


Next, follow these steps for each partner that you are configuring for database mirroring. In the master
database:
1. Create a login for the other system.
2. Create a user for that login.
3. Obtain the certificate for the mirroring endpoint of the other server instance.
4. Associate the certificate with the user created in step 2.
5. Grant CONNECT permission on the login for that mirroring endpoint.
If there is a witness, you must also set up inbound connections for it. This requires setting up logins, users,
and certificates for the witness on both of the partners, and vice versa.
For more information, see Allow a Database Mirroring Endpoint to Use Certificates for Inbound
Connections (Transact-SQL ).
Security
Unless you can guarantee that your network is secure, we recommend that you use encryption for database
mirroring connections. For more information, see The Database Mirroring Endpoint (SQL Server).
When copying a certificate to another system, use a secure copy method. Be extremely careful to keep all of your
certificates secure.

See Also
Create a Database Master Key
CREATE MASTER KEY (Transact-SQL )
Transport Security for Database Mirroring and Always On Availability Groups (SQL Server)
Security Center for SQL Server Database Engine and Azure SQL Database
The Database Mirroring Endpoint (SQL Server)
Database Mirroring - Use Certificates for Outbound
Connections
6/12/2018 • 4 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
This topic describes the steps for configuring server instances to use certificates to authenticate outbound
connections for database mirroring. Outbound connection configuration must be done before you can set up
inbound connections.

NOTE
All mirroring connections on a server instance use a single database mirroring endpoint, and you must specify the
authentication method of the server instance when you create the endpoint.

The process of configuring outbound connections, involves the following general steps:
1. In the master database, create a database Master Key.
2. In the master database, create an encrypted certificate on the server instance.
3. Create an endpoint for the server instance using its certificate.
4. Back up the certificate to a file and securely copy it to the other system or systems.
You must complete these steps for each partner and the witness, if there is one.
The following procedure describes these steps in detail. For each step, the procedure provides an example
for configuring a server instance on a system named HOST_A. The accompanying Example section
demonstrates the same steps for another server instance on a system named HOST_B.

Procedure
To configure server instances for outbound mirroring connections (On HOST_A)
1. On the master database, create the database Master Key, if none exists. To view the existing keys for a
database, use the sys.symmetric_keys catalog view.
To create the database Master Key, use the following Transact-SQL command:

CREATE MASTER KEY ENCRYPTION BY PASSWORD = '<1_Strong_Password!>';


GO

Use a unique, strong password, and record it in a safe place.


For more information, see CREATE MASTER KEY (Transact-SQL ) and Create a Database Master Key.
2. In the master database, create an encrypted certificate on the server instance to use for its outbound
connections for database mirroring.
For example, to create a certificate for the HOST_A system.
IMPORTANT
If you intend to use the certificate for more than one year, specify the expiry date in UTC time by using the
EXPIRY_DATE option in your CREATE CERTIFICATE statement. Also, we recommend that you use SQL Server
Management Studio to create a Policy-Based Management rule to alert you when your certificates are expiring.
Using the Policy Management Create New Condition dialog box, create this rule on the @ExpirationDate field of
the Certificate facet. For more information, see Administer Servers by Using Policy-Based Management and
Securing SQL Server.

USE master;
CREATE CERTIFICATE HOST_A_cert
WITH SUBJECT = 'HOST_A certificate for database mirroring',
EXPIRY_DATE = '11/30/2013';
GO

For more information, see CREATE CERTIFICATE (Transact-SQL ).


To view the certificates in the master database, you can use the following Transact-SQL statements:

USE master;
SELECT * FROM sys.certificates;

For more information, see sys.certificates (Transact-SQL ).


3. Ensure that the database mirroring endpoint exist on each of the server instances.
If a database mirroring endpoint already exists for the server instance, you should reuse that endpoint for
any other sessions you establish on the server instance. To determine whether a database mirroring
endpoint exists on a server instance and to view its configuration, use the following statement:

SELECT name, role_desc, state_desc, connection_auth_desc, encryption_algorithm_desc


FROM sys.database_mirroring_endpoints;

If no endpoint exists, create an endpoint that uses this certificate for outbound connections and that uses
the certificate's credentials for verification on the other system. This is a server-wide endpoint that is used
by all mirroring sessions in which the server instance participates.
For example, to create a mirroring endpoint for the example server instance on HOST_A.

CREATE ENDPOINT Endpoint_Mirroring


STATE = STARTED
AS TCP (
LISTENER_PORT=7024
, LISTENER_IP = ALL
)
FOR DATABASE_MIRRORING (
AUTHENTICATION = CERTIFICATE HOST_A_cert
, ENCRYPTION = REQUIRED ALGORITHM AES
, ROLE = ALL
);
GO

For more information, see CREATE ENDPOINT (Transact-SQL ).


4. Back up the certificate and copy it to the other system or systems. This is necessary in order to configure
inbound connections on the other system.
BACKUP CERTIFICATE HOST_A_cert TO FILE = 'C:\HOST_A_cert.cer';
GO

For more information, see BACKUP CERTIFICATE (Transact-SQL ).


Copy this certificate using any secure method you choose. Be extremely careful to keep all of your
certificates secure.
The example code in the preceding steps configure outbound connections on HOST_A.
You now need to perform the equivalent outbound steps for HOST_B. These steps are illustrated in the
following Example section.

Example
The following example demonstrates configuring HOST_B for outbound connections.

USE master;
--Create the database Master Key, if needed.
CREATE MASTER KEY ENCRYPTION BY PASSWORD = '<Strong_Password_#2>';
GO
-- Make a certifcate on HOST_B server instance.
CREATE CERTIFICATE HOST_B_cert
WITH SUBJECT = 'HOST_B certificate for database mirroring',
EXPIRY_DATE = '11/30/2013';
GO
--Create a mirroring endpoint for the server instance on HOST_B.
CREATE ENDPOINT Endpoint_Mirroring
STATE = STARTED
AS TCP (
LISTENER_PORT=7024
, LISTENER_IP = ALL
)
FOR DATABASE_MIRRORING (
AUTHENTICATION = CERTIFICATE HOST_B_cert
, ENCRYPTION = REQUIRED ALGORITHM AES
, ROLE = ALL
);
GO
--Backup HOST_B certificate.
BACKUP CERTIFICATE HOST_B_cert TO FILE = 'C:\HOST_B_cert.cer';
GO
--Using any secure copy method, copy C:\HOST_B_cert.cer to HOST_A.

Copy the certificate to the other system using any secure method you choose. Be extremely careful to keep all of
your certificates secure.

IMPORTANT
After you set up outbound connections, you must configure inbound connections on each server instance for the other
server instance or instances. For more information, see Allow a Database Mirroring Endpoint to Use Certificates for
Inbound Connections (Transact-SQL).

For information on creating a mirror database, including a Transact-SQL example, see Prepare a Mirror
Database for Mirroring (SQL Server).
For a Transact-SQL example of establishing a high-performance mode session, see Example: Setting Up
Database Mirroring Using Certificates (Transact-SQL ).
.NET Framework Security
Unless you can guarantee that your network is secure, we recommend that you use encryption for database
mirroring connections.
When copying a certificate to another system, use a secure copy method.

See Also
Choose an Encryption Algorithm
Prepare a Mirror Database for Mirroring (SQL Server)
ALTER ENDPOINT (Transact-SQL )
Example: Setting Up Database Mirroring Using Certificates (Transact-SQL )
The Database Mirroring Endpoint (SQL Server)
Troubleshoot Database Mirroring Configuration (SQL Server)
Set Up an Encrypted Mirror Database
Database Mirroring - Use Certificates for Inbound
Connections
6/12/2018 • 4 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
This topic describes the steps for configuring server instances to use certificates to authenticate inbound
connections for database mirroring. Before you can set up inbound connections, you must configure outbound
connections on each server instance. For more information, see Allow a Database Mirroring Endpoint to Use
Certificates for Outbound Connections (Transact-SQL ).
The process of configuring inbound connections, involves the following general steps:
1. Create a login for other system.
2. Create a user for that login.
3. Obtain the certificate for the mirroring endpoint of the other server instance.
4. Associate the certificate with the user created in step 2.
5. Grant CONNECT permission on the login for that mirroring endpoint.
If there is a witness, you must also set up inbound connections for it. This requires setting up logins, users,
and certificates for the witness on both of the partners, and vice versa.
The following procedure describes these steps in detail. For each step, the procedure provides an example
for configuring a server instance on a system named HOST_A. The accompanying Example section
demonstrates the same steps for another server instance on a system named HOST_B.
To configure server instances for inbound mirroring connections (on HOST_A )
1. Create a login for the other system.
The following example creates a login for the system, HOST_B, in the master database of the server
instance on HOST_A; in this example, the login is named HOST_B_login . Substitute a password of your
own for the sample password.

USE master;
CREATE LOGIN HOST_B_login
WITH PASSWORD = '1Sample_Strong_Password!@#';
GO

For more information, see CREATE LOGIN (Transact-SQL ).


To view the logins on this server instance, you can use the following Transact-SQL statement:

SELECT * FROM sys.server_principals

For more information, see sys.server_principals (Transact-SQL ).


2. Create a user for that login.
The following example creates a user, HOST_B_user , for the login created in the preceding step.
USE master;
CREATE USER HOST_B_user FOR LOGIN HOST_B_login;
GO

For more information, see CREATE USER (Transact-SQL ).


To view the users on this server instance, you can use the following Transact-SQL statement:

SELECT * FROM sys.sysusers;

For more information, see sys.sysusers (Transact-SQL ).


3. Obtain the certificate for the mirroring endpoint of the other server instance.
If you have not already done so when configuring outbound connections, obtain a copy of the certificate
for the mirroring endpoint of the remote server instance. To do this, back up the certificate on that server
instance as described in Allow a Database Mirroring Endpoint to Use Certificates for Outbound
Connections (Transact-SQL ). When copying a certificate to another system, use a secure copy method. Be
extremely careful to keep all of your certificates secure.
For more information, see BACKUP CERTIFICATE (Transact-SQL ).
4. Associate the certificate with the user created in step 2.
The following example, associates the certificate of HOST_B with its user on HOST_A.

USE master;
CREATE CERTIFICATE HOST_B_cert
AUTHORIZATION HOST_B_user
FROM FILE = 'C:\HOST_B_cert.cer'
GO

For more information, see CREATE CERTIFICATE (Transact-SQL ).


To view the certificates on this server instance, use the following Transact-SQL statement:

SELECT * FROM sys.certificates

For more information, see sys.certificates (Transact-SQL ).


5. Grant CONNECT permission on the login for the remote mirroring endpoint.
For example, to grant permission on HOST_A to the remote server instance on HOST_B to connect to its
local login—that is, to connect to HOST_B_login —use the following Transact-SQL statements:

USE master;
GRANT CONNECT ON ENDPOINT::Endpoint_Mirroring TO [HOST_B_login];
GO

For more information, see GRANT Endpoint Permissions (Transact-SQL ).


This completes setting up certificate authentication for HOST_B to log in to HOST_A.
You now need to perform the equivalent inbound steps for HOST_A on HOST_B. These steps are
illustrated in the inbound portion of the example in the Example section, below.
Example
The following example demonstrates configuring HOST_B for inbound connections.

NOTE
This example uses a certificate file containing the HOST_A certificate that is created by a code snippet in Allow a Database
Mirroring Endpoint to Use Certificates for Outbound Connections (Transact-SQL).

USE master;
--On HOST_B, create a login for HOST_A.
CREATE LOGIN HOST_A_login WITH PASSWORD = 'AStrongPassword!@#';
GO
--Create a user, HOST_A_user, for that login.
CREATE USER HOST_A_user FOR LOGIN HOST_A_login
GO
--Obtain HOST_A certificate. (See the note
-- preceding this example.)
--Asscociate this certificate with the user, HOST_A_user.
CREATE CERTIFICATE HOST_A_cert
AUTHORIZATION HOST_A_user
FROM FILE = 'C:\HOST_A_cert.cer';
GO
--Grant CONNECT permission for the server instance on HOST_A.
GRANT CONNECT ON ENDPOINT::Endpoint_Mirroring TO HOST_A_login
GO

If you intend to run in high-safety mode with automatic failover, you must repeat the same set up steps to
configure the witness for outbound and inbound connections.
For information on creating a mirror database, including a Transact-SQL example, see Prepare a Mirror Database
for Mirroring (SQL Server).
For a Transact-SQL example of establishing a high-performance mode session, see Example: Setting Up
Database Mirroring Using Certificates (Transact-SQL ).

.NET Framework Security


When copying a certificate to another system, use a secure copy method. Be extremely careful to keep all of your
certificates secure.

See Also
Transport Security for Database Mirroring and Always On Availability Groups (SQL Server)
GRANT Endpoint Permissions (Transact-SQL )
Set Up an Encrypted Mirror Database
The Database Mirroring Endpoint (SQL Server)
Troubleshoot Database Mirroring Configuration (SQL Server)
Database Mirroring (SQL Server)
6/12/2018 • 16 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse

NOTE
This feature is in maintenance mode and may be removed in a future version of Microsoft SQL Server. Avoid using this
feature in new development work, and plan to modify applications that currently use this feature. Use Always On
availability groups instead.

Database mirroring is a solution for increasing the availability of a SQL Server database. Mirroring is
implemented on a per-database basis and works only with databases that use the full recovery model.

IMPORTANT
For information about support for database mirroring, restrictions, prerequisites, recommendations for configuring
partner servers, and recommendations for deploying database mirroring, see Prerequisites, Restrictions, and
Recommendations for Database Mirroring.

Benefits of Database Mirroring


Database mirroring is a simple strategy that offers the following benefits:
Increases availability of a database.
In the event of a disaster, in high-safety mode with automatic failover, failover quickly brings the
standby copy of the database online (without data loss). In the other operating modes, the database
administrator has the alternative of forcing service (with possible data loss) to the standby copy of the
database. For more information, see Role Switching, later in this topic.
Increases data protection.
Database mirroring provides complete or almost complete redundancy of the data, depending on
whether the operating mode is high-safety or high-performance. For more information, see Operating
Modes, later in this topic.
A database mirroring partner running on SQL Server 2008 Enterprise or later versions automatically
tries to resolve certain types of errors that prevent reading a data page. The partner that is unable to
read a page requests a fresh copy from the other partner. If this request succeeds, the unreadable page
is replaced by the copy, which usually resolves the error. For more information, see Automatic Page
Repair (Availability Groups: Database Mirroring).
Improves the availability of the production database during upgrades.
To minimize downtime for a mirrored database, you can sequentially upgrade the instances of SQL
Server that are hosting the failover partners. This will incur the downtime of only a single failover. This
form of upgrade is known as a rolling upgrade. For more information, see Upgrading Mirrored
Instances.
Database Mirroring Terms and Definitions
automatic failover
The process by which, when the principal server becomes unavailable, the mirror server to take over the role
of principal server and brings its copy of the database online as the principal database.
failover partners
The two server instances (the principal server or the mirror server) that act as role-switching partners for a
mirrored database.
forced service
A failover initiated by the database owner upon the failure of the principal server that transfers service to the
mirror database while it is in an unknown state.
High-performance mode
The database mirroring session operates asynchronously and uses only the principal server and mirror server.
The only form of role switching is forced service (with possible data loss).
High-safety mode
The database mirroring session operates synchronously and, optionally, uses a witness, as well as the principal
server and mirror server.
manual failover
A failover initiated by the database owner, while the principal server is still running, that transfers service from
the principal database to the mirror database while they are in a synchronized state.
mirror database
The copy of the database that is typically fully synchronized with the principal database.
mirror server
In a database mirroring configuration, the server instance on which the mirror database resides.
principal database
In database mirroring, a read-write database whose transaction log records are applied to a read-only copy of
the database (a mirror database).
principal server
In database mirroring, the partner whose database is currently the principal database.
redo queue
Received transaction log records that are waiting on the disk of a mirror server.
role
The principal server and mirror server perform complementary principal and mirror roles. Optionally, the role
of witness is performed by a third server instance.
role switching
The taking over of the principal role by the mirror.
send queue
Unsent transaction log records that have accumulated on the log disk of the principal server.
session
The relationship that occurs during database mirroring among the principal server, mirror server, and witness
server (if present).
After a mirroring session starts or resumes, the process by which log records of the principal database that
have accumulated on the principal server are sent to the mirror server, which writes these log records to disk
as quickly as possible to catch up with the principal server.
Transaction safety
A mirroring-specific database property that determines whether a database mirroring session operates
synchronously or asynchronously. There are two safety levels: FULL and OFF.
Witness
For use only with high-safety mode, an optional instance of SQL Server that enables the mirror server to
recognize when to initiate an automatic failover. Unlike the two failover partners, the witness does not serve
the database. Supporting automatic failover is the only role of the witness.

Overview of Database Mirroring


Database mirroring maintains two copies of a single database that must reside on different server instances of
SQL Server Database Engine. Typically, these server instances reside on computers in different locations.
Starting database mirroring on a database, initiates a relationship, known as a database mirroring session,
between these server instances.
One server instance serves the database to clients (the principal server). The other instance acts as a hot or
warm standby server (the mirror server), depending on the configuration and state of the mirroring session.
When a database mirroring session is synchronized, database mirroring provides a hot standby server that
supports rapid failover without a loss of data from committed transactions. When the session is not
synchronized, the mirror server is typically available as a warm standby server (with possible data loss).
The principal and mirror servers communicate and cooperate as partners in a database mirroring session. The
two partners perform complementary roles in the session: the principal role and the mirror role. At any given
time, one partner performs the principal role, and the other partner performs the mirror role. Each partner is
described as owning its current role. The partner that owns the principal role is known as the principal server,
and its copy of the database is the current principal database. The partner that owns the mirror role is known
as the mirror server, and its copy of the database is the current mirror database. When database mirroring is
deployed in a production environment, the principal database is the production database.
Database mirroring involves redoing every insert, update, and delete operation that occurs on the principal
database onto the mirror database as quickly as possible. Redoing is accomplished by sending a stream of
active transaction log records to the mirror server, which applies log records to the mirror database, in
sequence, as quickly as possible. Unlike replication, which works at the logical level, database mirroring works
at the level of the physical log record. Beginning in SQL Server 2008, the principal server compresses the
stream of transaction log records before sending it to the mirror server. This log compression occurs in all
mirroring sessions.

NOTE
A given server instance can participate in multiple concurrent database mirroring sessions with the same or different
partners. A server instance can be a partner in some sessions and a witness in other sessions. The mirror server instance
must be running the same edition of SQL Server.

In This Section:
Operating Modes
Role Switching
Concurrent Sessions
Client Connections
Impact of Pausing a Session on the Principal Transaction Log
Operating Modes
A database mirroring session runs with either synchronous or asynchronous operation. Under asynchronous
operation, the transactions commit without waiting for the mirror server to write the log to disk, which
maximizes performance. Under synchronous operation, a transaction is committed on both partners, but at the
cost of increased transaction latency.
There are two mirroring operating modes. One of them, high-safety mode supports synchronous operation.
Under high-safety mode, when a session starts, the mirror server synchronizes the mirror database together
with the principal database as quickly as possible. As soon as the databases are synchronized, a transaction is
committed on both partners, at the cost of increased transaction latency.
The second operating mode, high-performance mode, runs asynchronously. The mirror server tries to keep up
with the log records sent by the principal server. The mirror database might lag somewhat behind the principal
database. However, typically, the gap between the databases is small. However, the gap can become significant
if the principal server is under a heavy work load or the system of the mirror server is overloaded.
In high-performance mode, as soon as the principal server sends a log record to the mirror server, the
principal server sends a confirmation to the client. It does not wait for an acknowledgement from the mirror
server. This means that transactions commit without waiting for the mirror server to write the log to disk. Such
asynchronous operation enables the principal server to run with minimum transaction latency, at the potential
risk of some data loss.
All database mirroring sessions support only one principal server and one mirror server. This configuration is
shown in the following illustration.

High-safety mode with automatic failover requires a third server instance, known as a witness. Unlike the two
partners, the witness does not serve the database. The witness supports automatic failover by verifying
whether the principal server is up and functioning. The mirror server initiates automatic failover only if the
mirror and the witness remain connected to each other after both have been disconnected from the principal
server.
The following illustration shows a configuration that includes a witness.

For more information, see Role Switching, later in this topic.


NOTE
Establishing a new mirroring session or adding a witness to an existing mirroring configuration requires that all involved
server instances run the same version of SQL Server. However, when you are upgrading to SQL Server 2008 or a later
version, the versions of the involved instances can vary. For more information, see Upgrading Mirrored Instances.

Transaction Safety and Operating Modes


Whether an operating mode is asynchronous or synchronous depends on the transaction safety setting. If you
exclusively use SQL Server Management Studio to configure database mirroring, transaction safety settings
are configured automatically when you select the operation mode.
If you use Transact-SQL to configure database mirroring, you must understand how to set transaction safety.
Transaction safety is controlled by the SAFETY property of the ALTER DATABASE statement. On a database
that is being mirrored, SAFETY is either FULL or OFF.
If the SAFETY option is set to FULL, database mirroring operation is synchronous, after the initial
synchronizing phase. If a witness is set in high-safety mode, the session supports automatic failover.
If the SAFETY option is set to OFF, database mirroring operation is asynchronous. The session runs in
high-performance mode, and the WITNESS option should also be OFF.
For more information, see Database Mirroring Operating Modes.
Role Switching
Within the context of a database mirroring session, the principal and mirror roles are typically interchangeable
in a process known as role switching. Role switching involves transferring the principal role to the mirror
server. In role switching, the mirror server acts as the failover partner for the principal server. When a role
switch occurs, the mirror server takes over the principal role and brings its copy of the database online as the
new principal database. The former principal server, if available, assumes the mirror role, and its database
becomes the new mirror database. Potentially, the roles can switch back and forth repeatedly.
The following three forms of role switching exist.
Automatic failover
This requires high-safety mode and the presence of the mirror server and a witness. The database must
already be synchronized, and the witness must be connected to the mirror server.
The role of the witness is to verify whether a given partner server is up and functioning. If the mirror
server loses its connection to the principal server but the witness is still connected to the principal
server, the mirror server does not initiate a failover. For more information, see Database Mirroring
Witness.
Manual failover
This requires high-safety mode. The partners must be connected to each other, and the database must
already be synchronized.
Forced service (with possible data loss)
Under high-performance mode and high-safety mode without automatic failover, forcing service is
possible if the principal server has failed and the mirror server is available.

IMPORTANT
High-performance mode is intended to run without a witness. But if a witness exists, forcing service requires that
the witness is connected to the mirror server.
In any role-switching scenario, as soon as the new principal database comes online, the client
applications can recover quickly by reconnecting to the database.
Concurrent Sessions
A given server instance can participate in multiple, concurrent database mirroring sessions (once per mirrored
database) with the same or different server instances. Often, a server instance serves exclusively as a partner
or a witness in all of its database mirroring sessions. However, because each session is independent of the
other sessions, a server instance can act as a partner in some sessions and as a witness in other sessions. For
example, consider the following four sessions among three server instances ( SSInstance_1 , SSInstance_2 , and
SSInstance_3 ). Each server instance serves as a partner in some sessions and as a witness in others:

SESSION FOR SESSION FOR SESSION FOR SESSION FOR


SERVER INSTANCE DATABASE A DATABASE B DATABASE C DATABASE D

SSInstance_1 Witness Partner Partner Partner

SSInstance_2 Partner Witness Partner Partner

SSInstance_3 Partner Partner Witness Witness

The following figure illustrates two server instances that are participating as partners together in two
mirroring sessions. One session is for a database named Db_1, and the other session is for a database named
Db_2.

Each of the databases is independent of the others. For example, a server instance might initially be the mirror
server for two databases. If one of those databases fails over, the server instance becomes the principal server
for the failed-over database while remaining the mirror server for the other database.
As another example, consider a server instance that is the principal server for two or more databases running
in high-safety mode with automatic failover, If the server instance fails, all of the databases automatically
failover to their respective mirror databases.
When setting up a server instance to operate both as a partner and a witness, be sure that the database
mirroring endpoint supports both roles (for more information, see The Database Mirroring Endpoint (SQL
Server)). Also, ensure that the system has sufficient resources to reduce resource contention.

NOTE
Because mirrored databases are independent of each other, databases cannot fail over as a group.

Client Connections
Client-connection support for database mirroring sessions is provided by the Microsoft .NET Data Provider
for SQL Server. For more information, see Connect Clients to a Database Mirroring Session (SQL Server).
Impact of Pausing a Session on the Principal Transaction Log
At any time, the database owner can pause a session. Pausing preserves the session state while removing
mirroring. When a session is paused, the principal server does not send any new log records to the mirror
server. All of these records remain active and accumulate in the transaction log of the principal database. As
long as a database mirroring session remains paused, the transaction log cannot be truncated. Therefore, if the
database mirroring session is paused for too long, the log can fill up.
For more information, see Pausing and Resuming Database Mirroring (SQL Server).

Setting Up Database Mirroring Session


Before a mirroring session can begin, the database owner or system administrator must create the mirror
database, set up endpoints and logins, and, in some cases, create and set up certificates. For more information,
see Setting Up Database Mirroring (SQL Server).

Interoperability and Coexistence with Other Database Engine


Features
Database mirroring can be used with the following features or components of SQL Server.
Log shipping
Full-text catalogs
Database snapshots
Replication

In This Section
Prerequisites, Restrictions, and Recommendations for Database Mirroring
Describes the prerequisites and recommendations for setting up database mirroring.
Database Mirroring Operating Modes
Contains information about the synchronous and asynchronous operating modes for database mirroring
sessions, and about switching partner roles during a database mirroring session.
Database Mirroring Witness
Describes the role of a witness in database mirroring, how to use a single witness in multiple mirroring
sessions, software and hardware recommendations for witnesses, and the role of the witness in automatic
failover. It also contains information about adding or removing a witness.
Role Switching During a Database Mirroring Session (SQL Server)
Contains information about switching partner roles during a database mirroring session, including automatic
failover, manual failover, and forced service (with possible data loss). Also, contains information about
estimating the interruption of service during role switching.
Possible Failures During Database Mirroring
Discusses physical, operating system, and SQL Server problems, including hard errors and soft errors, that
can cause a failure in a database mirroring session. Discusses how the mirroring time-out mechanism
responds to soft errors.
The Database Mirroring Endpoint (SQL Server)
Discusses how the database mirroring endpoint functions.
Setting Up Database Mirroring (SQL Server)
Contains topics about the prerequisites, recommendations, and steps for setting up database mirroring.
Connect Clients to a Database Mirroring Session (SQL Server)
Contains topics covering client connection-string attributes and the algorithms for connecting and
reconnecting a client to a mirrored database.
Pausing and Resuming Database Mirroring (SQL Server)
Discusses what happens while database mirroring is paused, including the impact on transaction log
truncation, and contains descriptions about how to pause and resume database mirroring.
Removing Database Mirroring (SQL Server)
Discusses the impact of removing mirroring and contains descriptions about how to end a session
Monitoring Database Mirroring (SQL Server)
Contains information about using Database Mirroring Monitor or the dbmmonitor stored procedures to
monitor database mirroring or sessions.

Related Tasks
Configuration Tasks
Using SQL Server Management Studio
Start the Configuring Database Mirroring Security Wizard (SQL Server Management Studio)
Establish a Database Mirroring Session Using Windows Authentication (SQL Server Management
Studio)
Using Transact-SQL
Allow Network Access to a Database Mirroring Endpoint Using Windows Authentication (SQL Server)
Allow a Database Mirroring Endpoint to Use Certificates for Outbound Connections (Transact-SQL )
Allow a Database Mirroring Endpoint to Use Certificates for Inbound Connections (Transact-SQL )
Create a Database Mirroring Endpoint for Windows Authentication (Transact-SQL )
Establish a Database Mirroring Session Using Windows Authentication (Transact-SQL )
Add a Database Mirroring Witness Using Windows Authentication (Transact-SQL )
Set Up a Mirror Database to Use the Trustworthy Property (Transact-SQL )
Using Transact-SQL or SQL Server Management Studio
Upgrading Mirrored Instances
Prepare a Mirror Database for Mirroring (SQL Server)
Administrative Tasks
Transact-SQL
Change Transaction Safety in a Database Mirroring Session (Transact-SQL )
Manually Fail Over a Database Mirroring Session (Transact-SQL )
Force Service in a Database Mirroring Session (Transact-SQL )
Pause or Resume a Database Mirroring Session (SQL Server)
Remove the Witness from a Database Mirroring Session (SQL Server)
Remove Database Mirroring (SQL Server)
SQL Server Management Studio
Add or Replace a Database Mirroring Witness (SQL Server Management Studio)
Manually Fail Over a Database Mirroring Session (SQL Server Management Studio)
Pause or Resume a Database Mirroring Session (SQL Server)
Remove the Witness from a Database Mirroring Session (SQL Server)
Remove Database Mirroring (SQL Server)

See Also
The Database Mirroring Endpoint (SQL Server)
Automatic Page Repair (Availability Groups: Database Mirroring)
Troubleshoot Database Mirroring Configuration (SQL Server)
Database Mirroring: Interoperability and Coexistence (SQL Server)
Prerequisites, Restrictions, and Recommendations for Database Mirroring
Overview of Always On Availability Groups (SQL Server)
About Log Shipping (SQL Server)
Prerequisites, Restrictions, and Recommendations for
Database Mirroring
6/12/2018 • 5 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse

NOTE
This feature is in maintenance mode and may be removed in a future version of Microsoft SQL Server. Avoid using this
feature in new development work, and plan to modify applications that currently use this feature. Use Always On availability
groups instead.

This topic describes the prerequisites and recommendations for setting up database mirroring. For an introduction
to database mirroring, see Database Mirroring (SQL Server).

Support For Database Mirroring


For information about support for database mirroring in SQL Server 2017, see Editions and Supported Features
for SQL Server 2016.
Note that database mirroring works with any supported database compatibility level. For information about the
supported compatibility levels, see ALTER DATABASE Compatibility Level (Transact-SQL ).

Prerequisites
For a mirroring session to be established, the partners and the witness, if any, must be running on the same
version of SQL Server.
The two partners, that is the principal server and mirror server, must be running the same edition of SQL
Server. The witness, if any, can run on any edition of SQL Server that supports database mirroring.

NOTE
You can upgrade server instances that are partners in a mirroring session to a more recent version of SQL Server. For
more information, see Upgrading Mirrored Instances.

The database must use the full recovery model. The simple and bulk-logged recovery models do not
support database mirroring. Therefore, bulk operations are always fully logged for a mirrored database. For
information about recovery models, see Recovery Models (SQL Server).
Verify that the mirror server has sufficient disk space for the mirror database.

NOTE
For information about how to use database mirroring on a replicated database, see Database Mirroring and
Replication (SQL Server).

When you are creating the mirror database on the mirror server, make sure that you restore the backup of
the principal database specifying the same database name WITH NORECOVERY. Also, all log backups that
were created after that backup was taken must also be applied, again WITH NORECOVERY.

IMPORTANT
If database mirroring has been stopped, before you can restart it, any subsequent log backups taken on the principal
database must be applied to the mirror database.

Restrictions
Only user databases can be mirrored. You cannot mirror the master, msdb, tempdb, or model databases.
A mirrored database cannot be renamed during a database mirroring session.
Database mirroring does not support FILESTREAM. A FILESTREAM filegroup cannot be created on the
principal server. Database mirroring cannot be configured for a database that contains FILESTREAM
filegroups.
Database mirroring is not supported with either cross-database transactions or distributed transactions.
For more information, see Cross-Database Transactions and Distributed Transactions for Always On
Availability Groups and Database Mirroring (SQL Server).

Recommendations for Configuring Partner Servers


The partners should run on comparable systems that can handle identical workloads.

NOTE
If you plan to use high-safety mode with automatic failover, the normal load on each failover partner should be less
than 50 percent of the CPU. If your work load overloads the CPU, a failover partner might be unable to ping the
other server instances in the mirroring session. This causes a unnecessary failover. If you cannot keep the CPU usage
under 50 percent, we recommend that you use either high-safety mode without automatic failover or high-
performance mode.

If possible, the path (including the drive letter) of the mirror database should be identical to the path of the
principal database. You must include the MOVE option in the RESTORE statement if the file layouts must
differ. For example, if the principal database is on drive 'F:' but the mirror system lacks an F: drive.

IMPORTANT
If you move the database files when you create the mirror database, you might be unable to add files to the
database later without mirroring being suspended.

All of the server instances in a mirroring session should use the same master code page and collation.
Differences can cause a problem during mirroring setup.
Optionally, estimate the time to fail over a database, to make sure that the system configuration will provide
the performance you require. For more information, see Estimate the Interruption of Service During Role
Switching (Database Mirroring).
For best performance, use a dedicated network adapter (network interface card) for mirroring.
We make no recommendations about whether a wide-area network (WAN ) is reliable enough for database
mirroring in high-safety mode. If you decide to use high-safety mode over a WAN, be cautious about how
you add a witness to the session, because unwanted automatic failovers can occur. For more information,
see Recommendations for Deploying Database Mirroring, later in this topic.

Recommendations for Deploying Database Mirroring


Optimal database mirroring performance is obtained by using asynchronous operation. A mirroring session that
uses synchronous operation might experience slowed performance when its workload generates large amounts of
transaction log data.
In test environments, it is appropriate to explore all the operating modes to evaluate how database mirroring
performs. However, before you deploy mirroring into a production environment, make sure that you understand
how the network functions in the real world.
High-safety mode with automatic failover is designed for a high-service network that has either a dedicated
connection or a fairly simple network configuration that minimizes the sources of possible network failures. Such
a high-quality network environment is necessary for high-safety mode with automatic failover and is
recommended for all database mirroring sessions. However, high-performance mode and high-safety mode
without automatic failover are much less affected by network reliability.
Therefore, for production environments we recommend that you adhere to the following deployment guidelines:
1. Start running in asynchronous, high-performance mode. This mode is the least sensitive to the network
environment and provides the best configuration for exploring how mirroring works. We recommend that
you run your system asynchronously until you are confident that your bandwidth supports mirroring and
you have developed an understanding of mirroring setup and of the performance of asynchronous mode in
your environment. For more information, see Database Mirroring Operating Modes.

IMPORTANT
Throughout testing, we recommend that you monitor your sessions for network errors that cause database
mirroring to fail. For more information about potential sources of failure, see Possible Failures During Database
Mirroring. For information about how to monitor database mirroring, see Monitoring Database Mirroring (SQL
Server).

2. When you are confident that asynchronous operation is meeting the business needs, you might want to try
synchronous operation to improve your data protection. When you test how synchronous mirroring works
in your environment, we recommend that first you test high-safety mode without automatic failover. The
primary purpose of this testing is to see how synchronous operation affects the database performance. For
more information, see Database Mirroring Operating Modes.
3. Wait to enable automatic failover until you are confident that high-safety mode without automatic failover
is meeting the business needs and that network errors are not causing failures. For more information, see
Role Switching During a Database Mirroring Session (SQL Server).

See Also
Setting Up Database Mirroring (SQL Server)
Transport Security for Database Mirroring and Always On Availability Groups (SQL Server)
Database Mirroring (SQL Server)
Troubleshoot Database Mirroring Configuration (SQL Server)
Database Mirroring Operating Modes
6/12/2018 • 15 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
This topic describes the synchronous and asynchronous operating modes for database mirroring sessions.

NOTE
For an introduction to database mirroring, see Database Mirroring (SQL Server).

Terms and Definitions


This section introduces a few terms that are central to this topic.
High-performance mode
The database mirroring session operates asynchronously and uses only the principal server and mirror server.
The only form of role switching is forced service (with possible data loss).
High-safety mode
The database mirroring session operates synchronously and, optionally, uses a witness, as well as the principal
server and mirror server.
Transaction safety
A mirroring-specific database property that determines whether a database mirroring session operates
synchronously or asynchronously. There are two safety levels: FULL and OFF.
Witness
For use only with high-safety mode, an optional instance of SQL Server that enables the mirror server to
recognize whether to initiate an automatic failover. Unlike the two failover partners, the witness does not serve
the database. Supporting automatic failover is the only role of the witness.

Asynchronous Database Mirroring (High-Performance Mode)


This section describes how asynchronous database mirroring works, when it is appropriate to use high-
performance mode, and how to respond if the principal server fails.

NOTE
Most editions of SQL Server 2017 support only synchronous database mirroring ("Safety Full Only"). For information
about editions that fully support database mirroring, see "High Availability (Always On)" in Editions and Supported
Features for SQL Server 2016.

When transaction safety is set to OFF, the database mirroring session operates asynchronously. Asynchronous
operation supports only one operating mode—high-performance mode. This mode enhances performance at
the expense of high availability. High-performance mode uses just the principal server and the mirror server.
Problems on the mirror server never impact the principal server. On the loss of the principal server, the mirror
database is marked DISCONNECTED but is available as a warm standby.
High-performance mode, supports only one form of role switching: forced service (with possible data loss),
which uses the mirror server as a warm standby server. Forced service is one of the possible responses to the
failure of the principal server. Because data loss is possible, you should consider other alternatives before
forcing service to the mirror. For more information, see Responding to Failure of the Principal, later in this
topic.
The following figure shows the configuration of a session using high-performance mode.

In high-performance mode, as soon as the principal server sends the log for a transaction to the mirror server,
the principal server sends a confirmation to the client, without waiting for an acknowledgement from the
mirror server. Transactions commit without waiting for the mirror server to write the log to disk. Asynchronous
operation permits the principal server to run with minimum transaction latency.
The mirror server attempts to keep up with the log records sent by the principal server. But the mirror
database might lag somewhat behind the principal database, though typically the gap between the databases is
small. However, the gap can become substantial if the principal server is under a heavy work load or the
system of the mirror server is over loaded.
In This Section:
When Is High-Performance Mode Appropriate?
The Impact of a Witness on High-Performance Mode
Responding to Failure of the Principal
When Is High-Performance Mode Appropriate?
High-performance mode can be useful in a disaster-recovery scenario in which the principal and mirror
servers are separated by a significant distance and where you do not want small errors to impact the principal
server.

NOTE
Log shipping can be a supplement to database mirroring and is a favorable alternative to asynchronous database
mirroring. For information about the advantages of log shipping, see High Availability Solutions (SQL Server). For
information on using log shipping with database mirroring, see Database Mirroring and Log Shipping (SQL Server).

The Impact of a Witness on High-Performance Mode


If you use Transact-SQL to configure high-performance mode, whenever the SAFETY property is set to OFF,
we strongly recommend that the WITNESS property also be set to OFF. A witness can coexist with high-
performance mode, but the witness provides no benefit and introduces risk.
If the witness is disconnected from the session when either partner goes down, the database becomes
unavailable. This is because, even though high-performance mode does not require a witness, if one is set, the
session requires a quorum consisting of two or more server instances. If the session losses quorum, it cannot
serve the database.
When a witness is set in a high-performance mode session, the enforcement of quorum means that:
If the mirror server is lost, the principal server must be connected to the witness. Otherwise, the
principal server takes its database offline until either the witness or mirror server rejoins the session.
If the principal server is lost, forcing service to the mirror server requires that the mirror server be
connected to the witness.
NOTE
For information about the types of quorums, see Quorum: How a Witness Affects Database Availability (Database
Mirroring).

Responding to Failure of the Principal


When the principal fails, the database owner has several choices, as follows:
Leave the database unavailable until the principal becomes available again.
If the principal database and its transaction log are intact, this choice preserves all of the committed
transactions at the expense of availability.
Stop the database mirroring session, manually update the database, and then begin a new database
mirroring session.
If the principal database is lost but the principal server is still running, immediately attempt to back up
the tail of the log on the principal database. If the tail-log backup succeeds, removing mirroring may be
your best alternative. After removing mirroring, you can restore the log onto the former mirror
database, which preserves all of the data.

NOTE
If the tail-log backup failed and you cannot wait for the principal server to recover, consider forcing service, which
has the advantage of maintaining the session state.

Force service (with possible data loss) on the mirror server.


Forced service is strictly a disaster recovery method and should be used sparingly. Forcing service is
possible only if the principal server is down, the session is asynchronous (transaction safety is set to
OFF ), and either the session does not have any witness (the WITNESS property is set to OFF ) or the
witness is connected to the mirror server (that is, they have quorum).
Forcing service causes the mirror server to assume the role of principal and serve its copy of the
database for clients. When service is forced, whatever transaction logs the principal has not yet sent to
the mirror server are lost. Therefore, you should limit forced service to situations where possible data
loss is acceptable and immediate database availability is critical. For information on how forced service
works and on best practices for using it, see Role Switching During a Database Mirroring Session (SQL
Server).

Synchronous Database Mirroring (High-Safety Mode)


This section describes how synchronous database mirroring works, including the alternative high-safety modes
(with automatic failover and without automatic failover), and contains information about the role of the witness
in automatic failover.
When transaction safety is set to FULL, the database mirroring session runs in high-safety mode and operates
synchronously after an initial synchronizing phase. This section describes the details of database mirroring
sessions that are configured for synchronous operation.
To achieve synchronous operation for a session, the mirror server must synchronize the mirror database with
the principal database. When the session begins, the principal server begins sending its active log to the mirror
server. The mirror server writes all of the incoming log records to disk as quickly as possible. As soon as all of
the received log records have been written to disk, the databases are synchronized. As long as the partners
remain in communication, the databases remain synchronized.
NOTE
To monitor state changes in a database mirroring session, use the Database Mirroring State Change event class. For
more information, see Database Mirroring State Change Event Class.

After synchronization finishes, every transaction committed on the principal database is also committed on the
mirror server, guaranteeing protection of the data. This is achieved by waiting to commit a transaction on the
principal database, until the principal server receives a message from the mirror server stating that it has
hardened the transaction's log to disk. Note the wait for this message increases the latency of the transaction.
The time required for synchronization depends essentially on how far the mirror database was behind the
principal database at the start of the session (measured by the number of log records initially received from the
principal server), the work load on the principal database, and the speed of the mirror system. After a session is
synchronized, the hardened log that has yet to be redone on the mirror database remains in the redo queue.
As soon as the mirror database becomes synchronized, the state of both the copies of the database changes to
SYNCHRONIZED.
Synchronous operation is maintained in the following manner:
1. On receiving a transaction from a client, the principal server writes the log for the transaction to the
transaction log.
2. The principal server writes the transaction to the database and, concurrently, sends the log record to the
mirror server. The principal server waits for an acknowledgement from the mirror server before
confirming either of the following to the client: a transaction commit or a rollback.
3. The mirror server hardens the log to disk and returns an acknowledgement to the principal server.
4. On receiving the acknowledgement from the mirror server, the principal server sends a confirmation
message to the client.
High-safety mode protects your data by requiring the data to be synchronized between two places. All
the committed transactions are guaranteed to be written to disk on the mirror server.
In This Section:
High-Safety Mode Without Automatic Failover
High-Safety Mode with Automatic Failover
High-Safety Mode Without Automatic Failover
The following figure shows the configuration of high-safety mode without automatic failover. The
configuration consists of only the two partners.

When the partners are connected and the database is already synchronized, manual failover is supported. If
the mirror server instance goes down, the principal server instance is unaffected and runs exposed (that is
without mirroring the data). If the principal server is lost, the mirror is suspended, but service can be forced to
the mirror server (with possible data loss). For more information, see Role Switching During a Database
Mirroring Session (SQL Server).
High-Safety Mode with Automatic Failover
Automatic failover provides high availability by ensuring that the database is still served after the loss of one
server. Automatic failover requires that the session possess a third server instance, the witness, which ideally
resides on a third computer. The following figure shows the configuration of a high-safety mode session that
supports automatic failover.

Unlike the two partners, the witness does not serve the database. The witness simply supports automatic
failover by verifying whether the principal server is up and functioning. The mirror server initiates automatic
failover only if the mirror and the witness remain connected to each other after both have been disconnected
from the principal server.
When a witness is set, the session requires quorum—a relationship between at least two server instances that
allows the database to be made available. For more information, see Database Mirroring Witness and
Quorum: How a Witness Affects Database Availability (Database Mirroring).
Automatic failover requires the following conditions:
The database is already synchronized.
The failure occurs while all three server instances are connected, and the witness and mirror server
remain connected.
The loss of a partner has the following effect:
If the principal server becomes unavailable under the above conditions, automatic failover occurs. The
mirror server switches to the role of principal, and it offers its database as the principal database.
If the principal server becomes unavailable when those conditions are not met, forcing service (with
possible data loss) might be possible. For more information, see Role Switching During a Database
Mirroring Session (SQL Server).
If the only mirror server becomes unavailable, the principal and witness continue.
If the session loses its witness, quorum requires both partners. If either partner loses quorum, both
partners lose quorum, and the database becomes unavailable until quorum is re-established. This
quorum requirement makes sure that in the absence of a witness the database never runs exposed, that
is without being mirrored.

NOTE
If you expect the witness to remain disconnected for a significant amount of time, we recommend that you remove the
witness from the session until it becomes available.

Transact-SQL Settings and Database Mirroring Operating Modes


This section describes a database mirroring session in terms of the ALTER DATABASE settings and states of
the mirrored database and witness, if any. The section is aimed at users who manage database mirroring
primarily or exclusively using Transact-SQL, rather than using SQL Server Management Studio.
TIP
As an alternative to using Transact-SQL, you can control the operating mode of a session in Object Explorer using the
Mirroring page of the Database Properties dialog box. For more information, see Establish a Database Mirroring
Session Using Windows Authentication (SQL Server Management Studio).

In This Section:
How Transaction Safety and Witness State Affect the Operating Mode
Viewing the Safety Setting and State of the Witness
Factors Affecting Behavior on Loss of the Principal Server
How Transaction Safety and Witness State Affect the Operating Mode
The operating mode of a session is determined by the combination of its transaction safety setting and the
state of the witness. At any time, the database owner can change the transaction safety level, and can add or
remove the witness.
In This Section:
Transaction Safety
Witness State
Transaction Safety
Transaction safety is a mirroring-specific database property that determines whether a database mirroring
session operates synchronously or asynchronously. There are two safety levels: FULL and OFF.
SAFETY FULL
Full transaction safety causes the session to operate synchronously in high-safety mode. If a witness is
present, a session supports automatic failover.
When you establish a session using ALTER DATABASE statements, the session begins with the SAFETY
property set to FULL; that is, the session begins in high-safety mode. After the session begins, you can
add a witness.
For more information, see Synchronous Database Mirroring (High-Safety Mode), earlier in this topic.
SAFETY OFF
Turning off transaction safety causes the session to operate asynchronously, in high-performance mode.
If the SAFETY property is set to OFF, the WITNESS property should also be set to OFF (the default).
For information about the impact of the witness in high-performance mode, see The State of the
Witness, later in this topic. For more information about running with transaction safety turned off, see
Asynchronous Database Mirroring (High-Performance Mode), earlier in this topic.
The transaction safety setting of the database is recorded on each partner in the
sys.database_mirroring catalog view in the mirroring_safety_level and
mirroring_safety_level_desc columns. For more information, see sys.database_mirroring (Transact-
SQL ).
The database owner can change the transaction safety level at any time.
The State of the Witness
If a witness has been set, quorum is required, so the state of the witness is always significant.
If it exists, the witness has one of two states:
When the witness is connected to a partner, the witness is in the CONNECTED state relative to that
partner and has quorum with that partner. In this case, the database can be made available, even if one
of the partners is unavailable.
When the witness exists but is not connected to a partner, the witness is in the UNKOWN or
DISCONNECTED state relative to that partner. In this case, the witness lacks quorum with that partner,
and if the partners are not connected to each other, the database becomes unavailable.
For information about quorum, see Quorum: How a Witness Affects Database Availability (Database
Mirroring).
The state of each witness on a server instance is recorded in the sys.database_mirroring catalog view
in the mirroring_witness_state and mirroring_witness_state_desc columns. For more information,
see sys.database_mirroring (Transact-SQL ).
The following table summarizes how the operating mode of a session depends upon its transaction
safety setting and on state of the witness.

OPERATING MODE TRANSACTION SAFETY WITNESS STATE

High-performance mode OFF NULL (no witness)**

High-safety mode without automatic FULL NULL (no witness)


failover

High-safety mode with automatic FULL CONNECTED


failover*

*If the witness becomes disconnected, we recommend that you set WITNESS OFF until the witness server
instance becomes available.
**If a witness is present in high-performance mode, the witness does not participate in the session. However, to
make the database available, at least two of the server instances must remain connected. Therefore, we
recommend keeping the WITNESS property set to OFF in high-performance mode sessions. For more
information, see Quorum: How a Witness Affects Database Availability (Database Mirroring).
Viewing the Safety Setting and State of the Witness
To view the safety setting and the state of the witness for a database, use the sys.database_mirroring catalog
view. The relevant columns are as follows:

FACTOR COLUMNS DESCRIPTION

Transaction safety mirroring_safety_level or Transaction safety setting for updates


mirroring_safety_level_desc on the mirror database, one of:

UNKNOWN

OFF

FULL

NULL= database is not online.

Does a witness exist? mirroring_witness_name Server name of the database mirroring


witness or NULL, indicating that no
witness exists.
FACTOR COLUMNS DESCRIPTION

Witness state mirroring_witness_state or State of the witness in the database on


mirroring_witness_state_desc a given partner:

UNKNOWN

CONNECTED

DISCONNECTED

NULL = no witness exists or the


database is not online.

For example, on either the principal or mirror server, enter:

SELECT mirroring_safety_level_desc, mirroring_witness_name, mirroring_witness_state_desc FROM


sys.database_mirroring

For more information about this catalog view, see sys.database_mirroring (Transact-SQL ).
Factors Affecting Behavior on Loss of the Principal Server
The following table summarizes the combined effect of the transaction safety setting, the state of the database,
and the state of the witness on the behavior of a mirroring session on the loss of the principal server.

MIRRORING STATE OF BEHAVIOR WHEN PRINCIPAL


TRANSACTION SAFETY MIRROR DATABASE WITNESS STATE IS LOST

FULL SYNCHRONIZED CONNECTED Automatic failover occurs.

FULL SYNCHRONIZED DISCONNECTED Mirror server stops; failover


is not possible, and the
database cannot be made
available.

OFF SUSPENDED or NULL (no witness) Service can be forced to the


DISCONNECTED mirror server (with possible
data loss).

FULL SYNCHRONIZING or NULL (no witness) Service can be forced to the


SUSPENDED mirror server (with possible
data loss).

Related Tasks
Add or Replace a Database Mirroring Witness (SQL Server Management Studio)
Establish a Database Mirroring Session Using Windows Authentication (SQL Server Management
Studio)
Add a Database Mirroring Witness Using Windows Authentication (Transact-SQL )
Remove the Witness from a Database Mirroring Session (SQL Server)
Change Transaction Safety in a Database Mirroring Session (Transact-SQL )

See Also
Monitoring Database Mirroring (SQL Server)
Database Mirroring Witness
Change Transaction Safety in a Database Mirroring
Session (Transact-SQL)
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
Transaction safety is the attribute that controls the operating mode of the session. At any time, however, the
database owner can change the transaction safety. By default, the level of transaction safety is set to FULL
(synchronous operating mode).
Turning off transaction safety shifts the session into asynchronous operating mode, which maximizes
performance. If the principal becomes unavailable, the mirror stops but is available as a warm standby (failover
requires forcing service with possible data loss).
To turn on transaction safety
1. Connect to the principal server.
2. Issue the following Transact-SQL statement:

ALTER DATABASE <database> SET PARTNER SAFETY FULL

where <database> is the name of the mirrored database.


To turn off transaction safety
1. Connect to the principal server.
2. Issue the following statement:

ALTER DATABASE <database> SET PARTNER SAFETY OFF

where <database> is the mirrored database.

See Also
ALTER DATABASE Database Mirroring (Transact-SQL )
Database Mirroring Operating Modes
Database Mirroring Witness
6/12/2018 • 4 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
To support automatic failover, a database mirroring session must be configured in high-safety mode and also
possess a third server instance, known as the witness. The witness is an optional instance of SQL Server that
enables the mirror server in a high-safety mode session to recognize whether to initiate an automatic failover.
Unlike the two partners, the witness does not serve the database. Supporting automatic failover is the only role
of the witness.

NOTE
In high-performance mode, the witness can adversely affect availability. If a witness is configured for a database mirroring
session, the principal server must be connected at least to one of the other server instances, the mirror server or the
witness, or both of them. Otherwise, the database becomes unavailable and forcing service (with possible data loss) is
impossible. Therefore, for high-performance mode, we strongly recommend that you always keep the witness set to OFF.
For information about the impact of a witness on high-performance mode, see Database Mirroring Operating Modes.

The following illustration shows a high-safety mode session with a witness.

In This Topic:
Using a Witness in Multiple Sessions
Software and Hardware Recommendations
Role of the Witness in Automatic Failover
To Add or Remove a Witness

Using a Witness in Multiple Sessions


A specific server instance can act as a witness in concurrent database mirroring sessions, each for a different
database. Different sessions can be with different partners. The following illustration shows a server instance
that is a witness in two database mirroring sessions with different partners.

A single-server instance can also function at the same time as a witness in some sessions and a partner in other
sessions. However, in practice, a server instance typically functions as either a witness or a partner. This is
because the partners require sophisticated computers that have enough hardware to support a production
database, whereas the witness can run on any available Windows system that supports SQL Server 2017.

Software and Hardware Recommendations


We strongly recommend that the witness reside on a separate computer from the partners. Database mirroring
partners are supported only by SQL Server Standard edition and by SQL Server Enterprise edition. Witnesses,
in contrast, are also supported by SQL Server Workgroup and by SQL Server Express. Except during an
upgrade from an earlier version of SQL Server, the server instances in a mirroring session must all be running
the same version of SQL Server. For example, a SQL Server 2008 witness is supported when you are upgrading
from a SQL Server 2008 mirroring configuration but cannot be added to an existing or new SQL Server 2008
R2 or later mirroring configuration.
A witness can run on any reliable computer system that supports any of these editions of SQL Server. However,
we recommend that every server instance that is used as a witness correspond to the minimum configuration
that is required for the SQL Server Standard version that you are running. For more information about these
requirements, see Hardware and Software Requirements for Installing SQL Server 2016.

Role of the Witness in Automatic Failover


Throughout a database mirroring session, all the server instances monitor their connection status. If the partners
become disconnected from each other, they rely on the witness to make sure that only one of them is currently
serving the database. If a synchronized mirror server loses its connection to the principal server but remains
connected to the witness, the mirror server contacts the witness to determine whether the witness has lost its
connection to the principal server:
If the principal server is still connected to the witness, automatic failover does not occur. Instead, the
principal server continues to server the database while accumulating log records to send the mirror
server when the partners reconnect.
If the witness is also disconnected from the principal server, the mirror server knows that principal
database has become unavailable. In this case, the mirror server immediately initiates an automatic
failover.
If the mirror server is disconnected from the witness and also from the principal server, automatic failover
is not possible, regardless of the state of the principal server.
The requirement that at least two of the server instances be connected is known as quorum. Quorum
makes sure that the database can only be served by one partner at a time. For information about how
quorum works and its impact on a session, see Quorum: How a Witness Affects Database Availability
(Database Mirroring).
To Add or Remove a Witness
To add a witness
Add or Replace a Database Mirroring Witness (SQL Server Management Studio)
Add a Database Mirroring Witness Using Windows Authentication (Transact-SQL )
To remove the witness
Remove the Witness from a Database Mirroring Session (SQL Server)

See Also
Role Switching During a Database Mirroring Session (SQL Server)
Database Mirroring Operating Modes
Quorum: How a Witness Affects Database Availability (Database Mirroring)
Possible Failures During Database Mirroring
Mirroring States (SQL Server)
Quorum: How a Witness Affects Database
Availability (Database Mirroring)
6/12/2018 • 5 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
Whenever a witness is set for a database mirroring session, quorum is required. Quorum is a relationship that
exists when two or more server instances in a database mirroring session are connected to each other. Typically,
quorum involves three interconnected server instances. When a witness is set, quorum is required to make the
database available. Designed for high-safety mode with automatic failover, quorum makes sure that a database
is owned by only one partner at a time.
If a particular server instance becomes disconnected from a mirroring session, that instance loses quorum. If no
server instances are connected, the session loses quorum and the database becomes unavailable. Three types of
quorum are possible:
A full quorum includes both partners and the witness.
A witness-to -partner quorum consists of the witness and either partner.
A partner-to -partner quorum consists of the two partners.
The following figure shows these types of quorum.

As long as the current principal server has quorum, this server owns the role of principal and continues to
serve the database, unless the database owner performs a manual failover. If the principal server loses
quorum, it stops serving the database. Automatic failover can occur only if the principal database has lost
quorum, which guarantees that it is no longer serving the database.
A disconnected server instance saves its most recent role in the session. Typically, a disconnected server
instance reconnects to the session when it restarts and regains quorum.
IMPORTANT
The witness should be set only when you intend to use high-safety mode with automatic failover. In high-performance
mode, for which a witness is never required, we strongly recommend setting the WITNESS property to OFF. For
information about the impact of a witness on high-performance mode, see Database Mirroring Operating Modes.

Quorum in High-Safety Mode Sessions


In high-safety mode, quorum allows automatic failover by providing a context in which the server instances with
quorum arbitrate which partner owns the role of principal. The principal server serves the database if it has
quorum. If the principal server loses quorum when the synchronized mirror server and witness retain quorum,
automatic failover occurs.
The quorum scenarios for high-safety mode are as follows:
A full quorum that consists of both partners and the witness.
Ordinarily, all three server instances participate in a three-way quorum, called a full quorum. With a full
quorum, the principal and mirror servers continue to perform their respective roles (unless manual
failover occurs).
A witness-to -partner quorum that consists of the witness and either partner.
If the network connection between the partners is lost because one of the partners has been lost, the
following cases are possible:
The mirror server is lost, and the principal server and witness retain quorum.
In this case, the principal sets its database to DISCONNECTED and runs with mirroring in a
SUSPENDED state. (This is referred to as running exposed, because the database is currently not
being mirrored.) When the mirror server rejoins the session, the server regains quorum as mirror
and starts resynchronizing its copy of the database.
The principal server is lost, and the witness and the mirror server retain quorum.
In this case, automatic failover occurs. For more information, see Database Mirroring Operating
Modes.
All the server instances lose quorum, but subsequently the mirror and witness reconnect. The
database will not be served in this case.
Rarely, the network connection between failover partners is lost while both partners remain
connected to the witness. In this event, two, separate witness-to–partner quorums exist, with the
witness as a liaison. The witness informs the mirror server that the principal server is still
connected. Therefore, automatic failover does not occur. Instead, the mirror server retains the
mirror role and waits to reconnect to the principal. If the redo queue contains log records at this
point, the mirror server continues to roll forward the mirror database. On reconnecting, the mirror
server will resynchronize the mirror database.
A partner-to -partner quorum that consists of the two partners.
As long as the partners retain quorum, the database continues in a SYNCHRONIZED state, and manual
failover remains possible. Without the witness, automatic failover is not possible; but when the witness
regains quorum, the session resumes regular operation, and automatic failover is supported again.
The session loses quorum.
If all the server instances become disconnected from each other, the session is said to have lost quorum.
As server instances reconnect to each other, they regain quorum with each other.
If the principal server reconnects with either of the other server instances, the database becomes
available.
If the principal server remains disconnected, but the mirror and witness reconnect to each other,
automatic failover cannot occur because data loss might occur. Therefore, the database remains
unavailable, until the principal server rejoins the session.
When all three server instances have reconnected, full quorum is regained, and the session
resumes its regular operation.

IMPORTANT
When a session has a partner-to-partner quorum, if either partner loses quorum, the session loses quorum. Therefore, if
you expect the witness to remain disconnected for lots of time, we recommend that you temporarily remove the witness
from the session. Removing the witness removes the requirement for quorum. Then, if the mirror server becomes
disconnected, the principal server can continue to serve the database. For information about how to add or remove a
witness, see Database Mirroring Witness.

How Quorum Affects Database Availability


The following illustration shows how the witness and the partners cooperate to make sure that, at given time,
only one partner owns the role of principal and only the current principal server can bring its database online.
Both scenarios start with full quorum, and Partner_A in the principal role and Partner_B in the mirror role.
Scenario 1 shows how after the original principal server (Partner_A ) fails, the witness and mirror agree that the
principal, Partner_A, is not available any longer and form quorum. The mirror, Partner_B then assumes the
principal role. Automatic failover occurs, and Partner_B, brings its copy of the database online. Then Partner_B
goes down, and the database goes offline. Later, the former principal server, Partner_A, reconnects to the
witness regaining quorum, but on communicating with the witness, Partner_A learns that it cannot bring its
copy of the database online, because Partner_B now owns the principal role. When Partner_B rejoins the
session, it brings the database back online.
In Scenario 2, the witness loses quorum, while the partners, Partner_A and Partner_B, retain quorum with each
other, and the database remains online. Then the partners lose their quorum, too, and the database goes offline.
Later, the principal server, Partner_A, reconnects to the witness regaining quorum. The witness confirms that
Partner_A still owns the principal role, and Partner_A brings the database back online.

See Also
Database Mirroring Operating Modes
Role Switching During a Database Mirroring Session (SQL Server)
Database Mirroring Witness
Possible Failures During Database Mirroring
Mirroring States (SQL Server)
Add a Database Mirroring Witness Using Windows
Authentication (Transact-SQL)
6/12/2018 • 4 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
To set up a witness for a database, the database owner assigns a Database Engine instance to the role of witness
server. The witness server instance can run on the same computer as the principal or mirror server instance, but
this substantially reduces the robustness of automatic failover.
We strongly recommend that the witness reside on a separate computer. A given server can participate in
multiple concurrent database mirroring sessions with the same or different partners. A given server can be a
partner in some sessions and a witness in other sessions.
The witness is intended exclusively for high-safety mode with automatic failover. Before you set a witness, we
strongly recommend that you ensure that the SAFETY property is currently set to FULL.

IMPORTANT
We recommend that you configure database mirroring during off-peak hours because configuration can impact
performance.

To establish a witness
1. On the witness server instance, ensure that an endpoint exists for database mirroring. Regardless of the
number of mirroring session to be supported, the server instance must have only one database mirroring
endpoint. If you intend to use this server instance exclusively as a witness in database mirroring sessions,
assign the role of witness to the endpoint (ROLE=WITNESS ). If you intend to use this server instance as a
partner in one or more other database mirroring sessions, assign the role of the endpoint as ALL.
To execute a SET WITNESS statement, the database mirroring session must already be started (between
the partners), and the STATE of the endpoint of the witness must be set to STARTED.
To learn whether the witness server instance has its database mirroring endpoint and to learn its role and
state, on that instance, use the following Transact-SQL statement:

SELECT role_desc, state_desc FROM sys.database_mirroring_endpoints

IMPORTANT
If a database mirroring endpoint exists and is already in use, we recommend that you use that endpoint for every
session on the server instance. Dropping an in-use endpoint disrupts the connections of the existing sessions. If a
witness has been set for a session, dropping the database mirroring endpoint can cause the principal server of that
session to lose quorum; if that occurs, the database is taken offline and its users are disconnected. For more
information, see Quorum: How a Witness Affects Database Availability (Database Mirroring).

If the witness lacks an endpoint, see Create a Database Mirroring Endpoint for Windows Authentication
(Transact-SQL ).
2. If the partner instances are running under different domain user accounts, create a login for the different
accounts in the master database of each instance. For more information, see Allow Network Access to a
Database Mirroring Endpoint Using Windows Authentication (SQL Server).
3. Connect to the principal server and issue the following statement:
ALTER DATABASE <database_name> SET WITNESS =<server_network_address>
where <database_name> is the name of the database to be mirrored (this name is the same on both
partners), and <server_network_address> is the server network address of the witness server instance.
The syntax for a server network address is as follows:
TCP://<system -address>:<port>
where <system -address> is a string that unambiguously identifies the destination computer system, and
<port> is the port number used by the mirroring endpoint of the partner server instance. For more
information, see Specify a Server Network Address (Database Mirroring).
For example, on the principal server instance, the following ALTER DATABASE statement sets the witness.
The database name is AdventureWorks, the system address is DBSERVER3—the name of the witness
system, and the port used by the database mirroring endpoint of the witness is 7022 :

ALTER DATABASE AdventureWorks


SET WITNESS = 'TCP://DBSERVER3:7022'

Example
The following example establishes a data mirroring witness. On the witness server instance (default instance on
WITNESSHOST4 ):

1. Create an endpoint for this server instance for the WITNESS role only using port 7022 .

CREATE ENDPOINT Endpoint_Mirroring


STATE=STARTED
AS TCP (LISTENER_PORT=7022)
FOR DATABASE_MIRRORING (ROLE=WITNESS)
GO

2. Create a login for domain user account of partner instances, if different; for example, assume that the
witness is running as SOMEDOMAIN\witnessuser , but the partners are running as MYDOMAIN\dbousername .
Create a login for the partners, as follows:

--Create a login for the partner server instances,


--which are both running as MYDOMAIN\dbousername:
USE master ;
GO
CREATE LOGIN [MYDOMAIN\dbousername] FROM WINDOWS ;
GO
--Grant connect permissions on endpoint to login account
--of partners
GRANT CONNECT ON ENDPOINT::Endpoint_Mirroring TO [MYDOMAIN\dbousername];
GO

3. On each of the partner server instances, create a login for the witness server instance:
--Create a login for the witness server instance,
--which is running as SOMEDOMAIN\witnessuser:
USE master ;
GO
CREATE LOGIN [SOMEDOMAIN\witnessuser] FROM WINDOWS ;
GO
--Grant connect permissions on endpoint to login account
--of partners
GRANT CONNECT ON ENDPOINT::Endpoint_Mirroring TO [SOMEDOMAIN\witnessuser];
GO

4. On the principal server, set the witness (which is on WITNESSHOST4 ):

ALTER DATABASE AdventureWorks


SET WITNESS =
'TCP://WITNESSHOST4:7022'
GO

NOTE
The server network address indicates the target server instance by the port number, which maps to the mirroring endpoint
of the instance.

For a complete example showing security setup, preparing the mirror database, setting up the partners, and
adding a witness, see Setting Up Database Mirroring (SQL Server).

See Also
ALTER DATABASE (Transact-SQL )
Allow Network Access to a Database Mirroring Endpoint Using Windows Authentication (SQL Server)
Create a Database Mirroring Endpoint for Windows Authentication (Transact-SQL )
Establish a Database Mirroring Session Using Windows Authentication (Transact-SQL )
Remove the Witness from a Database Mirroring Session (SQL Server)
Database Mirroring Witness
Add or Replace a Database Mirroring Witness (SQL
Server Management Studio)
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
If the database mirroring endpoints use Windows Authentication,, you can use SQL Server Management Studio
to add or replace a witness. Adding a witness in Management Studio also changes the operating mode to high-
safety mode with automatic failover.

NOTE
We strongly recommend that the witness reside on a separate computer from either of the partners. The service account
used by the witness must be in the same domain as the service accounts used by the principal and mirror server instances,
or it must be in a trusted domain.

To Add or Replace a Witness


1. After connecting to the principal server instance, in Object Explorer, click the server name to expand the
server tree.
2. Expand Databases, and select the principal database of the session to which you are adding or replacing a
witness.
3. Right-click the database, select Tasks, and then click Mirror. This opens the Mirroring page of the
Database Properties dialog box.
4. Click Configure Security.
5. If the Configure Database Mirroring Security Wizard welcome screen appears, click Next.
6. In the Include Witness Server dialog box, click Yes, and then click Next.
7. In the Choose Servers to Configure dialog box, the Witness server instance check box is automatically
checked. Click Next.
8. On the Principal Server Instance dialog box, keep the existing port and endpoint. Click Next.
9. On the Witness Server Instance dialog box, click Connect.
10. In the Connect to Server dialog box, specify the witness server instance in the Server name field, and
use Windows Authentication (the default). Click Connect.
11. Once a connection is established, the listener port and database mirroring endpoint of the witness server
instance are displayed on the Witness Server Instance dialog box. Click Next.
12. The Service Accounts dialog box contains fields for the domain service accounts of the principal, mirror,
and witness server instances.
If the server instances all use the same service account, leave the fields blank.
If the witness server instance uses a different service account from either of the partners, fill in the
Principal, Mirror, and Witness fields with the account name:
DOMAINNAME \ username
The domain name must be in upper case.
Click Next.
13. On the Complete the Wizard summary screen, optionally, verify the witness configuration, and then click
Finish.
14. On finishing, the wizard returns you to the Database Properties dialog box where the server network
address of the witness now appears in Witness field. Also, High-safety mode with automatic failover
(synchronous), which is required with a witness, is automatically selected.
To enable the witness and change the session to high-safety mode with automatic failover, Click OK.

See Also
Database Mirroring Witness
Database Mirroring (SQL Server)
Database Properties (Mirroring Page)
Establish a Database Mirroring Session Using Windows Authentication (SQL Server Management Studio)
Database Mirroring Witness
Remove the Witness from a Database Mirroring
Session (SQL Server)
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
This topic describes how to remove a witness from a database mirroring session in SQL Server 2017 by using
SQL Server Management Studio or Transact-SQL. At any time during a database mirroring session, the database
owner can turn off the witness for a database mirroring session.
In This Topic
Before you begin:
Security
To Replace remove the witness, using:
SQL Server Management Studio
Transact-SQL
Follow Up: After Removing the Witness

Before You Begin


Security
Permissions
Requires ALTER permission on the database.

Using SQL Server Management Studio


To remove the witness
1. Connect to the principal server instance and, in the Object Explorer pane, click the server name to
expand the server tree.
2. Expand Databases, and select the database whose witness you want to remove.
3. Right-click the database, select Tasks, and then click Mirror. This opens the Mirroring page of the
Database Properties dialog box.
4. To remove the witness, delete its server network address from the Witness field.

NOTE
If you switch from high-safety mode with automatic failover to high-performance mode, the Witness field is
automatically cleared.

Using Transact-SQL
To remove the witness
1. Connect to the Database Engine on either partner server instance.
2. From the Standard bar, click New Query.
3. Issue the following statement:
ALTER DATABASE database_name SET WITNESS OFF
where database_name is the name of the mirrored database.
The following example removes the witness from the AdventureWorks2012 database.

ALTER DATABASE AdventureWorks2012 SET WITNESS OFF ;

Follow Up: After Removing the Witness


Turning off the witness changes the operating modein accordance with the transaction-safety setting:
If transaction safety is set to FULL (the default), the session uses high-safety, synchronous mode without
automatic failover.
If transaction safety is set to OFF, the session operates asynchronously (in high-performance mode)
without requiring quorum. Whenever transaction safety is turned off, we strongly recommend also turning
the witness off.

TIP
The transaction safety setting of the database is recorded on each partner in the sys.database_mirroring catalog view in the
mirroring_safety_level and mirroring_safety_level_desc columns.

Related Tasks
Add a Database Mirroring Witness Using Windows Authentication (Transact-SQL )
Add or Replace a Database Mirroring Witness (SQL Server Management Studio)

See Also
ALTER DATABASE Database Mirroring (Transact-SQL )
Change Transaction Safety in a Database Mirroring Session (Transact-SQL )
Add a Database Mirroring Witness Using Windows Authentication (Transact-SQL )
Database Mirroring Witness
Role Switching During a Database Mirroring
Session (SQL Server)
6/12/2018 • 18 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
Within the context of a database mirroring session, the principal and mirror roles are typically interchangeable
in a process known as role switching. In role switching, the mirror server acts as the failover partner for the
principal server, taking over the principal role, recovering its copy of the database and bringing it online as the
new principal database. The former principal server, when available, assumes the mirror role, and its database
becomes the new mirror database. Potentially, the roles can switch back and forth either in response to multiple
failures or for administrative purposes.

NOTE
This topic assumes that you are familiar with the database mirroring operating modes. For more information, see
Database Mirroring Operating Modes.

The following illustration shows mirroring partners, Partner_A and Partner_B, switching the principal and
mirror roles over a series of automatic or manual failovers.

IMPORTANT
After a role switch, jobs that ran on the former principal database must be recreated on the new principal server to run
there. For more information, see Management of Logins and Jobs After Role Switching (SQL Server).

Three types of role switching exist: automatic failover, manual failover, and forced service (with possible data
loss). Support for each form depends on the operating mode of the session.
NOTE
If you are unfamiliar with these operating modes, see Database Mirroring Operating Modes.

Manual failover
High-safety mode supports manual failover. Whenever the database is synchronized, the database owner
can initiate a manual failover.
Manual failover is provided for administrative purposes. For more information, see Manual Failover,
later in this topic.
Automatic failover
In the presence of a witness, high-safety mode supports automatic failover. Automatic failover occurs
only on the loss of the principal server when the witness and mirror server are still connected to each
other and the database is already synchronized. For more information, see Automatic Failover, later in
this topic.
Forced service (with possible data loss)
Forcing service is supported in high-safety mode when no witness is set and in high-performance mode.
On the loss of the principal server, the database owner can make the database available by forcing
service to the mirror server (with possible data loss).

NOTE
We recommend that the WITNESS property be set to OFF in high-performance mode. Otherwise, to bring the
database online, the mirror server must connected to the witness.

For more information, see Forced Service (with Possible Data Loss), later in this topic.
The following table summarizes which forms of failover are supported under each of the operating
modes.

HIGH-SAFETY MODE HIGH-SAFETY MODE WITH A


HIGH PERFORMANCE WITHOUT A WITNESS WITNESS

Automatic failover No No Yes

Manual failover No Yes Yes

Forced service Yes Yes No

After a role switch, certain metadata must exist on both partners to ensure that all of the database users can
access the new principal database. In addition, backup jobs must be created on the new principal server, to
ensure that the database continues to be backed up on its regular schedule. For more information, see
Management of Logins and Jobs After Role Switching (SQL Server).
During a role switch, the amount of time that database mirroring will be out of service depends on the type of
role switching and on the cause. For more information, see Estimate the Interruption of Service During Role
Switching (Database Mirroring).

Manual Failover
Manual failover disconnects the clients from the database and reverses the roles of the partners. Only high-
safety mode supports manual failover.
In This Section:
Maintaining Availability During Upgrades
Conditions Required for a Manual Failover
How Manual Failover Works
Maintaining Availability During Upgrades
The database administrator can use manual failover for upgrading hardware or software without sacrificing
availability. To use database mirroring for software upgrades, the mirror server and/or system must have
already received the upgrades.

NOTE
Database mirroring should be able to do a rolling upgrade, but this is not guaranteed, because future changes are
unknown. For more information, see Upgrading Mirrored Instances.

The following figure illustrates an instance of using manual failover to maintain database availability while you
upgrade a database server instance. When the upgrade is completed, an administrator may optionally fail over
back to the original server instance. This is useful when the administrator wants to stop the mirroring session
and use the mirror server elsewhere. In this way, a single server instance can be used repeatedly when updating
a series of database server instances.

Conditions Required for a Manual Failover


Manual failover requires transaction safety to be set to FULL (that is, high-safety mode). When the partners are
connected and the database is already synchronized, manual failover is supported.
How Manual Failover Works
Manual failover initiates the following sequence of actions:
1. The principal server disconnects clients from the principal database, sends the tail of the log to the mirror
server, and, in preparation for switching to the mirror role, sets the mirroring state to
SYNCHRONIZING.
2. The mirror server records the log sequence number (LSN ) of the last log record received from the
principal as the failover LSN.

NOTE
To view this LSN, select the mirroring_failover_lsn column from sys.database_mirroring (Transact-SQL).

3. If any log is waiting in the redo queue, the mirror server finishes rolling forward the mirror database.
The amount of time required depends on the speed of the system, the recent workload, and the amount
of log in the redo queue. For a synchronous operating mode, the failover time can be regulated by
limiting the size of the redo queue. However, this can cause the principal server to slow down to allow
the mirror server to keep up.

NOTE
To learn the current size of the redo queue, use the Redo Queue performance counter in the database mirroring
performance object (for more information, see Monitoring Database Mirroring (SQL Server)).

4. The mirror server becomes the new principal server, and the former principal server becomes the new
mirror server.
5. The new principal server rolls back any uncommitted transactions and brings its copy of the database
online as the principal database.
6. The former principal takes on the mirror role, and the former principal database becomes the mirror
database. The new mirror server quickly resynchronizes the new mirror database with the new principal
database.

NOTE
As soon as the new mirror server has resynchronized the databases, failover is again possible, but in the reverse
direction.

After failover, clients must reconnect to the current principal database. For more information, see
Connect Clients to a Database Mirroring Session (SQL Server).
To initiate manual failover
Manually Fail Over a Database Mirroring Session (SQL Server Management Studio)
Manually Fail Over a Database Mirroring Session (Transact-SQL ).

Automatic Failover
Automatic failover is supported only in database mirroring sessions running with a witness in high-safety mode
(high-safety mode with automatic failover). In high-safety mode with automatic failover, once the database is
synchronized, if the principal database becomes unavailable, an automatic failover occurs. An automatic failover
causes the mirror server to take over the role of principal server and bring its copy of the database online as the
principal database. Requiring that the database be synchronized prevents data loss during failover, because
every transaction committed on the principal database is also committed on the mirror database.
IMPORTANT
For automatic failover to improve reliability, the mirror and principal databases must reside on different computers.

In This Section:
Conditions Required for an Automatic Failover
How Automatic Failover Works
To Disable Automatic Failover (SQL Server Management Studio)
To Disable Automatic Failover (Using Transact-SQL )
Conditions Required for an Automatic Failover
Automatic failover requires the following conditions:
The database mirroring session must be running in high-safety mode and must possess a witness. For
more information, see Database Mirroring Operating Modes.
The mirror database must already be synchronized. This guarantees that all of the log sent to the mirror
server has been written to disk.
The principal server has lost communication with the rest of the database mirroring configuration, while
the mirror and witness retain quorum. If all server instances lose communication, however, and the
witness and the mirror server later regain communication, automatic failover does not occur.

NOTE
For more information, see Quorum: How a Witness Affects Database Availability (Database Mirroring).

The mirror server has detected the loss of the principal server.
How the mirror server detects a failure of the principal server depends on whether it is a hard or soft
failure. For more information, see Possible Failures During Database Mirroring.
How Automatic Failover Works
Under the preceding conditions, automatic failover initiates the following sequence of actions:
1. If the principal server is still running, it changes the state of the principal database to DISCONNECTED
and disconnects all clients from the principal database.
2. The witness and mirror servers register that the principal server is unavailable.
3. If any log is waiting in the redo queue, the mirror server finishes rolling forward the mirror database.

NOTE
The amount of time required to apply the log depends on the speed of the system, the recent work load, and the
amount of log in the redo queue.

4. The former mirror database moves online as the new principal database, and recovery cleans up all
uncommitted transactions by rolling them back as quickly as possible. Locks isolate those transactions.
5. When the former principal server rejoins the session, it recognizes that its failover partner now owns the
principal role. The former principal server takes on the role of mirror, making its database the mirror
database. The new mirror server synchronizes the new mirror database with the principal database as
quickly as possible. As soon as the new mirror server has resynchronized the databases, failover is again
possible, but in the reverse direction.
The following illustration shows a single instance of automatic failover.

Initially, all three servers are connected (the session has full quorum). Partner_A is the principal server
and Partner_B is the mirror server. Partner_A (or the principal database on Partner_A ) becomes
unavailable. The witness and Partner_B both recognize that the principal is no longer available the
session retains quorum. Partner_B becomes the principal server and makes its copy of the database
available as the new principal database. Eventually, Partner_A reconnects to the session and discovers
that Partner_B now owns the principal role. Partner_A then takes on the mirror role.
After failover, clients must reconnect to the current principal database. For more information, see
Connect Clients to a Database Mirroring Session (SQL Server).

NOTE
Transactions that have been prepared using the Microsoft Distributed Transaction Coordinator but are still not committed
when a failover occurs, are considered aborted after the database has failed over.

To Disable Automatic Failover (SQL Server Management Studio )


Open the Database PropertiesMirroring page, and change the operating mode by selecting one of the
following options:
High safety without automatic failover (synchronous)
In this mode, the database continues to be synchronized, and manual failover remains possible.
High performance (asynchronous)
In this mode, the mirror database might lag somewhat behind the principal database, and manual
failover is no longer possible.
To Disable Automatic Failover (Using Transact-SQL )
At any point in a database mirroring session, the database owner can disable automatic failover by turning off
the witness.
To turn off the witness
Remove the Witness from a Database Mirroring Session (SQL Server)

NOTE
Turning off the witness while retaining full transaction safety puts the session into high-safety mode without
automatic failover.

Forced Service (with Possible Data Loss)


Database mirroring provides forcing service (with possible data loss) as a disaster recovery method to allow
you to use a mirror server as a warm standby server. Forcing service is possible only if the principal server is
disconnected from the mirror server in a mirroring session. Because forcing service risks possible data loss, it
should be used cautiously and sparingly.
Support for forced service depends on the operating mode and the state of the session, as follows:
Typically, high-performance mode supports forcing service whenever the principal server is
disconnected. However, though unnecessary, a witness can exist for a high-performance mode session. In
this case, forcing service requires that the mirror server and witness are connected to each other.
High-safety mode without automatic failover supports forcing service whenever the principal server is
disconnected.
High-safety mode with automatic failover supports forcing service whenever the mirror server and
witness are connected to each other and neither is connected to the principal server (as long as the
mirror server was not in the process of rolling back the mirror database when it was last connected to
the principal).
We recommend forcing service only if you must restore service to the database immediately and are
willing to risk losing data. The effect of forcing service is similar to removing mirroring, except that
forcing service facilitates resynchronizing the databases when mirroring is resumed, at the risk of
possible data loss. Forcing service initiates a smooth transition of the principal role to the mirror
database. The mirror server assumes the role of principal server and immediately serves its copy of the
database to clients. The new principal database runs without a mirror (that is, it runs exposed).

IMPORTANT
If the principal server was merely disconnected from the database mirroring session and is still running, some clients
might continue to access the original principal database. Before you force service, it is important to prevent clients from
accessing the original principal server. Otherwise, after service is forced, the original principal database and the current
principal database could be updated independently of the other.

In This Section:
Typical Case of Forced Service
Risks of Forcing Service
Managing the Potential Data Loss
Related Tasks For Managing a Forced Failover
Typical Case of Forced Service
The following figure illustrates a typical case of forced service (with possible data loss).

In the figure, the original principal server, Partner_A, becomes unavailable to the mirror server, Partner_B,
causing the mirror database to be disconnected. After ensuring that Partner_A is not available to clients, the
database administrator forces service, with possible data loss, on Partner_B. Partner_B becomes the principal
server and runs with the database exposed (that is, unmirrored). At this point, clients can reconnect to
Partner_B.
When Partner_A becomes available, it reconnects to the new principal server, rejoining the session and
assuming the mirror role. The mirroring session is suspended immediately, without having synchronized the
new mirror database. Suspending the session allows the database administrator to decide whether to resume
the session or, in extreme cases, remove mirroring and attempt to salvage data from the former principal
database. In this case, the database administrator chooses to resume mirroring. At that point, Partner_A takes
over the role of mirror server and rolls back the former principal database to the point in time of the last
successfully synchronized transaction; if any committed transactions were not written to disk on the mirror
server before service was forced, they are lost. Partner_A then rolls forward the new mirror database by
applying any changes made on the new principal database since the former mirror server became the new
principal server.

NOTE
Although high-performance mode does not require a witness, if one is configured, forcing service is possible only if the
witness is currently connected to the mirror server.

Risks of Forcing Service


It is essential to understand that forcing service can cause data loss. Data loss is possible because the mirror
server cannot communicate with the principal server and, therefore, cannot guarantee that the two databases
are synchronized. Forcing service starts a new recovery fork. Because the original principal database and mirror
database are on different recovery forks, each database now contains data that the other database does not: the
original principal database contains whatever changes were not yet sent from its send queue to the former
mirror database (the unsent log); the former mirror database contains whatever changes occur after service was
forced.
If service is forced because the principal server has failed, potential data loss is depends on whether any
transaction logs were not sent to the mirror server before the failure. Under high-safety mode, this is possible
only until the mirror database becomes synchronized. Under the high-performance mode, accumulated unsent
log is always a possibility.
The implications of forcing service depend partly on whether the session has a witness:
In the absence of a witness, service can be forced if the partners become disconnected, for example,
because their network connection is broken. If the original principal server is still running, both partners
own the principal role. Clients connecting to the new principal server will access the current version of
the database, while clients connecting to the original principal server will access the original principal
database. This situation increases the potential for data loss. If the partners are allowed to reconnect, the
original principal server assumes the mirror role and changes the status of its database to "recovering,"
before mirroring is suspended. If the session is resumed, transactions on the original principal database
whose log was in the send queue as of the most recent disconnection are lost. In addition, any the
transactions that occurred after service was forced are also lost.
In the presence of a witness, if the mirror server is disconnected from both the principal server and the
witness, as long as the latter two remain connected to each other, the principal runs exposed. If the
principal server then becomes disconnected from the witness, it stops serving the database. Thereafter, if
the mirror server reconnects to the witness, forcing service becomes possible. If service is forced, all the
changes made while the original principal server was running exposed will be lost if the original principal
server reconnects.
For more information, see Managing the Potential Data Loss, later in this topic.
Managing the Potential Data Loss
After service is forced, once the former principal server is available, assuming that its database is undamaged,
you can attempt to manage the potential data loss. The available approach for managing potential data loss
depends on whether the original principal server has reconnected to its partner and rejoined the mirroring
session. Assuming that the original principal server can access the new principal instance, reconnecting occurs
automatically and transparently.
The Original Principal Server Has Reconnected
Typically, after a failure, when the original principal server restarts it quickly reconnects to its partner. On
reconnecting, the original principal server becomes the mirror server. Its database becomes the mirror database
and enters the recovering state before the session is suspended. The mirror database will not be not rolled back
unless you resume mirroring.
However, the recovering database is inaccessible; therefore, you cannot inspect it to evaluate what data would
be lost if you were to resume mirroring. Therefore, the decision on whether to resume or remove mirroring
depends on whether you are willing to accept any data loss at all.
If losing any data would be unacceptable, you should remove mirroring to salvage them.
Removing mirroring would allow the database administrator to recover the original principal database
and attempt to recover the data that would have been lost. However, when the former mirror database
comes online, the former partners will be serving divergent databases with the same name. The
database administrator needs to make one of the databases inaccessible to clients to avoid further
divergence of the database and to prevent client-failover issues.
If losing any data would be acceptable, you can resume mirroring.
Resuming mirroring causes the new mirror database to be rolled back as the first step in synchronizing
the database. If any log records were waiting in the send queue at the time of failure, the corresponding
transactions are lost, even if they were committed.
The Original Principal Server Has Not Reconnected
If you can temporarily prevent the original principal server from reconnecting over the network to the new
principal server, you can inspect the original principal database to evaluate what data would be lost if mirroring
were resumed.
If the potential data loss is acceptable
Allow the original principal server to reconnect to its partner. Reconnecting causes mirroring to be
suspended. To proceed with mirroring, simply resume the session. The former principal server assumes
the mirror role. The new mirror server drops the original recovery fork, losing any transactions that were
never sent to or received by the former mirror server.
If the data loss is unacceptable
If the original principal database contains critical data that would be lost if you resumed the session, you
can preserve the data on the original principal server by removing mirroring. We recommend that you
attempt to back up the tail of the principal's log at this point. Then, you can update the current principal
(the former mirror database) by exporting the data you want to salvage from the original principal
database and importing it into the current principal database. We recommend taking a full database
backup of the updated database as quickly as possible.
To re-establish mirroring with the updated database as the initial principal database, use this backup (and
least one subsequent log backup) to create a new mirror database. Every log backup taken after
mirroring was removed must be applied. Therefore, we recommend delaying additional log backups of
the principal database until the new mirroring session starts.
Related Tasks For Managing a Forced Failover
To force service
Force Service in a Database Mirroring Session (Transact-SQL ).
To resume database mirroring
Pause or Resume a Database Mirroring Session (SQL Server)
To create a new mirror database
Prepare a Mirror Database for Mirroring (SQL Server)
To start up database mirroring
Setting Up Database Mirroring (SQL Server)
Establish a Database Mirroring Session Using Windows Authentication (SQL Server Management
Studio)

See Also
Estimate the Interruption of Service During Role Switching (Database Mirroring)
Possible Failures During Database Mirroring
Connect Clients to a Database Mirroring Session (SQL Server)
Database Mirroring Witness
Complete Database Restores (Full Recovery Model)
Database Mirroring Operating Modes
Mirroring States (SQL Server)
Manually Fail Over a Database Mirroring Session
(Transact-SQL)
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
When the mirrored database is synchronized (that is, when the database is in the SYNCHRONIZED state), the
database owner can initiate manual failover to the mirror server. Manual failover can be initiated only from the
principal server.
To manually fail over a database mirroring session
1. Connect to the principal server.
2. Set the database context to the master database:
USE master;
3. Issue the following statement on the principal server:
ALTER DATABASE database_name SET PARTNER FAILOVER, where database_name is the mirrored
database.
This initiates an immediate transition of the mirror server to the principal role.
On the former principal, clients are disconnected from the database and in-flight transactions are rolled
back.

NOTE
Transactions that have been prepared by using the Microsoft Distributed Transaction Coordinator but are still not committed
when a failover occurs are considered aborted after the database has failed over.

See Also
ALTER DATABASE Database Mirroring (Transact-SQL )
Manually Fail Over a Database Mirroring Session (SQL Server Management Studio)
Role Switching During a Database Mirroring Session (SQL Server)
Manually Fail Over a Database Mirroring Session
(SQL Server Management Studio)
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
When the mirrored database is synchronized (that is, when the database is in the SYNCHRONIZED state), the
database owner can initiate manual failover to the mirror server.
During a manual failover, the principal and mirror server roles are swapped for the database on which the failover
occurs. The mirror database becomes the principal database and the principal database becomes the mirror. For
example, the following table shows the how a manual failover swaps the roles of two mirroring partners:
SQLDBENGINE0_1 and SQLDBENGINE0_2 .

SERVER BEFORE FAILOVER AFTER FAILOVER

SQLDBENGINE0_1 PRINCIPAL MIRROR

SQLDBENGINE0_2 MIRROR PRINCIPAL

Note that the server roles for other database mirroring sessions are not affected. For more information, see Role
Switching During a Database Mirroring Session (SQL Server).
To manually fail over database mirroring
1. Connect to the principal server instance and, in the Object Explorer pane, click the server name to expand
the server tree.
2. Expand Databases, and select the database to be failed over.
3. Right-click the database, select Tasks, and then click Mirror. This opens the Mirroring page of the
Database Properties dialog box.
4. Click Failover.
A confirmation box appears. The principal server begins by trying to connect to the mirror server by using
Windows Authentication. If Windows Authentication does not work, the principal server displays the
Connect to Server dialog box. If the mirror server uses SQL Server Authentication, select SQL Server
Authentication in the Authentication box. In the Login text box, specify the login account to connect
with on the mirror server, and in the Password text box, specify the password for that account.
If failover succeeds, the Database Properties dialog box closes. The mirror database becomes the
principal database and the principal database becomes the mirror.
If failover fails, an error message is displayed and the dialog box remains open.

IMPORTANT
If you have modified any properties since opening the Mirroring page, those changes will not be saved.

The dialog box closes automatically.


See Also
Database Properties (Mirroring Page)
Database Mirroring (SQL Server)
Manually Fail Over a Database Mirroring Session (Transact-SQL )
Pause or Resume a Database Mirroring Session (SQL Server)
Remove Database Mirroring (SQL Server)
Force Service in a Database Mirroring Session
(Transact-SQL)
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
In high-performance mode and high-safety mode without automatic failover, if the principal server fails while the
mirror server is available, the database owner can make the database available by forcing service to fail over (with
possible data loss) to the mirror database. This option is available only under all the following conditions:
The principal server is down.
WITNESS is set to OFF or is connected to the mirror server.
Cau t i on

Forced service is strictly a disaster recovery method. Forcing service may involve some data loss. Therefore, force
service only if you are willing to risk losing some data in order to restore service to the database immediately. If
forcing service risks losing significant data, we recommend that you stop mirroring and manually resynchronize
the databases. For more information about the risks of forcing service, see Database Mirroring Operating Modes.
Forcing service suspends the session and starts a new recovery fork. The effect of forcing service is similar to
removing mirroring and recovering the former principal database. However, forcing service facilitates
resynchronizing the databases (with possible data loss) when mirroring resumes.
To force service in a database mirroring session
1. Connect to the mirror server.
2. Issue the following statement:
ALTER DATABASE <database_name> SET PARTNER FORCE_SERVICE_ALLOW_DATA_LOSS
where <database_name> is the mirrored database.
The mirror server immediately transitions to principal server, and mirroring is suspended.

See Also
ALTER DATABASE (Transact-SQL )
Database Mirroring Operating Modes
Estimate the Interruption of Service During Role
Switching (Database Mirroring)
6/12/2018 • 5 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
During a role switch, the amount of time that database mirroring will be out of service depends on the type of role
switching and the cause of the role switch.
For automatic failover, two factors contribute to the time service is interrupted: the time required for the
mirror server to recognize that the principal server instance has failed, that is error detection, plus the time
required to fail over the database, that is failover time.
For a forced-service operation, though a failure has occurred, detecting and responding to the failure
depends on human responsiveness. However, estimating the potential interruption of service is limited to
estimating the time for the mirror server to switch roles after the forced service command is issued.

NOTE
To reduce the time required to detect specific conditions such as some types of errors, you can define alerts for
those conditions.

For a manual failover, only the time required to fail over the database after the failover command is issued.

Error detection
The time for the system to notice an error depends on the type of error; for example, a network error is noticed
almost instantly, while noticing a server hang by default takes 10 seconds, which is the default timeout period.
For information on errors that can cause a failure during a database mirroring session and timeout detection in
high-safety mode with automatic failover, see Possible Failures During Database Mirroring).

Failover time
Failover time consists mainly of the time that the former mirror server requires to roll forward any log remaining
in its redo queue, plus a short additional time (for more information about how the mirror server processes log
records, see Database Mirroring (SQL Server)). For information on estimating failover time, see Estimating Your
Failover Redo Rate, later in this topic.

IMPORTANT
If failover occurs during a transaction in which an index or table is created and then changed, failover might take longer than
usual. For example, failing over during the following series of operations might increase failover time: BEGIN TRANSACTION,
CREATE INDEX on a table, and SELECT INTO the table. The possibility of increased failover time during such a transaction
remains until it is completed with either a COMMIT TRANSACTION or ROLLBACK TRANSACTION statement.

The Redo Queue


Rolling forward the database involves applying whatever log records are currently in the redo queue on the
mirror server. The redo queue consists of the log records that have been written to disk on the mirror server but
not yet rolled forward on the mirror database.
Failover time for the database depends on how fast the mirror server can roll forward the log in the redo queue,
which, in turn, is determined primarily by the system hardware and the current work load. Potentially, a principal
database can become so busy that the principal server ships log to the mirror server much faster than it can roll
the log forward. In this situation, failover might take significant time while the mirror server rolls forward the log
in the redo queue. To learn the current size of the redo queue, use the Redo Queue counter in the database
mirroring performance object. For more information, see SQL Server, Database Mirroring Object.
Estimating the Failover Redo Rate
You can measure the amount of time required to roll forward log records—the redo rate—by using a test copy of
the production database.
The method for estimating roll forward time during failover depends on the number of threads the mirror server
uses during the redo phase. The number of threads depends on the following:
In SQL Server Standard, the mirror server always uses a single thread to roll forward the database.
In SQL Server Enterprise, mirror servers on computers with fewer than five CPUs also use only a single
thread. With five or more CPUs, a mirror server distributes its roll forward operations among multiple
threads during a failover (this is known as parallel redo). Parallel redo is optimized to use one thread for
every four CPUs.
Estimating the Single-Threaded Redo Rate
For single-threaded redo, roll forward of the mirror database during failover takes approximately the same
amount of time as a restore of a log backup takes to roll forward the same amount of log. To estimate failover
time, create a test database in the environment under which you intend to run mirroring. Then take a log backup
from the production database. To measure the redo rate for that log backup, time how long it takes you to restore
the log backup WITH NORECOVERY onto the test database.
Once you know the redo rate of your mirror server, you can estimate the time to fail over the database at a given
point in time by dividing the amount of current log to be redone on the mirror (as measured by the Redo Queue
performance counter) by the redo rate. Under normal conditions, if the mirror server can keep up with the load
from the principal, the Redo Queue is small or close to zero, and a failover only takes a few seconds.
Estimating the Parallel Redo Rate
In SQL Server Enterprise, parallel redo is optimized to use one thread for every four CPUs. To estimate roll
forward time for parallel redo, it is more accurate to access a running test system than a test database. While
monitoring the redo queue on the mirror server, increase the load on the principal server. In normal operation, the
redo queue is close to zero. Increase the load on the principal server until the Redo Queue starts to grow
continuously; the system is then at its maximum redo rate, and the Redo Bytes/sec performance counter at this
point represents the maximum redo rate. For more information, see SQL Server, Database Mirroring Object.

Estimating Interruption of Service During Automatic Failover


The following figure illustrates how error detection and failover time contribute to the overall time required for an
automatic failover to complete on Partner_B. Failover requires time to roll forward the database (the redo phase)
plus a small amount of time to bring the database online. The undo phase, which involves rolling back any
uncommitted transactions, occurs after the new principal database goes online and continues after fail over. The
database is available during the undo phase.
See Also
Database Mirroring Operating Modes
Role Switching During a Database Mirroring Session (SQL Server)
Monitoring Database Mirroring (SQL Server)
Possible Failures During Database Mirroring
6/12/2018 • 5 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
Physical, operating system, or SQL Server problems can cause a failure in a database mirroring session.
Database mirroring does not regularly check the components on which Sqlservr.exe relies to verify whether they
are functioning correctly or have failed. However, for some types of failures, the affected component reports an
error to Sqlservr.exe. An error reported by another component is called a hard error. To detect other failures that
would otherwise go unnoticed, database mirroring implements its own time-out mechanism. When a mirroring
time-out occurs, database mirroring assumes that a failure has occurred and declares a soft error. However, some
failures that happen at the SQL Server instance level do not cause mirroring to time-out and can go undetected.

IMPORTANT
Failures in databases other than the mirrored database are not detectable in a database mirroring session. Moreover, a
data disk failure is unlikely to be detected, unless the database is restarted because of a data disk failure.

The speed of error detection and, therefore, the reaction time of the mirroring session to a failure, depends on
whether the error is hard or soft. Some hard errors, such as network failures are reported immediately. However,
in some cases, component-specific time-out periods can delay the reporting of some hard errors. For soft errors,
the length of the mirroring time-out period determines the speed of error detection. By default, this period is 10
seconds. This is the minimum recommended value.

Failures Due to Hard Errors


Possible causes of hard errors include (but are not limited to) the following conditions:
A broken connection or wire
A bad network card
A router change
Changes in the firewall
Endpoint reconfiguration
Loss of the drive where the transaction log resides
Operating system or process failure
For example, when the log drive on the principal database becomes unresponsive and fails, the operating
system informs Sqlservr.exe that a serious error has occurred.
Some components, such as network components and some IO subsystems, have their own time-outs to
determine failures. Such time-outs are independent of database mirroring, which has no knowledge of
them and is completely unaware of their behavior. In these cases, the time-out delay increases the time
between a failure and when database mirroring receive the resulting hard error.
NOTE
The only active error checking performed for database mirroring occurs for soft error cases. For more information, see
"Failures Due to Soft Errors," later in this topic.

To help you interpret the error conditions that occur on the network, ask a network engineer what error
messages are sent to a port when the following events occur on a TCP connection:
DNS is not working.
Cables are unplugged.
Microsoft Windows has a firewall that blocks a specific port.
The application that is monitoring a port fails.
A Windows-based server is renamed.
A Windows-based server is rebooted.

NOTE
Mirroring does not protect against problems specific to client accessing the servers. For example, consider a case in which a
public network adapter handles client connections to the principal server instance, while a private network interface card
handles all mirroring traffic among server instances. In this case, failure of the public network adapter would prevent clients
from accessing the database, though the database would continue to be mirrored.

Failures Due to Soft Errors


Conditions that might cause mirroring time-outs include (but are not limited to) the following:
Network errors such as TCP link time-outs, dropped or corrupted packets, or packets that are in an
incorrect order.
A hanging operating system, server, or database state.
A Windows server timing out.
Insufficient computing resources, such as a CPU or disk overload, the transaction log filling up, or the
system is running out of memory or threads. In these cases, you must increase the time-out period, reduce
the workload, or change the hardware to handle the workload.
The Mirroring Time -Out Mechanism
Because soft errors are not detectable directly by a server instance, a soft error could potentially cause a server
instance to wait indefinitely. To prevent this, database mirroring implements its own time-out mechanism, based
on each server instance in a mirroring session sending out a ping on each open connection at a fixed interval.
To keep a connection open, a server instance must receive a ping on that connection in the time-out period
defined, plus the time that is required to send one more ping. Receiving a ping during the time-out period
indicates that the connection is still open and that the server instances are communicating over it. On receiving a
ping, a server instance resets its time-out counter on that connection.
If no ping is received on a connection during the time-out period, a server instance considers the connection to
have timed out. The server instance closes the timed-out connection and handles the time-out event according to
the state and operating mode of the session.
Even if the other server is actually proceeding correctly, a time-out is considered a failure. If the time-out value
for a session is too short for the regular responsiveness of either partner, false failures can occur. A false failure
occurs when one server instance successfully contacts another whose response time is so slow that its pings are
not received before the time-out period expires.
In high-performance mode sessions, the time-out period is always 10 seconds. This is generally enough to avoid
false failures. In high-safety mode sessions, the default time-out period is 10 seconds, but you can change the
duration. To avoid false failures, we recommend that the mirroring time-out period always be 10 seconds or
more.
To change the time-out value (high-safety mode only)
Use the ALTER DATABASE <database> SET PARTNER TIMEOUT <integer> statement.
To view the current time-out value
Query mirroring_connection_timeout in sys.database_mirroring.

Responding to an Error
Regardless of the type of error, a server instance that detects an error responds appropriately based on the role
of the instance, the operating mode of the session, and the state of any other connection in the session. For
information about what occurs on the loss of a partner, see Database Mirroring Operating Modes.

See Also
Estimate the Interruption of Service During Role Switching (Database Mirroring)
Database Mirroring Operating Modes
Role Switching During a Database Mirroring Session (SQL Server)
Database Mirroring (SQL Server)
Mirroring States (SQL Server)
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
During a database mirroring session, the mirrored database is always in a specific state (the mirroring state). The
state of the database reflects the communication status, data flow, and the difference in data between the partners.
The database mirroring session adopts the same state as the principal database.
Throughout a database mirroring session, the server instances monitor each other. The partners use the mirroring
state to monitor the database. With the exception of the PENDING_FAILOVER state, the principal and mirror
database are always in the same state. If a witness is set for the session, each of the partners monitors the witness
using its connection state (CONNECTED or DISCONNECTED ).
The possible mirroring states of the database are as follows:

MIRRORING STATE DESCRIPTION

SYNCHRONIZING The contents of the mirror database are lagging behind the
contents of the principal database. The principal server is
sending log records to the mirror server, which is applying the
changes to the mirror database to roll it forward.

At the start of a database mirroring session, the database is in


the SYNCHRONIZING state. The principal server is serving the
database, and the mirror is trying to catch up.

SYNCHRONIZED When the mirror server becomes sufficiently caught up to the


principal server, the mirroring state changes to
SYNCHRONIZED. The database remains in this state as long
as the principal server continues to send changes to the
mirror server and the mirror server continues to apply
changes to the mirror database.

If transaction safety is set to FULLautomatic failover and


manual failover are both supported in the SYNCHRONIZED
state, there is no data loss after a failover.

If transaction safety is off, some data loss is always possible,


even in the SYNCHRONIZED state.

SUSPENDED The mirror copy of the database is not available. The principal
database is running without sending any logs to the mirror
server, a condition known as running exposed. This is the
state after a failover.

A session can also become SUSPENDED as a result of redo


errors or if the administrator pauses the session.

SUSPENDED is a persistent state that survives partner


shutdowns and startups.
MIRRORING STATE DESCRIPTION

PENDING_FAILOVER This state is found only on the principal server after a failover
has begun, but the server has not transitioned into the mirror
role.

When the failover is initiated, the principal database goes into


the PENDING_FAILOVER state, quickly terminates any user
connections, and takes over the mirror role soon thereafter.

DISCONNECTED The partner has lost communication with the other partner.

See Also
Monitoring Database Mirroring (SQL Server)
Setting Up Database Mirroring (SQL Server)
6/12/2018 • 5 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
This section describes the prerequisites, recommendations, and steps for setting up database mirroring. For an
introduction to database mirroring, see Database Mirroring (SQL Server).

IMPORTANT
We recommend that you configure database mirroring during off-peak hours because configuration can impact
performance.

Preparing a Server Instance to Host a Mirror Server


For each database mirroring session:
1. The principal server, mirror server, and witness, if any, must be hosted by separate server instances, which
should be on separate host systems. Each of the server instances requires a database mirroring endpoint.
If you need to create a database mirroring endpoint, ensure that it is accessible to the other server
instances.
The form of authentication used for database mirroring by a server instance is a property of its database
mirroring endpoint. Two types of transport security are available for database mirroring: Windows
Authentication or certificate-based authentication. For more information, see Transport Security for
Database Mirroring and Always On Availability Groups (SQL Server).
The requirements for network access are specific to the form of authentication, as follows:
If using Windows Authentication
If server instances are running under different domain user accounts, each requires a login in the
master database of the others. If the login does not exist, you must create it. For more information,
see Allow Network Access to a Database Mirroring Endpoint Using Windows Authentication (SQL
Server).
If using certificates
To enable certificate authentication for database mirroring on a given server instance, the system
administrator must configure each server instance to use certificates on both outbound and
inbound connections. Outbound connections must be configured first. For more information, see
Use Certificates for a Database Mirroring Endpoint (Transact-SQL ).
2. Make sure that logins exist on the mirror server for all the database users. For more information, see Set
Up Login Accounts for Database Mirroring or Always On Availability Groups (SQL Server).
3. On the server instance that will host the mirror database, set up the rest of the environment that is
required for the mirrored database. For more information, see Manage Metadata When Making a
Database Available on Another Server Instance (SQL Server).

Overview: Establishing a Database Mirroring Session


The basic steps for establishing a mirroring session are as follows:
1. Create the mirror database by restoring the following backups, using RESTORE WITH NORECOVERY
on every restore operation:
a. Restore a recent full database backup of the principal database, after making sure that the principal
database was already using the full recovery model when the backup was taken. The mirror
database must have the same name as the principal database.
b. If you have taken any differential backups of the database since the restored full backup, restore
your most recent differential backup.
c. Restore all the log backups done since the full or differential database backup.
For more information, see Prepare a Mirror Database for Mirroring (SQL Server).

IMPORTANT
Complete the remaining setup steps as soon as you can after taking the backup of the principal database. Before
you can start mirroring on the partners, you should create a current log backup on the original database and
restore it to the future mirror database.

2. You can set up mirroring by using either Transact-SQL or the Database Mirroring Wizard. For more
information, see one of the following:
Establish a Database Mirroring Session Using Windows Authentication (Transact-SQL )
Establish a Database Mirroring Session Using Windows Authentication (SQL Server Management
Studio)
3. By default a session is set to full transaction safety (SAFETY is set to FULL ), which starts the session in
synchronous, high-safety mode without automatic failover. You can reconfigure the session to run in
high-safety mode with automatic failover or in asynchronous, high-performance mode, as follows:
High-safety mode with automatic failover
If you want a high-safety mode session to support automatic failover, add a witness server
instance.
To add a witness
Add a Database Mirroring Witness Using Windows Authentication (Transact-SQL )
Establish a Database Mirroring Session Using Windows Authentication (SQL Server
Management Studio)

NOTE
The database owner can turn off the witness for a database at any time. Turning off the witness is
equivalent to having no witness, and automatic failover cannot occur.

High-performance mode
Alternatively, if you do not want automatic failover and you prefer to emphasize performance over
availability, turn off transaction safety. For more information, see Change Transaction Safety in a
Database Mirroring Session (Transact-SQL ).
NOTE
In high-performance mode, WITNESS needs to be set to OFF. For more information, see Quorum: How a
Witness Affects Database Availability (Database Mirroring).

NOTE
For an example of using Transact-SQL to set up database mirroring using Microsoft Windows Authentication, see Example:
Setting Up Database Mirroring Using Windows Authentication (Transact-SQL).
For an example of using Transact-SQL to set up database mirroring using certificate-based security, see Example: Setting
Up Database Mirroring Using Certificates (Transact-SQL).

In This Section
Prepare a Mirror Database for Mirroring (SQL Server)
Summarizes the steps for creating a mirror database or preparing a mirror database before resuming a
suspended session. Also provides links to how -to topics.
Specify a Server Network Address (Database Mirroring)
Describes the syntax of a server network address, how the address identifies the database mirroring endpoint of
the server instance, and how to find the fully-qualified domain name of a system.
Establish a Database Mirroring Session Using Windows Authentication (SQL Server Management Studio)
Describes how to use the Configure Database Mirroring Security Wizard to start database mirroring on a
database.
Establish a Database Mirroring Session Using Windows Authentication (Transact-SQL )
Describes the Transact-SQL steps for setting up database mirroring.
Example: Setting Up Database Mirroring Using Windows Authentication (Transact-SQL )
Contains an example of all the stages required to create a database mirroring session with a witness, using
Windows Authentication.
Example: Setting Up Database Mirroring Using Certificates (Transact-SQL )
Contains an example of all the stages required to create a database mirroring session with a witness, using
certificate-based authentication.
Set Up Login Accounts for Database Mirroring or Always On Availability Groups (SQL Server)
Describes creating a login for a remote server instance that is using a different account than the local server
instance.

Related Tasks
SQL Server Management Studio
Start the Configuring Database Mirroring Security Wizard (SQL Server Management Studio)
Establish a Database Mirroring Session Using Windows Authentication (SQL Server Management
Studio)
Transact-SQL
Allow Network Access to a Database Mirroring Endpoint Using Windows Authentication (SQL Server)
Allow a Database Mirroring Endpoint to Use Certificates for Outbound Connections (Transact-SQL )
Allow a Database Mirroring Endpoint to Use Certificates for Inbound Connections (Transact-SQL )
Create a Database Mirroring Endpoint for Windows Authentication (Transact-SQL )
Establish a Database Mirroring Session Using Windows Authentication (Transact-SQL )
Add a Database Mirroring Witness Using Windows Authentication (Transact-SQL )
Set Up a Mirror Database to Use the Trustworthy Property (Transact-SQL )
Transact-SQL/SQL Server Management Studio
Upgrading Mirrored Instances
Prepare a Mirror Database for Mirroring (SQL Server)
Troubleshoot Database Mirroring Configuration (SQL Server)

See Also
Database Mirroring (SQL Server)
Database Mirroring: Interoperability and Coexistence (SQL Server)
Transport Security for Database Mirroring and Always On Availability Groups (SQL Server)
Specify a Server Network Address (Database Mirroring)
Prepare a Mirror Database for Mirroring (SQL
Server)
6/12/2018 • 8 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
Before a database mirroring session can start, the database owner or system administrator must make sure
that the mirror database has been created and is ready for mirroring. Creating a new mirror database
minimally requires taking a full backup of the principal database and a subsequent log backup and restoring
them both onto the mirror server instance, using WITH NORECOVERY.
This topic describes how to prepare a mirror database in SQL Server 2017 by using SQL Server Management
Studio or Transact-SQL.
Before you begin:
Requirements
Limitations and Restrictions
Recommendations
Security
To Prepare an Existing Mirror Database to Restart Mirroring
To Prepare a New Mirror Database
Follow Up: After Preparing a Mirror Database
Related Tasks

Before You Begin


Requirements
The principal and mirror server instances must be running on the same version of SQL Server. While it
is possible for the mirror server to have a higher version of SQL Server, this configuration is only
recommended during a carefully planned upgrade process. In such a configuration, you run the risk of
an automatic failover, in which data movement is automatically suspended because data cannot move to
a lower version of SQL Server. For more information, see Upgrading Mirrored Instances.
The principal and mirror server instances must be running on the same edition of SQL Server. For
information about support for database mirroring in SQL Server 2017, see Editions and Supported
features of SQL Server 2017.
The database must use the full recovery model.
For more information, see View or Change the Recovery Model of a Database (SQL Server) or
sys.databases (Transact-SQL ) and ALTER DATABASE (Transact-SQL ).
The name of the mirror database must be the same as the name of the principal database.
The mirror database must be in the RESTORING state for mirroring to work. When preparing a mirror
database, you must use RESTORE WITH NORECOVERY for every restore operation. Minimally, you
will need to restore WITH NORECOVERY a full backup of the principal database, followed by all
subsequent log backups.
The system where you plan to create the mirror database must possesses a disk drive with sufficient
space to hold the mirror database.
Limitations and Restrictions
You cannot mirror the master, msdb, temp, or model system databases.
You cannot mirror a database that belongs to an Always On availability group.
Recommendations
Use a very recent full database backup or a recent differential database backup of the principal database.
If a log backup job is scheduled to run very frequently on the principal database, you might have to
disable the backup job until mirroring has started.
If possible, the path (including the drive letter) of the mirror database should be identical to the path of
the principal database.
If the file paths must differ, for example, if the principal database is on drive 'F:' but the mirror system
lacks an F: drive, you must include the MOVE option in the RESTORE STATEMENT.

IMPORTANT
Adding a file during a mirroring session without impacting the session requires that the path of the file exists on
both servers. Therefore, if you move the database files when creating the mirror database, a later add-file
operation might fail on the mirror database and cause mirroring to be suspended. For information about dealing
with a failed create-file operation, see Troubleshoot Database Mirroring Configuration (SQL Server).

If the principal database has any full-text catalogs, we recommend that you see Database Mirroring and
Full-Text Catalogs (SQL Server).
For a production database, always back up to a separate device.
Security
TRUSTWORTHY is set to OFF when a database is backed up. Therefore, TRUSTWORTHY is always OFF on a
new mirror database. If the database needs to be trustworthy after a failover, additional setup steps are
necessary. For more information, see Set Up a Mirror Database to Use the Trustworthy Property (Transact-
SQL ).
For information about enabling automatic decryption of the database master key of a mirror database, see Set
Up an Encrypted Mirror Database.
Permissions
Database owner or system administrator.

To Prepare an Existing Mirror Database to Restart Mirroring


If mirroring has been removed and the mirror database is still in the RECOVERING state, you can restart
mirroring.
1. Take at least one log backup on the principal database. For more information, see Back Up a Transaction
Log (SQL Server).
2. On the mirror database, use RESTORE WITH NORECOVERY to restore all log backups taken on the
principal database since mirroring was removed. For more information, see Restore a Transaction Log
Backup (SQL Server).

To Prepare a New Mirror Database


To prepare a mirror database

NOTE
For a Transact-SQL example of this procedure, see Example (Transact-SQL), later in this section.

1. Connect to principal server instance.


2. Create either a full database backup or a differential database backup of the principal database.
Create a Full Database Backup (SQL Server)
Create a Differential Database Backup (SQL Server).
3. Typically, you need to take at least one log backup on the principal database. However, a log backup
might be unnecessary, if the database has just been created and no log backup has been taken yet, or if
the recovery model has just been changed from SIMPLE to FULL.
Back Up a Transaction Log (SQL Server)
4. Unless the backups are on a network drive that is accessible from both systems, copy the database and
log backups to the system that will host the mirror server instance.
5. Connect to mirror server instance.
6. Using RESTORE WITH NORECOVERY, create the mirror database by restoring the full database
backup and, optionally, the most recent differential database backup, onto the mirror server instance.

NOTE
If you restore the database filegroup by filegroup, be sure to restore the whole database.

Restore a Database Backup Using SSMS


RESTORE (Transact-SQL ) and RESTORE Arguments (Transact-SQL ).
7. Using RESTORE WITH NORECOVERY, apply any outstanding log backup or backups to the mirror
database.
Restore a Transaction Log Backup (SQL Server)
Example (Transact-SQL )
Before you can start a database mirroring session, you must create the mirror database. You should do this just
before starting the mirroring session.
This example uses the AdventureWorks2012 sample database, which uses the simple recovery model by
default.
1. To use database mirroring with the AdventureWorks2012 database, modify it to use the full recovery
model:
USE master;
GO
ALTER DATABASE AdventureWorks
SET RECOVERY FULL;
GO

2. After modifying the recovery model of the database from SIMPLE to FULL, create a full backup, which
can be used to create the mirror database. Because the recovery model has just been changed, the
WITH FORMAT option is specified to create a new media set. This is useful to separate the backups
under the full recovery model from any previous backups made under the simple recovery model. For
the purpose of this example, the backup file ( C:\AdventureWorks.bak ) is created on the same drive as the
database.

NOTE
For a production database, you should always back up to a separate device.

On the principal server instance (on PARTNERHOST1 ), create a full backup of the principal database as
follows:

BACKUP DATABASE AdventureWorks


TO DISK = 'C:\AdventureWorks.bak'
WITH FORMAT
GO

3. Copy the full backup to the mirror server.


4. Using RESTORE WITH NORECOVERY, restore the full backup onto the mirror server instance. The
restore command depends on whether the paths of principal and mirror databases are identical.
If the paths are identical:
On the mirror server instance (on PARTNERHOST5 ), restore the full backup as follows:

RESTORE DATABASE AdventureWorks


FROM DISK = 'C:\AdventureWorks.bak'
WITH NORECOVERY
GO

If the paths differ:


If the path of the mirror database differs from the path of the principal database (for instance,
their drive letters differ), creating the mirror database requires that the restore operation include
a MOVE clause.

IMPORTANT
If the path names of the principal and mirror databases differ, you cannot add a file. This is because on
receiving the log for the add file operation, the mirror server instance attempts to place the new file in
the location used by the principal database.

For example, the following command restores a backup of a principal database residing in
C:\Program Files\Microsoft SQL Server\MSSQL.n\MSSQL\Data\ to a different location,
D:\Program Files\Microsoft SQL Server\MSSQL.n\MSSQL\Dat a\ , where the mirror database
is to reside.

RESTORE DATABASE AdventureWorks


FROM DISK='C:\AdventureWorks.bak'
WITH NORECOVERY,
MOVE 'AdventureWorks_Data' TO
'D:\Program Files\Microsoft SQL Server\MSSQL.n\MSSQL\Data\AdventureWorks_Data.mdf',
MOVE 'AdventureWorks_Log' TO
'D:\Program Files\Microsoft SQL Server\MSSQL.n\MSSQL\Data\AdventureWorks_Log.ldf';
GO

5. After you create the full backup, you must create a log backup on the principal database. For example,
the following Transact-SQL statement backs up the log to the same file used by the preceding full
backup:

BACKUP LOG AdventureWorks


TO DISK = 'C:\AdventureWorks.bak'
GO

6. Before you can start mirroring, you must apply the required log backup (and any subsequent log
backups).
For example, the following Transact-SQL statement restores the first log from C:\AdventureWorks.bak :

RESTORE LOG AdventureWorks


FROM DISK = 'C:\AdventureWorks.bak'
WITH FILE=1, NORECOVERY
GO

7. If any additional log backups occur before you start mirroring, you must also restore all of those log
backups, in sequence, to the mirror server using WITH NORECOVERY.
For example, the following Transact-SQL statement restores two additional logs from
C:\AdventureWorks.bak :

RESTORE LOG AdventureWorks


FROM DISK = 'C:\AdventureWorks.bak'
WITH FILE=2, NORECOVERY
GO
RESTORE LOG AdventureWorks
FROM DISK = 'C:\AdventureWorks.bak'
WITH FILE=3, NORECOVERY
GO

For a complete example of setting up database mirroring, showing security setup, preparing the mirror
database, setting up the partners, and adding a witness, see Setting Up Database Mirroring (SQL
Server).

Follow Up: After Preparing a Mirror Database


1. If any additional log backups have been taken since your most recent RESTORE LOG operation, you
must manually apply every additional log backup, using RESTORE WITH NORECOVERY.
2. Start the mirroring session. For more information, see Establish a Database Mirroring Session Using
Windows Authentication (SQL Server Management Studio) or Establish a Database Mirroring Session
Using Windows Authentication (Transact-SQL ).
3. If you disabled the backup job on the principal database, reenable the job.
4. If the database needs to be trustworthy after a failover, extra setup steps are necessary after mirroring
begins. For more information, see Set Up a Mirror Database to Use the Trustworthy Property (Transact-
SQL ).

Related Tasks
Create a Full Database Backup (SQL Server)
Restore a Transaction Log Backup (SQL Server)
Establish a Database Mirroring Session Using Windows Authentication (SQL Server Management
Studio)
Establish a Database Mirroring Session Using Windows Authentication (Transact-SQL )
Set Up an Encrypted Mirror Database
Set Up a Mirror Database to Use the Trustworthy Property (Transact-SQL )

See Also
Database Mirroring (SQL Server)
Transport Security for Database Mirroring and Always On Availability Groups (SQL Server)
Setting Up Database Mirroring (SQL Server)
Back Up and Restore Full-Text Catalogs and Indexes
Database Mirroring and Full-Text Catalogs (SQL Server)
Database Mirroring and Replication (SQL Server)
BACKUP (Transact-SQL )
RESTORE (Transact-SQL )
RESTORE Arguments (Transact-SQL )
Set Up an Encrypted Mirror Database
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
To enable automatic decryption of the database master key of a mirror database, you must provide the password
used to encrypt the master key to the mirror server instance. SQL Server 2005 (9.x) and later versions include
mechanisms to transfer the password. Use sp_control_dbmasterkey_password to create a credential for the
database master key before you start database mirroring. You must repeat this process for every database that
will be mirrored. For more information, see sp_control_dbmasterkey_password (Transact-SQL ).
Cau t i on

Do not enable failover decryption of a database that must remain inaccessible to sa and other highly privileged
server principals. You can configure a database so that its key hierarchy cannot be decrypted by the service
master key. This option is supported as a defense-in-depth for databases that contain information that should not
be accessible to sa or other highly privileged server principals. Enabling failover decryption of such a database
removes this defense-in-depth, enabling sa and other highly privileged server principals to decrypt the database.

See Also
sp_control_dbmasterkey_password (Transact-SQL )
CREATE MASTER KEY (Transact-SQL )
ALTER MASTER KEY (Transact-SQL )
Encryption Hierarchy
Setting Up Database Mirroring (SQL Server)
Set Up a Mirror Database to Use the Trustworthy
Property (Transact-SQL)
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
When a database is backed up, the TRUSTWORTHY database property is set to OFF. Therefore, on a new mirror
database TRUSTWORTHY is always OFF. If the database needs to be trustworthy after a failover, extra setup
steps are necessary after mirroring begins.

NOTE
For information about this database property, see TRUSTWORTHY Database Property.

Procedure
To setup a mirror database to use the Trustworthy Property
1. On the principal server instance, verify that the principal database has the Trustworthy property turned on.

SELECT name, database_id, is_trustworthy_on FROM sys.databases

For more information, see sys.databases (Transact-SQL ).


2. After starting mirroring, verify that the database is currently the principal database, the session is using a
synchronous operating mode, and the session is already synchronized.

SELECT database_id, mirroring_role, mirroring_safety_level_desc, mirroring_state_desc FROM


sys.database_mirroring

For more information, see sys.database_mirroring (Transact-SQL ).


3. Once the mirroring session is synchronized, manually fail over to the mirror database.
This can be done in either SQL Server Management Studio or using Transact-SQL:
Manually Fail Over a Database Mirroring Session (SQL Server Management Studio)
Manually Fail Over a Database Mirroring Session (Transact-SQL )
4. Turn on the trustworthy database property using the following ALTER DATABASE command:

ALTER DATABASE <database_name> SET TRUSTWORTHY ON

For more information, seeALTER DATABASE (Transact-SQL ).


5. Optionally, manually failover again to return to the original principal.
6. Optionally, switch to asynchronous, high-performance mode by setting SAFETY to OFF and ensuring that
WITNESS is also set to OFF.
In Transact-SQL:
Change Transaction Safety in a Database Mirroring Session (Transact-SQL )
Remove the Witness from a Database Mirroring Session (SQL Server)
In SQL Server Management Studio:
Establish a Database Mirroring Session Using Windows Authentication (SQL Server Management
Studio)

See Also
TRUSTWORTHY Database Property
Set Up an Encrypted Mirror Database
Specify a Server Network Address (Database
Mirroring)
6/12/2018 • 4 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
Setting up a database mirroring session requires a server network address for each of the server instances. The
server network address of a server instance must unambiguously identify the instance by providing a system
address and the number of the port on which the instance is listening.
Before you can specify a port in a server network address, the database mirroring endpoint must exist on the
server instance. For more information, see Create a Database Mirroring Endpoint for Windows Authentication
(Transact-SQL ).

Syntax for a Server Network Address


The syntax for a server network address is of the form:
TCP://<system -address>:<port>
where
<system -address> is a string that unambiguously identifies the destination computer system. Typically,
the server address is a system name (if the systems are in the same domain), a fully qualified domain
name, or an IP address:
If the systems are the same domain, you can use the name of the computer system; for example,
SYSTEM46 .

To use an IP address, it must be unique in your environment. We recommend that you use an IP
address only if it is static. The IP address can be IP Version 4 (IPv4) or IP Version 6 (IPv6). An IPv6
address must be enclosed within square brackets, for example: [<IPv6_address>].
To learn the IP address of a system, at the Windows command prompt, enter the ipconfig
command.
The fully qualified domain name is guaranteed to work. This is a locally defined address string that
different forms in different places. Often, but not always, a fully qualified domain name is a
compound name that includes the computer name and a series of period-separated domain
segments of the form:
computer_name . domain_segment[....domain_segment]
where computer_name is the network name of the computer running the server instance, and
domain_segment[....domain_segment] is the remaining domain information of the server; for
example: localinfo.corp.Adventure-Works.com .
The content and number of domain segments are determined within the company or organization.
If you do not know the fully qualified domain name for your server, see your system administrator.
NOTE
For information about how to find a fully qualified domain name, see "Finding the Fully Qualified Domain
Name," later in this topic.

<port> is the port number used by the mirroring endpoint of the partner server instance. For information
about specifying an endpoint, see Create a Database Mirroring Endpoint for Windows Authentication
(Transact-SQL ).
A database mirroring endpoint can use any available port on the computer system. Each port number on
a computer system must be associated with only one endpoint, and each endpoint is associated with a
single server instance; thus, different server instances on the same server listen on different endpoints
with different ports. Therefore, the port you specify in the server network address when you set up a
database mirroring session will always direct the session to the server instance whose endpoint is
associated with that port.
In the server network address of a server instance, only the number of the port associated with its
mirroring endpoint distinguishes that instance from any other instances on the computer. The following
figure illustrates the server network addresses of two server instances on a single computer. The default
instance uses port 7022 and the named instance uses port 7033 . The server network address for these
two server instances are, respectively: TCP://MYSYSTEM.Adventure-works.MyDomain.com:7022 and
TCP://MYSYSTEM.Adventure-works.MyDomain.com:7033 . Note that the address does not contain the name of
the server instance.

To identify the port currently associated with database mirroring endpoint of a server instance, use the
following Transact-SQL statement:

SELECT type_desc, port FROM sys.tcp_endpoints

Find the row whose type_desc value is "DATABASE_MIRRORING," and use the corresponding port
number.
Examples
A. Using a system name
The following server network address specifies a system name, SYSTEM46 , and port 7022 .

ALTER DATABASE AdventureWorks SET PARTNER ='tcp://SYSTEM46:7022';

B. Using a fully qualified domain name


The following server network address specifies a fully qualified domain name,
DBSERVER8.manufacturing.Adventure-Works.com , and port 7024 .

ALTER DATABASE AdventureWorks SET PARTNER ='tcp://DBSERVER8.manufacturing.Adventure-Works.com:7024';

C. Using IPv4
The following server network address specifies an IPv4 address, 10.193.9.134 , and port 7023 .

ALTER DATABASE AdventureWorks SET PARTNER ='tcp://10.193.9.134:7023';

D. Using IPv6
The following server network address contains an IPv6 address, 2001:4898:23:1002:20f:1fff:feff:b3a3 , and port
7022 .

ALTER DATABASE AdventureWorks SET PARTNER ='tcp://[2001:4898:23:1002:20f:1fff:feff:b3a3]:7022';

Finding the Fully Qualified Domain Name


To find the fully qualified domain name of a system, at the Windows command prompt on that system, enter:
IPCONFIG /ALL
To form the fully qualified domain name, concatenate the values of<host_name> and <Primary_Dns_Suffix> as
follows:
<host_name> . <Primary_Dns_Suffix>
For example, the IP configuration
Host Name . . . . . . : MYSERVER

Primary Dns Suffix . . . : mydomain.Adventure-Works.com

equates to the following fully qualified domain name:


MYSERVER.mydomain.Adventure-Works.com

Examples
The following example shows the server network address for a server instance on a computer system named
REMOTESYSTEM3 in another domain. The domain information is NORTHWEST.ADVENTURE-WORKS.COM , and the port of
the database mirroring endpoint is 7025 . Given these example components, the server network address is.
TCP://REMOTESYSTEM3.NORTHWEST.ADVENTURE-WORKS.COM:7025

The following example shows the server network address for a server instance on a computer system named
DBSERVER1 . This system is in the local domain and is unambiguously identified by its system name. The port of
the database mirroring endpoint is 7022 .
TCP://DBSERVER1:7022
Related Tasks
Create a Database Mirroring Endpoint for Windows Authentication (Transact-SQL )

See Also
Database Mirroring (SQL Server)
The Database Mirroring Endpoint (SQL Server)
Establish Database Mirroring Session - Windows
Authentication
6/12/2018 • 5 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse

NOTE
This feature is in maintenance mode and may be removed in a future version of Microsoft SQL Server. Avoid using this
feature in new development work, and plan to modify applications that currently use this feature. Use Always On
availability groups instead.

To establish a database mirroring session and to modify the properties of database mirroring for a database,
use the Mirroring page of the Database Properties dialog box.Before you use the Mirroring page to
configure database mirroring, ensure that the following requirements have been met:
The principal and mirror server instances must be running the same edition of SQL Server—either
Standard or Enterprise. Also, we strongly recommend that they run on comparable systems that can
handle identical workloads.

NOTE
A witness server instance is not available in every edition of Microsoft SQL Server. For a list of features that are
supported by the editions of SQL Server, see Features Supported by the Editions of SQL Server 2016.

The mirror database must exist and be current.


Creating a mirror database requires restoring a recent backup of the principal database (using WITH
NORECOVERY ) on the mirror server instance. It also requires taking one or more log backups after
the full backup and restoring them in sequence to the mirror database (using WITH NORECOVERY ).
For more information, see Prepare a Mirror Database for Mirroring (SQL Server).
If the server instances are running under different domain user accounts, each requires a login in the
master database of the others. If the login does not exist, you must create it before configuring
mirroring. For more information, see Allow Network Access to a Database Mirroring Endpoint Using
Windows Authentication (SQL Server).
To configure database mirroring
1. After connecting to the principal server instance, in Object Explorer, click the server name to expand
the server tree.
2. Expand Databases, and select the database to be mirrored.
3. Right-click the database, select Tasks, and then click Mirror. This opens the Mirroring page of the
Database Properties dialog box.
4. To begin configuring mirroring, click the Configure Security button to launch the Configure
Database Mirroring Security Wizard.
NOTE
During a database mirroring session, you can use this wizard only to add or change the witness server instance.

5. The Configure Database Mirroring Security Wizard automatically creates the database mirroring
endpoint (if none exists) on each server instance, and enters the server network addresses in the field
corresponding to the role of the server instance (Principal, Mirror, or Witness).

IMPORTANT
When creating an endpoint, the Configure Database Mirroring Security Wizard always uses Windows
Authentication. Before you can use the wizard with certificate-based authentication, the mirroring endpoint
must already have been configured to use certificates on each of the server instances. Also, all the fields of the
wizard's Service Accounts dialog box must remain empty. For information about creating a database mirroring
endpoint to use certificates, see CREATE ENDPOINT (Transact-SQL).

6. Optionally, change the operating mode. The availability of certain operating mode(s) depends on
whether you have specified a TCP address for a witness. The options are as follows:

OPTION WITNESS? EXPLANATION

High performance Null (if exists, not used but the To maximize performance, the
(asynchronous) session requires a quorum) mirror database always lags
somewhat behind the principal
database, never quite catching up.
However, the gap between the
databases is typically small. The loss
of a partner has the following
effect:

If the mirror server instance


becomes unavailable, the principal
continues.

If the principal server instance


becomes unavailable, the mirror
stops; but if the session has no
witness (as recommended) or the
witness is connected to the mirror
server, the mirror server is
accessible as a warm standby; the
database owner can force service
to the mirror server instance (with
possible data loss).

For more information, see Role


Switching During a Database
Mirroring Session (SQL Server).
OPTION WITNESS? EXPLANATION

High safety without automatic No All committed transactions are


failover (synchronous) guaranteed to be written to disk on
the mirror server.

Manual failover is possible when


the partners are connected to each
other and the database is
synchronized.

The loss of a partner has the


following effect:

If the mirror server instance


becomes unavailable, the principal
continues.

If the principal server instance


becomes unavailable, the mirror
stops but is accessible as a warm
standby; the database owner can
force service to the mirror server
instance (with possible data loss).

For more information, see Role


Switching During a Database
Mirroring Session (SQL Server).
OPTION WITNESS? EXPLANATION

High safety with automatic Yes (required) All committed transactions are
failover (synchronous) guaranteed to be written to disk on
the mirror server.

Availability is maximized by
including a witness server instance
to support automatic failover. Note
that you can select the High
safety with automatic failover
(synchronous) option only if you
have first specified a witness server
address.

Manual failover is possible when


the partners are connected to each
other and the database is
synchronized.

In the presence of a witness, the


loss of a partner has the following
effect:

If the principal server instance


becomes unavailable, automatic
failover occurs. The mirror server
instance switches to the role of
principal, and it offers its database
as the principal database.

If the mirror server instance


becomes unavailable, the principal
continues.

For more information, see Role


Switching During a Database
Mirroring Session (SQL Server).

** Important *\* If the witness


becomes disconnected, the
partners must be connected to
each other for the database to be
available. For more information, see
Quorum: How a Witness Affects
Database Availability (Database
Mirroring).

7. When all of the following conditions exist, click Start Mirroring to begin mirroring:
You are currently connected to the principal server instance.
Security has been configured correctly.
The fully-qualified TCP addresses of the principal and mirror server instances are specified (in
the Server network addresses section).
If the operating mode is set to High safety with automatic failover (synchronous), the
fully-qualified TCP address of the witness server instance is also specified.
8. After mirroring begins, you can change the operating mode and save the change by clicking OK. Note
that you can switch to high-safety mode with automatic failover only if you have first specified a
witness server address.

NOTE
To remove the witness, delete its server network address from the Witness field. If you switch from high-safety
mode with automatic failover to high-performance mode, the Witness field is automatically cleared.

See Also
Role Switching During a Database Mirroring Session (SQL Server)
Prepare a Mirror Database for Mirroring (SQL Server)
Database Properties (Mirroring Page)
Pause or Resume a Database Mirroring Session (SQL Server)
Set Up a Mirror Database to Use the Trustworthy Property (Transact-SQL )
Remove Database Mirroring (SQL Server)
Management of Logins and Jobs After Role Switching (SQL Server)
Setting Up Database Mirroring (SQL Server)
Manage Metadata When Making a Database Available on Another Server Instance (SQL Server)
Add or Replace a Database Mirroring Witness (SQL Server Management Studio)
Start the Configuring Database Mirroring Security
Wizard
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
The Configure Database Mirroring Security Wizard can be used to initially configure security settings at all or
some server instances involved in mirroring. This wizard works in conjunction with the Mirroring page of the
Database Properties dialog box.
To launch the Configure Database Mirroring Security Wizard
1. After connecting to the principal server instance, in Object Explorer, click the server name to expand the
server tree.
2. Expand Databases, and select the database to be mirrored.
3. Right-click the database, select Tasks, and then click Mirror. This opens the Mirroring Page of the
Database Properties dialog box.
4. Click Configure Security.

See Also
Database Mirroring (SQL Server)
Database Properties (Mirroring Page)
Establish a Database Mirroring Session Using Windows Authentication (SQL Server Management Studio)
Include Witness Server (Configure Database
Mirroring Security Wizard)
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
Use this page to specify whether you want to include a witness server in this security configuration for database
mirroring.
To configure database mirroring by using SQL Server Management Studio
Establish a Database Mirroring Session Using Windows Authentication (SQL Server Management Studio)
Start the Configuring Database Mirroring Security Wizard (SQL Server Management Studio)

Options
Yes
Click to include a witness server instance in the security configuration. The witness is necessary for high-safety
mode with automatic failover, which supports automatic failover to the mirror server instance if the principal server
instance fails.
No
Click to configure security without a witness.

See Also
Database Properties (Mirroring Page)
Database Mirroring (SQL Server)
Database Mirroring Witness
Choose Servers to Configure (Configure Database
Mirroring Security Wizard)
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
Use this page to specify which server instances you want to configure now. You must select at least one server
instance before continuing the wizard.
If you clear the check box for a server instance, the wizard will not make any changes to it. The wizard, however, will
ask you to enter information about that instance and save this information as part of the configuration of the other
server instances. For example, if you clear the check box for the witness server instance, the wizard will ask you to
enter the SQL Server service account of the witness because a login for that account must be created as part of the
security configuration saved at the principal and mirror server instances.
To configure database mirroring by using SQL Server Management Studio
Establish a Database Mirroring Session Using Windows Authentication (SQL Server Management Studio)
Start the Configuring Database Mirroring Security Wizard (SQL Server Management Studio)

Options
Principal server instance
Select to configure security for the principal server.
Mirror server instance
Select to configure security for the mirror server.
Witness server instance
Select to configure security for the witness server (if present).

See Also
Database Properties (Mirroring Page)
Database Mirroring (SQL Server)
Principal Server Instance (Configure Database
Mirroring Security Wizard)
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
Use this page to specify information about the server instance of the principal database. The principal database is
the copy of the database that begins the mirroring session. After the session has begun, the principal database is
the copy of the database that accepts user changes. (When a failover occurs, the principal and mirroring roles are
swapped; therefore, the initial principal database might not remain the principal database.)
To configure database mirroring by using SQL Server Management Studio
Establish a Database Mirroring Session Using Windows Authentication (SQL Server Management Studio)
Start the Configuring Database Mirroring Security Wizard (SQL Server Management Studio)

Options
Principal server instance
Because database mirroring in SQL Server Management Studio is always configured from the principal server, the
current server instance is always the principal server instance.
Listener Port
The behavior of this option depends on whether the mirroring endpoint exists for this server instance, as follows:
If the listener port does not exist for this server instance, port number 5022 is displayed in the Port text box.
You can use any available port number, such as, 7022.
When the mirroring endpoint already exists, the port number from the endpoint is displayed. If you need to
change the port, use an ALTER ENDPOINT command. For more information, see ALTER ENDPOINT
(Transact-SQL ).

NOTE
A port number is required.

Endpoint name
If the mirroring endpoint exists for this server instance, the endpoint name is displayed here. If the endpoint does
not exist, you can specify the name of the endpoint.
Encrypt data sent through this endpoint
By default, encryption is enabled. When enabled, encryption is required (not merely supported) and uses the
default values for all of the encryption options. For more information, see CREATE ENDPOINT (Transact-SQL ).
To disable encryption, clear the check box. To re-enable encryption, select the check box.

See Also
The Database Mirroring Endpoint (SQL Server)
Database Properties (Mirroring Page)
Create a Database Mirroring Endpoint for Windows Authentication (Transact-SQL )
Start Database Mirroring Monitor (SQL Server Management Studio)
Database Mirroring (SQL Server)
Mirror Server Instance (Configure Database Mirroring
Security Wizard)
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
Use this page to specify information about the server instance with the mirror database.

IMPORTANT
The mirror server instance must be running the same edition of SQL Server, either Standard or Enterprise, as the principal
server instance. Also, we strongly recommend that they run on comparable systems that can handle identical workloads.

To configure database mirroring by using SQL Server Management Studio


Establish a Database Mirroring Session Using Windows Authentication (SQL Server Management Studio)
Start the Configuring Database Mirroring Security Wizard (SQL Server Management Studio)

Options
Mirror server instance
If a mirror server instance is already specified (on the Mirroring page of the Database Properties dialog box),
that instance is displayed; for more information, see Database Properties (Mirroring Page).
Otherwise, enter the name of the mirror server instance. Note that the mirror server instance cannot be the same
as the principal server instance.
Connect
If a mirror server instance has not been specified, click Connect. This displays the Connect to Server dialog box
in which you can specify the server instance and establish a connection.
If the instance has been specified, but the wizard lacks a connection with sufficient permission to check for the
existence of the endpoint, click Connect. This displays the Connect to Server dialog box with the server instance
pre-selected and unchangeable. Specify a domain account with sufficient permission, and connect to the server
instance.

NOTE
When connecting to the server instance, the Configure Database Mirroring Security Wizard uses the credentials provided in
the Connect to Server dialog box. These are different from the credentials of a mirroring session, which uses the credentials
of the startup account where the server instance is running as a service.

Listener Port
The behavior of this option depends on whether the mirroring endpoint exists for this server instance, as follows:
If a listener port does not exist for the server instance, port number 5022 is displayed in the Port text box.
You can use any available port number, such as 7022.
When the mirroring endpoint already exists, the port number from that endpoint is displayed. If you need to
change the port, use an ALTER ENDPOINT command. For more information, see ALTER ENDPOINT
(Transact-SQL ).

NOTE
A port number is required.

Endpoint name
If the mirroring endpoint exists for this server instance, the endpoint name is displayed here. If the endpoint
does not exist, you can specify the name of the endpoint.
Encrypt data sent through this endpoint
By default, encryption is enabled. When enabled, encryption is required (not merely supported) and uses the
default values for all of the encryption options. For more information, see CREATE ENDPOINT (Transact-
SQL ).
To disable encryption, clear the check box. To re-enable encryption, select the check box.

See Also
The Database Mirroring Endpoint (SQL Server)
Database Properties (Mirroring Page)
Create a Database Mirroring Endpoint for Windows Authentication (Transact-SQL )
Start Database Mirroring Monitor (SQL Server Management Studio)
Database Mirroring (SQL Server)
Witness Server Instance (Configure Database
Mirroring Security Wizard)
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
Use this page to specify information about the server instance that is to serve as the witness for the session.

NOTE
A witness server instance is not available in every edition of Microsoft SQL Server. For a list of features that are supported by
the editions of SQL Server, see Features Supported by the Editions of SQL Server 2016.

To configure database mirroring by using SQL Server Management Studio


Establish a Database Mirroring Session Using Windows Authentication (SQL Server Management Studio)
Start the Configuring Database Mirroring Security Wizard (SQL Server Management Studio)

Options
Witness server instance
If a witness server instance is already specified (on the Mirroring page of the Database Properties dialog box),
that instance is displayed (for more information, see Database Properties (Mirroring Page)).
Otherwise, this list box displays the name of the current server. Be aware that the witness server instance cannot be
the same as the principal or mirror server instances.
Connect
If a witness server instance has not been specified, click Connect. This displays the Connect to Server dialog box
in which you can specify the server instance and establish a connection.
If the instance has been specified, but the wizard lacks a connection with sufficient permission to check for the
existence of the endpoint, click Connect. This displays the Connect to Server dialog box with the server instance
pre-selected and unchangeable. Specify a domain account with sufficient permission, and connect to the server
instance.

NOTE
When connecting to the server instance, the Configure Database Mirroring Security Wizard uses the credentials provided in
the Connect to Server dialog box. These are different from the credentials of a mirroring session, which uses the credentials
of the startup account where the server instance is running as a service.

Listener Port
The behavior of this option depends on whether the mirroring endpoint exists for this server instance, as follows:
If the listener port does not exist for the server instance, port number 5022 is displayed in the Port text box.
You can enter any available port number, such as, 7022.
When the mirroring endpoint already exists, the port number from the endpoint is displayed. If you need to
change that port, use an ALTER ENDPOINT statement. For more information, see ALTER ENDPOINT
(Transact-SQL ).

NOTE
A port number is required.

Endpoint name
If the mirroring endpoint exists for this server instance, the endpoint name is displayed here. If the endpoint
does not exist, you can specify the name of the endpoint.
Encrypt data sent through this endpoint
By default, encryption is enabled. When enabled, encryption is required (not merely supported) and uses the
default values for all of the encryption options. For more information, see CREATE ENDPOINT (Transact-
SQL ).
To disable encryption, clear the check box. To re-enable encryption, select the check box.

See Also
The Database Mirroring Endpoint (SQL Server)
Database Properties (Mirroring Page)
Create a Database Mirroring Endpoint for Windows Authentication (Transact-SQL )
Start Database Mirroring Monitor (SQL Server Management Studio)
Database Mirroring (SQL Server)
Database Mirroring Witness
Service Accounts (Configure Database Mirroring
Security Wizard)
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
When using Windows Authentication, if the server instances use different accounts, specify the service accounts for
SQL Server. These service accounts must all be domain accounts (in the same or trusted domains).
If all the server instances use the same domain account or use certificate-based authentication, leave the fields
blank. Simply click Finish, and the wizard automatically configures the accounts based on the account of the
current wizard.

IMPORTANT
If the database mirroring endpoints of the server instances are configured to use certificates, you must leave the service
account fields empty.

To configure database mirroring by using SQL Server Management Studio


Establish a Database Mirroring Session Using Windows Authentication (SQL Server Management Studio)
Start the Configuring Database Mirroring Security Wizard (SQL Server Management Studio)

Options
Principal
Specify the service account of the principal server instance. Enter the domain name in upper case:
DOMAINNAME\username
Mirror
Specify the service account of the mirror server instance. Enter the domain name in upper case:
DOMAINNAME\username
Witness
Specify the service account of the witness server instance. Enter the domain name in upper case:
DOMAINNAME\username

See Also
Database Properties (Mirroring Page)
Start Database Mirroring Monitor (SQL Server Management Studio)
Database Mirroring (SQL Server)
Set Up Login Accounts for Database Mirroring or Always On Availability Groups (SQL Server)
Database Mirroring - Establish Session - Windows
Authentication
6/12/2018 • 8 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse

NOTE
This feature is in maintenance mode and may be removed in a future version of Microsoft SQL Server. Avoid using this
feature in new development work, and plan to modify applications that currently use this feature. Use Always On
availability groups instead.

After the mirror database is prepared (see Prepare a Mirror Database for Mirroring (SQL Server)), you can
establish a database mirroring session. The principal, mirror, and witness server instances must be separate
server instances, which should be on separate host systems.

IMPORTANT
We recommend that you configure database mirroring during off-peak hours because configuring mirroring can impact
performance.

NOTE
A given server instance can participate in multiple concurrent database mirroring sessions with the same or different
partners. A server instance can be a partner in some sessions and a witness in other sessions. The mirror server instance
must be running the same edition of SQL Server as the principal server instance. Database mirroring is not available in
every edition of Microsoft SQL Server. For a list of features that are supported by the editions of SQL Server, see Features
Supported by the Editions of SQL Server 2016. Also, we strongly recommend that they run on comparable systems that
can handle identical workloads.

To establish a database mirroring session


1. Create the mirror database. For more information, see Prepare a Mirror Database for Mirroring (SQL
Server).
2. Set up security on each server instance.
Each server instance in a database mirroring session requires a database mirroring endpoint. If the
endpoint does not exist, you must create it.

NOTE
The form of authentication used for database mirroring by a server instance is a property of its database mirroring
endpoint. Two types of transport security are available for database mirroring: Windows Authentication or
certificate-based authentication. For more information, see Transport Security for Database Mirroring and Always
On Availability Groups (SQL Server).

On each partner server, ensure that an endpoint exists for database mirroring. Regardless of the number
of mirroring sessions to be supported, the server instance can have only one database mirroring
endpoint. If you intend to use this server instance exclusively for partners in database mirroring sessions,
you can assign the role of partner to the endpoint (ROLE=PARTNER ). If you intend also to use this server
for the witness in other database mirroring sessions, assign the role of the endpoint as ALL.
To execute a SET PARTNER statement, the STATE of the endpoints of both partners must be set to
STARTED.
To learn whether a server instance has a database mirroring endpoint and to learn its role and state, on
that instance, use the following Transact-SQL statement:

SELECT role_desc, state_desc FROM sys.database_mirroring_endpoints

IMPORTANT
Do not reconfigure an in-use database mirroring endpoint. If a database mirroring endpoint exists and is already in
use, we recommend that you use that endpoint for every session on the server instance. Dropping an in-use
endpoint can cause the endpoint to restart, disrupting the connections of the existing sessions, which can appear
to be an error to the other server instances. This is particularly important in high-safety mode with automatic
failover, in which reconfiguring the endpoint on a partner could cause a failover to occur. Also, if a witness has been
set for a session, dropping the database mirroring endpoint can cause the principal server of that session to lose
quorum; if that occurs, the database is taken offline and its users are disconnected. For more information, see
Quorum: How a Witness Affects Database Availability (Database Mirroring).

If either partner lacks an endpoint, see Create a Database Mirroring Endpoint for Windows
Authentication (Transact-SQL ).
3. If server instances are running under different domain user accounts, each requires a login in the master
database of the others. If the login does not exist, you must create it. For more information, see Allow
Network Access to a Database Mirroring Endpoint Using Windows Authentication (SQL Server).
4. To set the principal server as partner on the mirror database, connect to the mirror server, and issue the
following statement:
ALTER DATABASE <database_name> SET PARTNER =<server_network_address>
where <database_name> is the name of the database to be mirrored (this name is the same on both
partners), and <server_network_address> is the server network address of the principal server.
The syntax for a server network address is as follows:
TCP://<system -address>:<port>
where <system -address> is a string that unambiguously identifies the destination computer system, and
<port> is the port number used by the mirroring endpoint of the partner server instance. For more
information, see Specify a Server Network Address (Database Mirroring).
For example, on the mirror server instance, the following ALTER DATABASE statement sets the partner as
the original principal server instance. The database name is AdventureWorks, the system address is
DBSERVER1—the name of the partner's system—and the port used by the partner's database mirroring
endpoint is 7022:

ALTER DATABASE AdventureWorks


SET PARTNER = 'TCP://DBSERVER1:7022'

This statement prepares the mirror server to form a session when it is contacted by the principal server.
5. To set the mirror server as partner on the principal database, connect to the principal server, and issue the
following statement:
ALTER DATABASE <database_name> SET PARTNER =<server_network_address>
For more information, see step 4.
For example, on the principal server instance, the following ALTER DATABASE statement sets the partner
as the original mirror server instance. The database name is AdventureWorks, the system address is
DBSERVER2—the name of the partner's system—and the port used by the partner's database mirroring
endpoint is 7025:

ALTER DATABASE AdventureWorks SET PARTNER = 'TCP://DBSERVER2:7022'

Entering this statement on the principal server begins the database mirroring session.
6. By default a session is set to full transaction safety (SAFETY is set to FULL ), which starts the session in
synchronous, high-safety mode without automatic failover. You can reconfigure the session to run in high-
safety mode with automatic failover or in asynchronous, high-performance mode, as follows:
High-safety mode with automatic failover
If you want a high-safety mode session to support automatic failover, add a witness server
instance. For more information, see Add a Database Mirroring Witness Using Windows
Authentication (Transact-SQL ).
High-performance mode
Alternatively, if you do not want automatic failover and you prefer to emphasize performance over
availability, turn off transaction safety. For more information, see Change Transaction Safety in a
Database Mirroring Session (Transact-SQL ).

NOTE
In high-performance mode, WITNESS should be set to OFF. For more information, see Quorum: How a
Witness Affects Database Availability (Database Mirroring).

Example
NOTE
The following example establishes a database mirroring session between partners for an existing mirror database. For
information on creating a mirror database, see Prepare a Mirror Database for Mirroring (SQL Server)=.

The example shows the basic steps for creating a database mirroring session without a witness. The two partners
are the default server instances on two computer systems (PARTNERHOST1 and PARTNERHOST5). The two
partner instances run the same Windows domain user account (MYDOMAIN\dbousername).
1. On the principal server instance (default instance on PARTNERHOST1), create an endpoint that supports
all roles using port 7022:
--create an endpoint for this instance
CREATE ENDPOINT Endpoint_Mirroring
STATE=STARTED
AS TCP (LISTENER_PORT=7022)
FOR DATABASE_MIRRORING (ROLE=ALL)
GO
--Partners under same domain user; login already exists in master.

NOTE
For an example of how to setup a login, see Allow Network Access to a Database Mirroring Endpoint Using
Windows Authentication (SQL Server).

2. On the mirror server instance (default instance on PARTNERHOST5), create an endpoint that supports all
roles using port 7022:

--create an endpoint for this instance


CREATE ENDPOINT Endpoint_Mirroring
STATE=STARTED
AS TCP (LISTENER_PORT=7022)
FOR DATABASE_MIRRORING (ROLE=ALL)
GO
--Partners under same domain user; login already exists in master.

3. On the principal server instance (on PARTNERHOST1), back up the database:

BACKUP DATABASE AdventureWorks


TO DISK = 'C:\AdvWorks_dbmirror.bak'
WITH FORMAT
GO

4. On the mirror server instance (on PARTNERHOST5 ), restore the database:

RESTORE DATABASE AdventureWorks


FROM DISK = 'Z:\AdvWorks_dbmirror.bak'
WITH NORECOVERY
GO

5. After you create the full database backup, you must create a log backup on the principal database. For
example, the following Transact-SQL statement backs up the log to the same file used by the preceding
database backup:

BACKUP LOG AdventureWorks


TO DISK = 'C:\AdventureWorks.bak'
GO

6. Before you can start mirroring, you must apply the required log backup (and any subsequent log
backups).
For example, the following Transact-SQL statement restores the first log from C:\AdventureWorks.bak:
RESTORE LOG AdventureWorks
FROM DISK = 'C:\ AdventureWorks.bak'
WITH FILE=1, NORECOVERY
GO

7. On the mirror server instance, set the server instance on PARTNERHOST1 as the partner (making it the
initial principal server):

USE master;
GO
ALTER DATABASE AdventureWorks
SET PARTNER =
'TCP://PARTNERHOST1:7022'
GO

IMPORTANT
default, a database mirroring session runs in synchronous mode, which depends on having full transaction safety
(SAFETY is set to FULL). To cause a session to run in asynchronous, high-performance mode, set SAFETY to OFF.
For more information, see Database Mirroring Operating Modes.

8. On the principal server instance, set the server instance on PARTNERHOST5 as the partner (making it the
initial mirror server):

USE master;
GO
ALTER DATABASE AdventureWorks
SET PARTNER = 'TCP://PARTNERHOST5:7022'
GO

9. Optionally, if you intend to use high-safety mode with automatic failover, set up the witness server
instance. For more information, see Add a Database Mirroring Witness Using Windows Authentication
(Transact-SQL ).

NOTE
For a complete example showing security setup, preparing the mirror database, setting up the partners, and adding a
witness, see Setting Up Database Mirroring (SQL Server).

See Also
Setting Up Database Mirroring (SQL Server)
ALTER DATABASE (Transact-SQL )
Allow Network Access to a Database Mirroring Endpoint Using Windows Authentication (SQL Server)
Prepare a Mirror Database for Mirroring (SQL Server)
Create a Database Mirroring Endpoint for Windows Authentication (Transact-SQL )
Database Mirroring and Log Shipping (SQL Server)
Database Mirroring (SQL Server)
Database Mirroring and Replication (SQL Server)
Setting Up Database Mirroring (SQL Server)
Specify a Server Network Address (Database Mirroring)
Database Mirroring Operating Modes
Example: Setting Up Database Mirroring Using
Windows Authentication (Transact-SQL)
6/12/2018 • 3 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
This example shows all the stages required to create a database mirroring session with a witness using Windows
Authentication. The examples in this topic use Transact-SQL. Note that as an alternative to using Transact-SQL
steps, you can use the Configure Database Mirroring Security Wizard for database mirroring setup. For more
information, see Establish a Database Mirroring Session Using Windows Authentication (SQL Server
Management Studio).

Prerequisite
The example uses the AdventureWorks sample database, which uses the simple recovery model by default. To
use database mirroring with this database, you must alter it to use the full recovery model. To do this in Transact-
SQL, use the ALTER DATABASE statement, as follows:

USE master;
GO
ALTER DATABASE AdventureWorks
SET RECOVERY FULL;
GO

For information on changing the recovery model in SQL Server Management Studio, see View or Change the
Recovery Model of a Database (SQL Server).
Permissions
Requires ALTER permission on the database and CREATE ENDPOINT permission, or membership in the
sysadmin fixed server role.

Example
In this example, the two partners and the witness are the default server instances on three computer systems. The
three server instances run the same Windows domain, but the user account (used as the startup service account)
is different for the example's witness server instance.
The following table summarizes the values used in this example.

INITIAL MIRRORING ROLE HOST SYSTEM DOMAIN USER ACCOUNT

Principal PARTNERHOST1 <Mydomain>\<dbousername>

Mirror PARTNERHOST5 <Mydomain>\<dbousername>

Witness WITNESSHOST4 <Somedomain>\<witnessuser>

1. Create an endpoint on the principal server instance (default instance on PARTNERHOST1).


CREATE ENDPOINT Endpoint_Mirroring
STATE=STARTED
AS TCP (LISTENER_PORT=7022)
FOR DATABASE_MIRRORING (ROLE=PARTNER)
GO
--Partners under same domain user; login already exists in master.
--Create a login for the witness server instance,
--which is running as Somedomain\witnessuser:
USE master ;
GO
CREATE LOGIN [Somedomain\witnessuser] FROM WINDOWS ;
GO
-- Grant connect permissions on endpoint to login account of witness.
GRANT CONNECT ON ENDPOINT::Endpoint_Mirroring TO [Somedomain\witnessuser];
--Grant connect permissions on endpoint to login account of partners.
GRANT CONNECT ON ENDPOINT::Endpoint_Mirroring TO [Mydomain\dbousername];
GO

2. Create an endpoint on the mirror server instance (default instance on PARTNERHOST5).

CREATE ENDPOINT Endpoint_Mirroring


STATE=STARTED
AS TCP (LISTENER_PORT=7022)
FOR DATABASE_MIRRORING (ROLE=ALL)
GO
--Partners under same domain user; login already exists in master.
--Create a login for the witness server instance,
--which is running as Somedomain\witnessuser:
USE master ;
GO
CREATE LOGIN [Somedomain\witnessuser] FROM WINDOWS ;
GO
--Grant connect permissions on endpoint to login account of witness.
GRANT CONNECT ON ENDPOINT::Endpoint_Mirroring TO [Somedomain\witnessuser];
--Grant connect permissions on endpoint to login account of partners.
GRANT CONNECT ON ENDPOINT::Endpoint_Mirroring TO [Mydomain\dbousername];
GO

3. Create an endpoint on the witness server instance (default instance on WITNESSHOST4).

CREATE ENDPOINT Endpoint_Mirroring


STATE=STARTED
AS TCP (LISTENER_PORT=7022)
FOR DATABASE_MIRRORING (ROLE=WITNESS)
GO
--Create a login for the partner server instances,
--which are both running as Mydomain\dbousername:
USE master ;
GO
CREATE LOGIN [Mydomain\dbousername] FROM WINDOWS ;
GO
--Grant connect permissions on endpoint to login account of partners.
GRANT CONNECT ON ENDPOINT::Endpoint_Mirroring TO [Mydomain\dbousername];
GO

4. Create the mirror database. For more information, see Prepare a Mirror Database for Mirroring (SQL
Server).
5. On the mirror server instance on PARTNERHOST5, set the server instance on PARTNERHOST1 as the
partner (making it the initial principal server instance).
ALTER DATABASE AdventureWorks
SET PARTNER =
'TCP://PARTNERHOST1.COM:7022'
GO

6. On the principal server instance on PARTNERHOST1, set the server instance on PARTNERHOST5 as the
partner (making it the initial mirror server instance).

ALTER DATABASE AdventureWorks


SET PARTNER = 'TCP://PARTNERHOST5.COM:7022'
GO

7. On the principal server, set the witness (which is on WITNESSHOST4).

ALTER DATABASE AdventureWorks


SET WITNESS =
'TCP://WITNESSHOST4.COM:7022'
GO

Related Tasks
Prepare a Mirror Database for Mirroring (SQL Server)
Start the Configuring Database Mirroring Security Wizard (SQL Server Management Studio)
Set Up a Mirror Database to Use the Trustworthy Property (Transact-SQL )
Allow a Database Mirroring Endpoint to Use Certificates for Outbound Connections (Transact-SQL )
Allow a Database Mirroring Endpoint to Use Certificates for Inbound Connections (Transact-SQL )
Example: Setting Up Database Mirroring Using Certificates (Transact-SQL )

See Also
ALTER DATABASE (Transact-SQL )
The Database Mirroring Endpoint (SQL Server)
Transport Security for Database Mirroring and Always On Availability Groups (SQL Server)
Manage Metadata When Making a Database Available on Another Server Instance (SQL Server)
Security Center for SQL Server Database Engine and Azure SQL Database
Example: Setting Up Database Mirroring Using
Certificates (Transact-SQL)
6/12/2018 • 5 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
This example shows all the stages required to create a database mirroring session using certificate-based
authentication. The examples in this topic use Transact-SQL. Unless you can guarantee that your network is
secure, we recommend that you use encryption for database mirroring connections.
When copying a certificate to another system, use a secure copy method. Be extremely careful to keep all of your
certificates secure.

Example
The following example demonstrates what must be done on one partner that resides on HOST_A. In this
example, the two partners are the default server instances on three computer systems. The two server instances
run in nontrusted Windows domains, so certificate-based authentication is required.
The initial principal role is taken by HOST_A, and the mirror role is taken by HOST_B.
Setting up database mirroring using certificates involves four general stages, of which three stages—1, 2, and 4—
are demonstrated by this example. These stages are as follows:
1. Configuring Outbound Connections
This example shows the steps for:
a. Configuring Host_A for outbound connections.
b. Configuring Host_B for outbound connections.
For information about this stage of setting up database mirroring, see Allow a Database Mirroring
Endpoint to Use Certificates for Outbound Connections (Transact-SQL ).
2. Configuring Inbound Connections
This example shows the steps for:
a. Configuring Host_A for inbound connections.
b. Configuring Host_B for inbound connections.
For information about this stage of setting up database mirroring, see Allow a Database Mirroring
Endpoint to Use Certificates for Inbound Connections (Transact-SQL ).
3. Creating the Mirror Database
For information on how to create a mirror database, see Prepare a Mirror Database for Mirroring (SQL
Server).
4. Configuring the Mirroring Partners
Configuring Outbound Connections
To configure Host_A for outbound connections
1. On the master database, create the database master key, if needed.

USE master;
CREATE MASTER KEY ENCRYPTION BY PASSWORD = '<1_Strong_Password!>';
GO

2. Make a certificate for this server instance.

USE master;
CREATE CERTIFICATE HOST_A_cert
WITH SUBJECT = 'HOST_A certificate';
GO

3. Create a mirroring endpoint for server instance using the certificate.

CREATE ENDPOINT Endpoint_Mirroring


STATE = STARTED
AS TCP (
LISTENER_PORT=7024
, LISTENER_IP = ALL
)
FOR DATABASE_MIRRORING (
AUTHENTICATION = CERTIFICATE HOST_A_cert
, ENCRYPTION = REQUIRED ALGORITHM AES
, ROLE = ALL
);
GO

4. Back up the HOST_A certificate, and copy it to other system, HOST_B.

BACKUP CERTIFICATE HOST_A_cert TO FILE = 'C:\HOST_A_cert.cer';


GO

5. Using any secure copy method, copy C:\HOST_A_cert.cer to HOST_B.


To configure Host_B for outbound connections
6. On the master database, create the database master key, if needed.

USE master;
CREATE MASTER KEY ENCRYPTION BY PASSWORD = '<Strong_Password_#2>';
GO

7. Make a certificate on the HOST_B server instance.

CREATE CERTIFICATE HOST_B_cert


WITH SUBJECT = 'HOST_B certificate for database mirroring';
GO

8. Create a mirroring endpoint for the server instance on HOST_B.


CREATE ENDPOINT Endpoint_Mirroring
STATE = STARTED
AS TCP (
LISTENER_PORT=7024
, LISTENER_IP = ALL
)
FOR DATABASE_MIRRORING (
AUTHENTICATION = CERTIFICATE HOST_B_cert
, ENCRYPTION = REQUIRED ALGORITHM AES
, ROLE = ALL
);
GO

9. Back up HOST_B certificate.

BACKUP CERTIFICATE HOST_B_cert TO FILE = 'C:\HOST_B_cert.cer';


GO

10. Using any secure copy method, copy C:\HOST_B_cert.cer to HOST_A.


For more information, see Allow a Database Mirroring Endpoint to Use Certificates for Outbound
Connections (Transact-SQL ).
[Top of Example]
Configuring Inbound Connections
To configure Host_A for inbound connections
1. Create a login on HOST_A for HOST_B.

USE master;
CREATE LOGIN HOST_B_login WITH PASSWORD = '1Sample_Strong_Password!@#';
GO

2. --Create a user for that login.

CREATE USER HOST_B_user FOR LOGIN HOST_B_login;


GO

3. --Associate the certificate with the user.

CREATE CERTIFICATE HOST_B_cert


AUTHORIZATION HOST_B_user
FROM FILE = 'C:\HOST_B_cert.cer'
GO

4. Grant CONNECT permission on the login for the remote mirroring endpoint.

GRANT CONNECT ON ENDPOINT::Endpoint_Mirroring TO [HOST_B_login];


GO

To configure Host_B for inbound connections


5. Create a login on HOST_B for HOST_A.
USE master;
CREATE LOGIN HOST_A_login WITH PASSWORD = '=Sample#2_Strong_Password2';
GO

6. Create a user for that login.

CREATE USER HOST_A_user FOR LOGIN HOST_A_login;


GO

7. Associate the certificate with the user.

CREATE CERTIFICATE HOST_A_cert


AUTHORIZATION HOST_A_user
FROM FILE = 'C:\HOST_A_cert.cer'
GO

8. Grant CONNECT permission on the login for the remote mirroring endpoint.

GRANT CONNECT ON ENDPOINT::Endpoint_Mirroring TO [HOST_A_login];


GO

IMPORTANT
If you intend to run in high-safety mode with automatic failover, you must repeat the same setup steps to configure the
witness for outbound and inbound connections. Setting up the inbound connections when a witness is involved requires
that you set up logins and users for the witness on both of the partners and for both partners on the witness.

For more information, see Allow a Database Mirroring Endpoint to Use Certificates for Inbound Connections
(Transact-SQL ).
[Top of Example]
Creating the Mirror Database
For information on how to create a mirror database, see Prepare a Mirror Database for Mirroring (SQL Server).
Configuring the Mirroring Partners
1. On the mirror server instance on HOST_B, set the server instance on HOST_A as the partner (making it
the initial principal server instance). Substitute a valid network address for
TCP://HOST_A.Mydomain.Corp.Adventure-Works``.com:7024 . For more information, see Specify a Server
Network Address (Database Mirroring).

--At HOST_B, set server instance on HOST_A as partner (principal server):


ALTER DATABASE AdventureWorks
SET PARTNER = 'TCP://HOST_A.Mydomain.Corp.Adventure-Works.com:7024';
GO

2. On the principal server instance on HOST_A, set the server instance on HOST_B as the partner (making it
the initial mirror server instance). Substitute a valid network address for
TCP://HOST_B.Mydomain.Corp.Adventure-Works.com:7024 .
--At HOST_A, set server instance on HOST_B as partner (mirror server).
ALTER DATABASE AdventureWorks
SET PARTNER = 'TCP://HOST_B.Mydomain.Corp.Adventure-Works.com:7024';
GO

3. This example assumes that the session will be running in high-performance mode. To configure this
session for high-performance mode, on the principal server instance (on HOST_A), set transaction safety
to OFF.

--Change to high-performance mode by turning off transacton safety.


ALTER DATABASE AdventureWorks
SET PARTNER SAFETY OFF
GO

NOTE
If you intend to run in high-safety mode with automatic failover, leave transaction safety set to FULL (the default
setting) and add the witness as soon as possible after executing the second SET PARTNER 'partner_server'
statement. Note that the witness must first be configured for outbound and inbound connections.

[Top of Example]

Related Tasks
Prepare a Mirror Database for Mirroring (SQL Server)
Allow a Database Mirroring Endpoint to Use Certificates for Inbound Connections (Transact-SQL )
Allow a Database Mirroring Endpoint to Use Certificates for Outbound Connections (Transact-SQL )
Management of Logins and Jobs After Role Switching (SQL Server)
Manage Metadata When Making a Database Available on Another Server Instance (SQL Server) (SQL
Server)
Troubleshoot Database Mirroring Configuration (SQL Server)

See Also
Transport Security for Database Mirroring and Always On Availability Groups (SQL Server)
Specify a Server Network Address (Database Mirroring)
The Database Mirroring Endpoint (SQL Server)
Use Certificates for a Database Mirroring Endpoint (Transact-SQL )
ALTER DATABASE (Transact-SQL )
Security Center for SQL Server Database Engine and Azure SQL Database
Troubleshoot Database Mirroring Configuration
(SQL Server)
6/12/2018 • 7 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
This topic provides information to help you troubleshoot problems in setting up a database mirroring session.

NOTE
Ensure that you are meeting all the prerequisites for database mirroring.

ISSUE SUMMARY

Error Message 1418 This SQL Server message indicates that the server network
address cannot be reached or does not exist, and it suggests
that you verify the network address name and reissue the
command.

Accounts Discusses requirements for correctly configuring the


accounts under which SQL Server is running.

Endpoints Discusses requirements for correctly configuring the


database mirroring endpoint of each server instance.

SystemAddress Summarizes the alternatives for specifying the system name


of a server instance in a database mirroring configuration.

Network access Documents the requirement that each the server instance be
able to access the ports of the other server instance or
instances over TCP.

Mirror database preparation Summarizes the requirements for preparing the mirror
database to enable mirroring to start.

Failed create-file operation Describes how to respond to a failed create-file operation.

Starting mirroring by Using Transact-SQL Describes the required order for ALTER DATABASE
database_name SET PARTNER ='partner_server' statements.

Cross-Database Transactions An automatic failover could lead to automatic and possibly


incorrect resolution of in-doubt transactions. For this reason
database mirroring does not support cross-database
transactions.

Accounts
The accounts under which SQL Server is running must be correctly configured.
1. Do the accounts have the correct permissions?
a. If the accounts are running in the same domain accounts, the chances of misconfiguration are
reduced.
b. If the accounts are running in different domains or are not domain accounts, the login of one
account must be created in master on the other computer, and that login must be granted
CONNECT permissions on the endpoint. For more information, see Manage Metadata When
Making a Database Available on Another Server Instance (SQL Server). This includes the Network
Service account.
2. If SQL Server is running as a service that is using the local system account, you must use certificates for
authentication. For more information, see Use Certificates for a Database Mirroring Endpoint (Transact-
SQL ).

Endpoints
Endpoints must be correctly configured.
1. Make sure that each server instance (the principal server, mirror server, and witness, if any) has a
database mirroring endpoint. For more information, see sys.database_mirroring_endpoints (Transact-
SQL ) and, depending on the form of authentication, either Create a Database Mirroring Endpoint for
Windows Authentication (Transact-SQL ) or Use Certificates for a Database Mirroring Endpoint (Transact-
SQL ).
2. Check that the port numbers are correct.
To identify the port currently associated with database mirroring endpoint of a server instance, use the
sys.database_mirroring_endpoints and sys.tcp_endpoints catalog views.
3. For database mirroring setup issues that are difficult to explain, we recommend that you inspect each
server instance to determine whether it is listening on the correct ports.
4. Make sure that the endpoints are started (STATE=STARTED ). On each server instance, use the following
Transact-SQL statement.

SELECT state_desc FROM sys.database_mirroring_endpoints

For more information about the state_desc column, see sys.database_mirroring_endpoints (Transact-
SQL ).
To start an endpoint, use the following Transact-SQL statement.

ALTER ENDPOINT Endpoint_Mirroring


STATE = STARTED
AS TCP (LISTENER_PORT = <port_number>)
FOR database_mirroring (ROLE = ALL);
GO

For more information, see ALTER ENDPOINT (Transact-SQL ).


5. Check that the ROLE is correct. On each server instance use the following Transact-SQL statement.

SELECT role FROM sys.database_mirroring_endpoints;


GO

For more information, see sys.database_mirroring_endpoints (Transact-SQL ).


6. The login for the service account from the other server instance requires CONNECT permission. Make
sure that the login from the other server has CONNECT permission. To determine who has CONNECT
permission for an endpoint, on each server instance use the following Transact-SQL statement.

SELECT 'Metadata Check';


SELECT EP.name, SP.STATE,
CONVERT(nvarchar(38), suser_name(SP.grantor_principal_id))
AS GRANTOR,
SP.TYPE AS PERMISSION,
CONVERT(nvarchar(46),suser_name(SP.grantee_principal_id))
AS GRANTEE
FROM sys.server_permissions SP , sys.endpoints EP
WHERE SP.major_id = EP.endpoint_id
ORDER BY Permission,grantor, grantee;
GO

System Address
For the system name of a server instance in a database mirroring configuration, you can use any name that
unambiguously identifies the system. The server address can be a system name (if the systems are in the same
domain), a fully qualified domain name, or an IP address (preferably, a static IP address). Using the fully qualified
domain name is guaranteed to work. For more information, see Specify a Server Network Address (Database
Mirroring).

Network Access
Each server instance must be able to access the ports of the other server instance or instances over TCP. This is
especially important if the server instances are in different domains that do not trust each other (untrusted
domains). This restricts much of the communication between the server instances.

Mirror Database Preparation


Whether starting mirroring for the first time or starting it again after mirroring was removed, verify that the
mirror database is prepared for mirroring.
When you create the mirror database on the mirror server, make sure that you restore the backup of the
principal database specifying the same database name WITH NORECOVERY. Also, all log backups created after
that backup was taken must also be applied, again WITH NORECOVERY.
Also, we recommend that, if it is possible, the file path (including the drive letter) of the mirror database be
identical to the path of the principal database. If the file paths must differ, for example, if the principal database is
on drive 'F:' but the mirror system lacks an F: drive, you must include the MOVE option in the RESTORE
statement.

IMPORTANT
If you move the database files when you are creating the mirror database, you might be unable to add files to the
database later without mirroring being suspended.

If database mirroring has been stopped, all subsequent log backups taken on the principal database must be
applied to the mirror database before mirroring can be restarted.
For more information, see Prepare a Mirror Database for Mirroring (SQL Server).

Failed Create-File Operation


Adding a file without impacting a mirroring session requires that the path of the file exist on both servers.
Therefore, if you move the database files when creating the mirror database, a later add-file operation might fail
on the mirror database and cause mirroring to be suspended.
To fix the problem:
1. The database owner must remove the mirroring session and restore a full backup of the filegroup that
contains the added file.
2. The owner must then back up the log containing the add-file operation on the principal server and
manually restore the log backup on the mirror database using the WITH NORECOVERY and WITH
MOVE options. Doing this creates the specified file path on the mirror server and restores the new file to
that location.
3. To prepare the database for a new mirroring session, the owner must also restore WITH NO RECOVERY
any other outstanding log backups from the principal server.
For more information, see Removing Database Mirroring (SQL Server), Prepare a Mirror Database for
Mirroring (SQL Server), Establish a Database Mirroring Session Using Windows Authentication
(Transact-SQL ), Use Certificates for a Database Mirroring Endpoint (Transact-SQL ), or Establish a
Database Mirroring Session Using Windows Authentication (SQL Server Management Studio).

Starting mirroring by Using Transact-SQL


The order in which the ALTER DATABASE database_name SET PARTNER ='partner_server' statements are
issued is very important.
1. The first statement must be run on the mirror server. When this statement is issued, the mirror server
does not try to contact any other server instance. Instead, the mirror server instructs its database to wait
until the mirror server has been contacted by the principal server.
2. The second ALTER DATABASE statement must be run on the principal server. This statement causes the
principal server to try to connect to the mirror server. After that connection is created, the mirror then
tries to connect to the principal server on another connection.
For more information, see ALTER DATABASE (Transact-SQL ).

NOTE
For information about using SQL Server Management Studio to start mirroring, see Establish a Database Mirroring
Session Using Windows Authentication (SQL Server Management Studio).

Cross-Database Transactions
When a database is being mirrored in high-safety mode with automatic failover, an automatic failover could lead
to automatic and possibly incorrect resolution of in-doubt transactions. If an automatic failover occurs on either
database while a cross-database transaction is being committed, logical inconsistencies can occur between the
databases.
The types of cross-database transactions that can be affected by an automatic failover include the following:
A transaction that is updating multiple databases in the same instance of SQL Server.
Transactions that use a Microsoft Distributed Transaction Coordinator (MS DTC ).
For more information, see Cross-Database Transactions and Distributed Transactions for Always On
Availability Groups and Database Mirroring (SQL Server).
See Also
Setting Up Database Mirroring (SQL Server)
Transport Security for Database Mirroring and Always On Availability Groups (SQL Server)
Connect Clients to a Database Mirroring Session
(SQL Server)
6/12/2018 • 17 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
To connect to a database mirroring session, a client can use either SQL Server Native Client or .NET Framework
Data Provider for SQL Server. When configured for a SQL Server 2017 database, these data access providers
both fully support database mirroring. For information about programming considerations for using a mirrored
database, see Using Database Mirroring. In addition, the current principal server instance must be available and
the login of the client must have been created on the server instance. For more information, see Troubleshoot
Orphaned Users (SQL Server). Client connections to a database mirroring session do not involve the witness
server instance, if one exists.

Making the Initial Connection to a Database Mirroring Session


For the initial connection to a mirrored database, a client must supply a connection string that minimally supplies
the name of a server instance. This required server name should identify the current principal server instance and
is known as the initial partner name.
Optionally, the connection string can also supply the name of another server instance, which should identify the
current mirror server instance, for use if the initial partner is unavailable during the first connection attempt. The
second name is known as the failover partner name.
The connection string must also supply a database name. This is necessary to enable failover attempts by the data
access provider.
On receiving a connection string, the data access provider stores the initial partner name and the failover partner
name, if supplied, in a cache in the client's volatile memory (for managed code, the cache is scoped to the
application domain). Once cached, the initial partner name is never updated by the data access provider. When
the client supplies the failover partner name, the data access provider also stores this failover partner name
temporarily in case the provider cannot connect using the initial partner name.
A database mirroring session does not protect against server-access problems that are specific to clients, such as
when a client computer is having a problems communicating with the network. A connection attempt to a
mirrored database can also fail for a variety of reasons that are unrelated to the data-access provider; for example,
a connection attempt can fail because the principal server instance is inactive, as occurs when the database is
failing over, or because of a network error.
When attempting to connect, the data access provider begins by using the initial partner name. If the specified
server instance is available and is the current principal server instance, the connection attempt typically succeeds.

NOTE
If the mirroring session is paused, the client typically connects to the principal server and the downloads the partner name.
However, the database is unavailable to the client until mirroring resumes.

If that attempt does not work, the data access provider tries the failover partner name, if available. If either
partner name correctly identifies the current principal server, the data access provider normally succeeds in
opening the initial connection. On completing this connection, the data access provider downloads the server
instance name of the current mirror server. This name is stored in the cache as the failover partner name,
overwriting the client-supplied failover partner name, if any. Thereafter, the .NET Framework Data Provider for
SQL Server does not update the failover partner name. In contrast, SQL Server Native Client updates the cache
whenever a subsequent connection or connection reset returns a different partner name.
The following figure illustrates a client connection to the initial partner, Partner_A, for a mirrored database
named Db_1. This figure shows a case in which the initial partner name supplied by the client correctly identifies
the current principal server, Partner_A. The initial connection attempt succeeds, and the data access provider
stores the name of the mirror server (currently Partner_B ) as the failover partner name in the local cache. Finally,
the client connects to the principal copy of the Db_1 database.

The initial connection attempt may fail, for example, because of a network error or an inactive server instance.
Because the initial partner is unavailable, for the data access provider to attempt to connect to the failover partner,
the client must have supplied the failover partner name in the connection string.
In that case, if the failover partner name is unavailable, the original connection attempt continues until the
network connection timeout or an error is returned ( just as for a non-mirrored database).
When the failover partner name is supplied in the connection string, the behavior of the data access provider
depends on the network protocol and operating system of the client, as follows:
For TCP/IP, the connection attempts are regulated by a connection retry algorithm that is specific to
database mirroring. The connection retry algorithm determines the maximum time (the retry time) allotted
for opening a connection in a given connection attempt.
For other network protocols
If an error occurs or if the initial partner is unavailable, the initial connection attempt waits until the
network connection timeout period expires or the login timeout period expires on the data access provider.
Typically, this wait is on the order of 20 to 30 seconds. Thereafter, if the data access provider has not timed
out, it attempts to connect to the failover partner. If the connection timeout period expires before the
connection succeeds or the failover partner is unavailable, the connection attempt fails. If failover partner is
available within the login timeout period and is now the principal server, the connection attempt normally
succeeds.
Connection Strings for a Mirrored Database
The connection string supplied by the client contains information that the data access provider uses to connect to
the database. This section discusses the keywords that are specifically relevant for connecting to a mirrored
database using a SQL Server Native Client ODBC Driver Connection.
Network Attribute
The connection string should contain the Network attribute to specify the network protocol. This ensures that the
specified network protocol persists between connections to different partners. The best protocol for connecting to
a mirrored database is TCP/IP. To ensure that the client requests TCP/IP for every connection to the partners, a
connection string supplies the following attribute:

Network=dbmssocn;

IMPORTANT
We recommend keeping TCP/IP at the top of a client's protocol list. However, if the connection string specifies the Network
attribute, this overrides the list order.

Alternatively, to ensure that the client requests named pipes for every connection to the partners, a connection
string supplies the following attribute:

Network=dbnmpntw;

IMPORTANT
Because named pipes does not use the TCP/IP retry algorithm, in many cases, a named pipes connection attempt may time
out before connecting to a mirrored database.

Server Attribute
The connection string must contain a Server attribute that supplies the initial partner name, which should identify
the current principal server instance.
The simplest way to identify the server instance is by specifying its name ,
<server_name>[\<SQL_Server_instance_name>]. For example:
Server=Partner_A;

or
Server=Partner_A\Instance_2;

However, when the system name is used, the client must perform a DNS lookup to obtain the IP address of the
server and a SQL Server Browser query to obtain the port number of the server on which the partner resides.
Those lookups and queries can be bypassed by specifying the IP address and port number of the partner in the
Server attribute, rather than specifying the server name. This is recommended to minimize the possibility of
external delays while connecting to that partner.

NOTE
A SQL Server Browser query is necessary if the connection string specifies the named instance name and not the port.

To specify the IP address and port, the Server attribute takes the following form, Server= <ip_address> ,
<port>, for example:

Server=123.34.45.56,4724;

NOTE
The IP address can be IP Version 4 (IPv4) or IP Version 6 (IPv6).
Database Attribute
In addition, the connection string must specify the Database attribute to supply the name of the mirrored
database. If the database is unavailable when the client attempts to connect, an exception is raised.
For example, to expressly connect to the AdventureWorks database on the principal server Partner_A, a client
uses the following connection string:
" Server=Partner_A; Database=AdventureWorks "

NOTE
This string omits authentication information.

IMPORTANT
Bundling the protocol prefix with the Server attribute ( Server=tcp: <servername>) is incompatible with the Network
attribute, and specifying the protocol in both places will likely result in an error. Therefore, we recommend that a connection
string specify the protocol using the Network attribute and specify only the server name in the Server attribute (
"Network=dbmssocn; Server= <servername> " ).

Failover Partner Attribute


In addition to the initial partner name, the client can also specify failover partner name, which should identify the
current mirror server instance. The failover partner is specified by one of the keywords for the failover partner
attribute. The keyword for this attribute depends on the API that you are using. The following table lists these
keywords:

API KEYWORD FOR FAILOVER PARTNER ATTRIBUTE

OLE DB Provider FailoverPartner

ODBC Driver Failover_Partner

ActiveX Data Objects (ADO) Failover Partner

The simplest way to identify the server instance is by its system name,
<server_name>[\<SQL_Server_instance_name>].
Alternatively, the IP address and port number can be supplied in the Failover Partner attribute. If the initial
connection attempt fails during the first connection to the database, the attempt to connect to the failover partner
will be freed from relying on DNS and SQL Server Browser. Once a connection is established, the failover partner
name will be overwritten with the failover partner name, so if a failover occurs, the redirected connections will
require DNS and SQL Server Browser.

NOTE
When only the initial partner name is provided, application developers do not need to take any action or write any code
except about how to reconnect.
NOTE
Managed code application developers supply the failover partner name in the ConnectionString of the SqlConnection
object. For information on using this connection string, see "Database Mirroring Support in the .NET Framework Data
Provider for SQL Server" in the ADO.NET documentation, which is part of the Microsoft .NET Framework SDK.

Example Connection String


For example, to explicitly connect using TCP/IP to the AdventureWorks database on either Partner_A or
Partner_B, a client application that uses the ODBC Driver could supply the following connection string:

"Server=Partner_A; Failover_Partner=Partner_B; Database=AdventureWorks; Network=dbmssocn"

Alternatively, the client could use the IP address and port number to identify the initial partner, Partner_A; for
example, if the IP address is 250.65.43.21 and the port number is 4734, the connection string would be:

"Server=250.65.43.21,4734; Failover_Partner=Partner_B; Database=AdventureWorks; Network=dbmssocn"

Connection Retry Algorithm (for TCP/IP Connections)


For a TCP/IP connection, when both partner names are in the cache, the data access provider adheres to a
connection retry algorithm. This is true both for making the initial connection to the session and for reconnecting
after losing an established connection. Once a connection has been opened, completing the pre-login and login
steps takes additional time.

NOTE
The time spent in opening a connection can exceed the retry time because of external factors, such as slow DNS lookups,
slow domain controller/Kerberos Key Distribution Center (KDC), time spent contacting SQL Server Browser, network
congestion, and so forth. Such external factors can prevent a client from connecting to a mirrored database. Also, external
factors can cause a connection to take longer to open than the allotted retry time. For information on bypassing DNS and
SQL Server Browser for connection attempt to the initial partner, see Making the Initial Connection to a Database Mirroring
Session, earlier in this topic.

If a connection attempt fails or the retry time expires before it succeeds, the data access provider tries the other
partner. If a connection is not opened by this point, the provider alternately tries the initial and failover partner
names, until a connection is opened or the login period times out. The default login time-out period is 15 seconds.
We recommend that the login time-out period be at least 5 seconds. Specifying a smaller time-out period might
prevent any of the connection attempts from succeeding.
The retry time is a percentage of the login period. The retry time for a connection attempt is larger in each
successive round. In the first round, the retry time for each of the two attempts is 8 percent of the total login
period. In each successive round, the retry algorithm increases the maximum retry time by the same amount.
Thus, the retry times for the first eight connection attempts is as follows:
8%, 8%, 16%, 16%, 24%, 24%, 32%, 32%
The retry time is calculated using the following formula:
RetryTime = PreviousRetryTime +( 0.08 \LoginTimeout)*
Where PreviousRetryTime is initially 0.
For example, if using the default login time-out period of 15 seconds, LoginTimeout = 15. In this case, the retry
times allotted in the first three rounds are as follows:

ROUND RETRYTIME CALCULATION RETRY TIME PER ATTEMPT

1 0 +(0.08 \* 15) 1.2 seconds

2 1.2 +(0.08 \* 15) 2.4 seconds

3 2.4 +(0.08 \* 15) 3.6 seconds

4 3.6 +(0.08 \* 15) 4.8 seconds

The following figure illustrates these retry times for successive connection attempts, each of which times out.

For the default login time-out period, the maximum time allotted to the first three rounds of connection attempts
is 14.4 seconds. If every attempt were to use all of its allotted time, only 0.6 seconds of time would remain before
the login period times out. In that case, the fourth round would be curtailed, allowing only a final quick attempt to
connect using the initial partner name. However, a connection attempt may fail in less than its allotted retry time,
particularly in later rounds. For example, receiving a network error can cause an attempt to end before the retry
time expires. If earlier attempts fail due to a network error, additional time would be available for the fourth round
and, perhaps, additional rounds.
Another cause of a failed attempt is an inactive server instance, as occurs when a server instance is engaged in
failing over its database. In this case, a retry delay is imposed to prevent clients from overloading the partners
with a rapid succession of connection attempts.

NOTE
When both partner names are available, if the login time-out period is infinite, the client attempts to reconnect to the
servers indefinitely, alternating between the initial partner name and the failover partner name.

Retry Delays During Failover


If a client attempts to connect to a partner that is failing over, the partner immediately responds that it is inactive.
In this case, each round of connection attempts are much briefer than the allotted retry time. This means that
many rounds of connection attempts could happen before the login period times out. To avoid overloading the
partners with a rapid series of connection attempts during a failover, the data access provider adds a brief retry
delay after each retry cycle. The length of a given retry delay is determined by the retry-delay algorithm. After the
first round, the delay is 100 milliseconds. After each of the next three rounds, the retry delay doubles—to 200,
400, and 800. For all later rounds, the retry delay is 1 second until the connection attempt succeeds or times out.
NOTE
If the server instance is stopped, then the connection request fails immediately.

The following figure illustrates how the retry delay affects connection attempts during a manual failover, in which
the partners switch their roles. The login time-out period is 15 seconds.

Reconnecting to a Database Mirroring Session


If an established connection to a database mirroring session fails for any reason, for example, due to a database
mirroring failover, and the application attempts to reconnect to the initial server, the data access provider can
attempt to reconnect using the failover partner name stored in the client's cache. Reconnecting is not automatic,
however. The application must become aware of the error. Then, the application needs to close the failed
connection and open a new connection using the same connection string attributes. At this point, the data access
provider redirects the connection to the failover partner. If the server instance identified by this name is currently
the principal server, the connection attempt usually succeeds. If it is unclear whether a transaction was committed
or rolled back, the application must check on the state of the transaction, in the same way as when reconnecting
to a stand-alone server instance.
Reconnecting resembles an initial connection for which the connection string supplied a failover partner name. If
the first connection attempt fails, connection attempts alternate back and forth between the initial partner name
and failover partner name until either the client connects to the principal server or the data access provider times
out.

NOTE
SQL Server Native Client verifies that it connects to a principal server instance but not whether this instance is the partner
of server instance specified in the initial partner name of the connection string.

If the connections use TCP/IP, the connection retry algorithm determines the amount of time allotted to the
connection attempts in each round.

IMPORTANT
If the client gets disconnected from the database, the data access provider does not attempt to reconnect. The client must
issue a new connection request. Also, if an application shuts down on losing the connection, it will lose the cached partner
names. If the connection was lost because the principal server became unavailable, the only way that the application can
reconnect to the mirror server is by supplying the failover partner name in its connection string.

Impact of Redirection on a Client Application


After a failover, the data access provider redirects the connection to the current principal server instance. However,
the redirection is transparent to clients. To a client, a redirected connection appears to be a connection to the
server instance identified by the initial partner name. When the initial partner is currently the mirror server, the
client can appear to be connected to the mirror server and updating the mirror database. Actually, however, the
client has been redirected to the failover partner, which is the current principal database, and the client is updating
the new principal database.
After being redirected to the failover partner, a client can experience unexpected results when using a Transact-
SQL USE statement to use a different database. This can happen if the current principal server instance (the
failover partner) has a different set of databases than the original principal server (the initial partner).

The Impact of a Stale Failover Partner Name


The database administrator can change the failover partner at any time. Therefore, a client-supplied failover
partner name might be out of date, or stale. For example, consider a failover partner named Partner_B that is
replaced by another server instance, Partner_C. Now, if a client supplies Partner_B as the failover partner name,
that name is stale. When the client-supplied failover partner name is stale, the behavior of the data access
provider equates to the case in which a failover partner name is not supplied by the client.
For example, consider situation in which a client uses one connection string for a series of four connection
attempts. In the connection string, the initial partner name is Partner_A, and the failover partner name is
Partner_B:

"Server=Partner_A; Failover Partner=Partner_B; Database=AdventureWorks"

The following table shows four partner configurations and indicates for each whether this connection string
works for connecting the client for the first time.

NOTE
An application can track configuration changes and change its connection string accordingly. This requires extra code but
reduces the administrative burden.

BEHAVIOR WHEN
ATTEMPTING TO CONNECT
SPECIFYING PARTNER_A AND
CONFIGURATION PRINCIPAL SERVER MIRROR SERVER PARTNER_B

Original mirroring Partner_A Partner_B Partner_A is cached as the


configuration. initial partner name. The
client succeeds in
connecting to Partner_A.
The client downloads the
name of mirror server,
Partner_B, and caches it,
ignoring the client-supplied
failover partner name.

Partner_A experiences a Partner_B none The Partner_A is still cached


hardware failure, and as the initial partner name,
failover occurs but the client-supplied
(disconnecting clients). failover partner name,
Partner_B, permits the client
to connect to the current
principal server.
BEHAVIOR WHEN
ATTEMPTING TO CONNECT
SPECIFYING PARTNER_A AND
CONFIGURATION PRINCIPAL SERVER MIRROR SERVER PARTNER_B

The database administrator Partner_B Partner_C The client attempts to


stops mirroring connect to Partner_A and
(disconnecting clients), fails; then the client tries
replaces Partner_A with Partner_B (the current
Partner_C, and restarts principal server) and
mirroring. succeeds. The data access
provider downloads the
name of the current mirror
server, Partner_C, and
caches it as the current
failover partner name.

Service is manually failed Partner_C Partner_B Client attempts to connect


over to Partner_C to Partner_A initially, and
(disconnecting clients). then to Partner_B. Both
names fail, and eventually
the connection request
times out and fails.

See Also
Database Mirroring (SQL Server)
Possible Failures During Database Mirroring
Pausing and Resuming Database Mirroring (SQL
Server)
6/12/2018 • 3 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
The database owner can pause and later resume a database mirroring session at any time. Pausing preserves the
session state while suspending mirroring. During bottlenecks, pausing might be useful to improve performance
on the principal server.
When a session is paused, the principal database remains available. Pausing sets the state of the mirroring session
to SUSPENDED, and the mirror database no longer keeps up with the principal database, causing the principal
database to run exposed.
We recommend that you resume a paused session quickly, because as long as a database mirroring session
remains paused, the transaction log cannot be truncated. Therefore, if a database mirroring session is paused for
too long, the transaction log fills up, making the database unavailable. For an explanation of why this happens, see
"How Pausing and Resuming Affect Log Truncation," later in this topic.

IMPORTANT
Following a forced service, when the original principal server reconnects mirroring is suspended. Resuming mirroring in this
situation could possibly cause data loss on the original principal server. For information about managing the potential data
loss, see Database Mirroring Operating Modes.

In this Topic:
How Pausing and Resuming Affect Log Truncation
Avoid a Full Transaction Log
Related Tasks

How Pausing and Resuming Affect Log Truncation


Normally, when an automatic checkpoint is performed on a database, its transaction log is truncated to that
checkpoint after the next log backup. While a database mirroring session remains paused, all of the current log
records remain active because the principal server is waiting to send them to the mirror server. The unsent log
records accumulate in the transaction log of the principal database until the session resumes and the principal
server has sent the log records to the mirror server.
When the session is resumed, the principal server immediately begins sending the accumulated log records to the
mirror server. After the mirror server confirms that it has queued the log record corresponding to the oldest
automatic checkpoint, the principal server truncates the log of the principal database to that checkpoint. The
mirror server truncates the redo queue at the same log record. As this process is repeated for each successive
checkpoint, the log is truncated in stages, checkpoint by checkpoint.

NOTE
For more information about the checkpoints and log truncation, see Database Checkpoints (SQL Server).
Avoid a Full Transaction Log
If the log fills up (either because it reaches its maximum size or the server instance runs out of space), the
database cannot perform any more updates. To avoid this problem, you have two alternatives:
Resume the database mirroring session before the log fills up, or add more log space. Resuming database
mirroring lets the principal server send its accumulated active log to the mirror server and puts the mirror
database in the SYNCHRONIZING state. The mirror server can then harden the log to disk and start to
redo it.
Stop the database mirroring session by removing mirroring.
Unlike pausing a session, removing mirroring drops all information about the mirroring session. Each
partner server instance retains its own copy of the database. If the former mirror copy is recovered, it will
have diverged from the former principal copy and be behind by the amount of time that has elapsed since
the session was paused. For more information, see Removing Database Mirroring (SQL Server).

Related Tasks
To pause or resume database mirroring
Pause or Resume a Database Mirroring Session (SQL Server)
To stop database mirroring
Remove Database Mirroring (SQL Server)

See Also
ALTER DATABASE (Transact-SQL )
Database Mirroring (SQL Server)
Removing Database Mirroring (SQL Server)
Pause or Resume a Database Mirroring Session (SQL
Server)
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
This topic describes how to pause or resume database mirroring in SQL Server 2017 by using SQL Server
Management Studio or Transact-SQL.
In This Topic
Before you begin:
Security
To ReplaceThisText, using:
SQL Server Management Studio
Transact-SQL
Follow Up: After Pausing or Resuming Database Mirroring

Before You Begin


At any time, you can suspend a database mirroring session, which might improve performance during
bottlenecks, and you can resume a suspended session at any time.
Cau t i on

After a forced service, when the original principal server reconnects, mirroring is suspended. Resuming mirroring
in this situation could possibly cause data loss on the original principal server. For information about managing
the potential data loss, see Role Switching During a Database Mirroring Session (SQL Server).
Security
Permissions
Requires ALTER permission on the database.

Using SQL Server Management Studio


To pause or resume a database mirroring session use the Database Properties Mirroring page.
To pause or resume database mirroring
1. During a database mirroring session, connect to the principal server instance, in Object Explorer, click the
server name to expand the server tree.
2. Expand Databases, and select the database.
3. Right-click the database, select Tasks, and then click Mirror. This opens the Mirroring page of the
Database Properties dialog box.
4. To pause the session, click Pause.
A prompt asks for confirmation; if you click Yes, the session is paused, and the button changes to Resume.
For more information about the impact of pausing a session, see Pausing and Resuming Database
Mirroring (SQL Server).
5. To resume the session, click Resume.

Using Transact-SQL
To pause database mirroring
1. Connect to the Database Engine for either partner.
2. From the Standard bar, click New Query.
3. Issue the following Transact-SQL statement:
ALTER DATABASE database_name SET PARTNER SUSPEND
where database_name is the mirrored database whose session you want to you want to suspend.
The following example pauses the AdventureWorks2012 sample database.

ALTER DATABASE AdventureWorks2012 SET PARTNER SUSPEND;

To r e su m e d a t a b a se m i r r o r i n g

1. Connect to the Database Engine for either partner.


2. From the Standard bar, click New Query.
3. Issue the following Transact-SQL statement:
ALTER DATABASE database_name SET PARTNER RESUME
where database_name is the mirrored database whose session you want to resume.
The following example pauses the AdventureWorks2012 sample database.

ALTER DATABASE AdventureWorks2012 SET PARTNER RESUME;

Follow Up: After Pausing or Resuming Database Mirroring


After pausing database mirroring
On the primary database, take precautions to avoid a full transaction log. For more information, see The
Transaction Log (SQL Server).
After resuming database mirroring
Resuming database mirroring places the mirror database in the SYNCHRONIZING state. If the safety
level is FULL, the mirror catches up with the principal and the mirror database enters the
SYNCHRONIZED state. At this point, failover becomes possible. If the witness is present and ON,
automatic failover is possible. In the absence of a witness, manual failover is possible.

Related Tasks
Remove Database Mirroring (SQL Server)

See Also
Database Mirroring (SQL Server)
Removing Database Mirroring (SQL Server)
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
The database owner can manually stop a database mirroring session at any time, at either partner.

Impact of Removing Mirroring


When mirroring is removed, the following occurs:
The relationship between the partners and between each partner and the witness breaks permanently, if
any relationship exists.
If the partners are communicating with each other when the session is stopped, their relationship is
immediately broken on both computers. If the partners are not communicating (the database is in a
DISCONNECTED state at the time of stopping), the relationship is broken immediately on the partner
from which mirroring is stopped; when the other partner tries to reconnect, it discovers that the database
mirroring session has ended.
Information about the mirroring session is dropped, unlike when pausing a session. Mirroring is removed
on both the principal database and the mirror database. In sys.databases, the mirroring_state column
and all other mirroring columns are set to NULL. For more information, see sys.database_mirroring
(Transact-SQL ).
Each partner server instance is left with a separate copy of the database.
The mirror database is left in the RESTORING state (see the state column of sys.databases), because the
mirror database was created by using RESTORE WITH NORECOVERY. At this point, you can drop the
former mirror database or restore it using WITH RECOVERY. When you recover the database, it will have
diverged from the former principal database because the recovery starts a new recovery fork.

NOTE
To continue mirroring after stopping a session, you must establish a new database mirroring session. If you create a log
backup after stopping mirroring, you must apply it to the mirror database before restarting mirroring.

Related Tasks
To remove database mirroring
Remove Database Mirroring (SQL Server)
To start database mirroring
Establish a Database Mirroring Session Using Windows Authentication (SQL Server Management Studio)
Establish a Database Mirroring Session Using Windows Authentication (Transact-SQL )

See Also
ALTER DATABASE Database Mirroring (Transact-SQL )
Database Mirroring (SQL Server)
Pausing and Resuming Database Mirroring (SQL Server)
sys.databases (Transact-SQL )
Remove Database Mirroring (SQL Server)
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
This topic describes how to remove database mirroring from a database in SQL Server 2017 by using SQL
Server Management Studio or Transact-SQL. At any time, the database owner can manually stop a database
mirroring session by removing mirroring from the database.
In This Topic
Before you begin:
Security
To remove database mirroring, using:
SQL Server Management Studio
Transact-SQL
Follow Up: After Removing Database Mirroring
Related Tasks

Before You Begin


Security
Permissions
Requires ALTER permission on the database.

Using SQL Server Management Studio


To remove database mirroring
1. During a database mirroring session, connect to the principal server instance, in Object Explorer, click the
server name to expand the server tree.
2. Expand Databases, and select the database.
3. Right-click the database, select Tasks, and then click Mirror. This opens the Mirroring page of the
Database Properties dialog box.
4. In the Select a Page pane, click Mirroring.
5. To remove mirroring, click Remove Mirroring. A prompt asks for confirmation. If you click Yes, the
session is stopped and mirroring is removed from the database.

Using Transact-SQL
To remove database mirroring, use the Database Properties. use the Mirroring page of the Database
Properties dialog box.
To remove database mirroring
1. Connect to the Database Engine of either mirroring partner.
2. From the Standard bar, click New Query.
3. Issue the following Transact-SQL statement:

ALTER DATABASE database_name SET PARTNER OFF

where database_name is the mirrored database whose session you want to remove.
The following example removes database mirroring from the AdventureWorks2012 sample database.

ALTER DATABASE AdventureWorks2012 SET PARTNER OFF;

Follow Up: Removing Database Mirroring


NOTE
For information about the impact of removing mirroring, see Removing Database Mirroring (SQL Server).

If you intend to restart mirroring on the database


Any log backups taken on the principal database after mirroring was removed must all be applied to the
mirror database before you can restart mirroring.
If you do not intent to restart mirroring
Optionally, you can recover the former mirror database. On the server instance that was the mirror server,
you can use the following Transact-SQL statement:

RESTORE DATABASE database_name WITH RECOVERY;

IMPORTANT
If you recover this database, two divergent databases with the same name are online. Therefore, you need to
ensure that clients can access only one of them—typically the most recent principal database.

Related Tasks
Pause or Resume a Database Mirroring Session (SQL Server)
Remove the Witness from a Database Mirroring Session (SQL Server)
Establish a Database Mirroring Session Using Windows Authentication (SQL Server Management Studio)
Establish a Database Mirroring Session Using Windows Authentication (Transact-SQL )
Example: Setting Up Database Mirroring Using Certificates (Transact-SQL )

See Also
Database Mirroring (SQL Server)
Setting Up Database Mirroring (SQL Server)
Always On Availability Groups (SQL Server)
Upgrading Mirrored Instances
6/12/2018 • 7 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
When upgrading a SQL Server mirrored instance to a new SQL Server 2017 version, to a new SQL
Serverservice pack or cumulative update, or to a new Windows service pack or cumulative update, you can
reduce downtime for each mirrored database to only a single manual failover by performing a rolling upgrade
(or two manual failovers if failing back to the original primary). A rolling upgrade is a multi-stage process that in
its simplest form involves upgrading the SQL Server 2017 instance that is currently acting as the mirror server in
a mirroring session, then manually failing over the mirrored database, upgrading the former principal SQL
Server 2017 instance, and resuming mirroring. In practice, the exact process will depend on the operating mode
and the number and layout of mirroring session running on the SQL Server 2017 instances that you are
upgrading.

NOTE
For information on using database mirroring with log shipping during a migration, download this Database Mirroring and
Log Shipping whitepaper.

Prerequisites
Before you begin, review the following important information:
Supported Version and Edition Upgrades: Verify that you can upgrade to SQL Server 2016 from your
version of the Windows operating system and version of SQL Server. For example, you cannot upgrade
directly from a SQL Server 2005 instance to SQL Server 2017.
Choose a Database Engine Upgrade Method: Select the appropriate upgrade method and steps based on
your review of supported version and edition upgrades and also based on other components installed in
your environment to upgrade components in the correct order.
Plan and Test the Database Engine Upgrade Plan: Review the release notes and known upgrade issues, the
pre-upgrade checklist, and develop and test the upgrade plan.
Hardware and Software Requirements for Installing SQL Server 2016: Review the software requirements
for installing SQL Server 2017. If additional software is required, install it on each node before you begin
the upgrade process to minimize any downtime.

Recommended Preparation (Best Practices)


Before starting a rolling upgrade, we recommend that you:
1. Perform a practice manual failover on at least one of your mirroring sessions:
Manually Fail Over a Database Mirroring Session (SQL Server Management Studio)
Manually Fail Over a Database Mirroring Session (Transact-SQL ).
NOTE
For information about how manual failover works, see Role Switching During a Database Mirroring Session (SQL
Server).

2. Protect your data:


a. Perform a full database backup on every principal database:
Create a Full Database Backup (SQL Server).
b. Run the DBCC CHECKDB command on every principal database.

Stages of a Rolling Upgrade


The specific steps of a rolling upgrade depend on the operating mode of the mirroring configuration. However,
the basic stages are the same.

NOTE
For information about the operating modes, see Database Mirroring Operating Modes.

The following illustration is a flowchart that shows the basic stages of a rolling upgrade for each operating mode.
The corresponding procedures are described after the illustration.

IMPORTANT
A server instance might be performing different mirroring roles (principal server, mirror server, or witness) in concurrent
mirroring sessions. In this case, you will have to adapt the basic rolling upgrade process accordingly. For more information,
see Role Switching During a Database Mirroring Session (SQL Server).
NOTE
In many cases, after the rolling upgrade is completed, you will failback to the original principal server.

To change a session from high-performance mode to high-safety mode


1. If a mirroring session is running in high-performance mode, before you perform a rolling upgrade, change
the operating mode to high safety without automatic failover.

IMPORTANT
If the mirror server is geographically distant from the principal server, a rolling upgrade might be inappropriate.

In SQL Server Management Studio: Change the Operating mode option to High safety without
automatic failover (synchronous) by using the Mirroring Page of the Database Properties
dialog box. For information about how to access this page, see Start the Configuring Database
Mirroring Security Wizard (SQL Server Management Studio).
In Transact-SQL: Set transaction safety to FULL. For more information, see Change Transaction
Safety in a Database Mirroring Session (Transact-SQL )
To remove a witness from a session
1. If a mirroring session involves a witness, we recommend that you remove the witness before you perform
a rolling upgrade. Otherwise, when the mirror server instance is being upgraded, database availability
depends on the witness that remains connected to the principal server instance. After you remove a
witness, you can upgrade it at any time during the rolling upgrade process without risking database
downtime.

NOTE
For more information, see Quorum: How a Witness Affects Database Availability (Database Mirroring).

Remove the Witness from a Database Mirroring Session (SQL Server)


To perform the rolling upgrade
1. To minimize downtime, we recommend the following: Start the rolling upgrade by updating any mirroring
partner that is currently the mirror server in all its mirroring sessions. You might have to update multiple
server instances at this point.

NOTE
A witness can be upgraded at any point in the rolling upgrade process. For example, if a server instance is a mirror
server in Session 1 and is a witness in Session 2, you can upgrade the server instance now.

The server instance to upgrade first depends on the current configuration of your mirroring sessions, as
follows:
If any server instance is already the mirror server in all its mirroring sessions, upgrade the server
instance to the new version.
If all your server instances are currently the principal server in any mirroring sessions, select one
server instance to upgrade first. Then, manually fail over each of its principal databases and
upgrade that server instance.
After being upgraded, a server instance automatically rejoins each of its mirroring sessions.
2. For each mirroring session whose mirror server instance has just been upgraded, wait for the session to
synchronize. Then, connect to the principal server instance, and manually fail over the session. On failover,
the upgraded server instance becomes the principal server for that session, and the former principal
server becomes the mirror server.
The goal of this step is for another server instance to become the mirror server in every mirroring session
in which it is a partner.
Restrictions after you failover to an upgraded server instance.
After failing over from an earlier server instance to a SQL Server 2017 server instance, the database
session is suspended. It cannot be resumed until the other partner has been upgraded. However, the
principal server is still accepting connections and allowing data access and modifications on the principal
database.

NOTE
Establishing a new mirroring session requires that the server instances all be running the same version of SQL
Server.

3. After you fail over, we recommend that you run the DBCC CHECKDB command on the principal database.
4. Upgrade each server instance that is now the mirror server in all mirroring sessions in which it is a
partner. You might have to update multiple servers at this point.

IMPORTANT
In a complex mirroring configuration, some server instance might still be the original principal server in one or more
mirroring sessions. Repeat steps 2–4 for those server instances until all instances involved are upgraded.

5. Resume the mirroring session.

NOTE
Automatic failover will not work until the witness has been upgraded and added back into the mirroring session.

6. Upgrade any remaining server instance that is the witness in all its mirroring sessions. After an upgraded
witness rejoins a mirroring session, automatic failover becomes possible again. You might have to update
multiple servers at this point.
To return a session to high-performance mode
1. Optionally, return to high-performance mode by using one of the following methods:
In SQL Server Management Studio: Change the Operating mode option to High performance
(asynchronous) by using the Mirroring Page of the Database Properties dialog box.
In Transact-SQL: Use ALTER DATABASEto set transaction safety to OFF.
To add a witness back into a mirroring session
1. Optionally, in high-safety mode, reestablish the witness to each mirroring session.
To return a witness
Add or Replace a Database Mirroring Witness (SQL Server Management Studio)
Add a Database Mirroring Witness Using Windows Authentication (Transact-SQL )

See Also
Upgrade to SQL Server 2016 Using the Installation Wizard (Setup)
Install SQL Server 2016 from the Command Prompt
ALTER DATABASE Database Mirroring (Transact-SQL )
BACKUP (Transact-SQL )
View the State of a Mirrored Database (SQL Server Management Studio)
Database Mirroring (SQL Server)
Role Switching During a Database Mirroring Session (SQL Server)
Force Service in a Database Mirroring Session (Transact-SQL )
Start Database Mirroring Monitor (SQL Server Management Studio)
Database Mirroring Operating Modes
Monitoring Database Mirroring (SQL Server)
6/12/2018 • 15 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
This section introduces Database Mirroring Monitor and the sp_dbmmonitor system stored procedures,
explains how database mirroring monitoring works (including the Database Mirroring Monitor Job), and
summarizes the information that you can monitor about database mirroring sessions. Additionally, this section
introduces how to define warning thresholds for a set of predefined database mirroring events and how to set
up alerts on any database mirroring event.
You can monitor a mirrored database during a mirroring session to verify whether and how well data is flowing.
To set up and manage monitoring for one or more of the mirrored databases on a server instance, you can use
either Database Mirroring Monitor or the sp_dbmmonitor system stored procedures.
A database mirroring monitoring job, Database Mirroring Monitor Job, operates in the background,
independently of Database Mirroring Monitor. SQL Server Agent calls Database Mirroring Monitor Job at
regular intervals, the default is once a minute, and the job calls a stored procedure that updates mirroring status.
If you use SQL Server Management Studio to start a mirroring session, Database Mirroring Monitor Job is
created automatically. However, if you only use ALTER DATABASE <database_name> SET PARTNER to start
mirroring, you must create the job by running a stored procedure.
In this Topic:
Monitoring Mirroring Status
Additional Sources of Information About a Mirrored Database
Related Tasks

Monitoring Mirroring Status


To set up and manage monitoring for one or more of the mirrored databases on a server instance, you can use
either Database Mirroring Monitor or the dbmmonitor system stored procedures. You can monitor a mirrored
database during a mirroring session to verify whether and how well data is flowing.
Specifically, monitoring a mirrored database enables you to:
Verify that mirroring is functioning.
Basic status includes knowing if the two server instances are up, that the servers are connected, and that
the log is being moved from the principal to the mirror.
Determine whether the mirror database is keeping up with the principal database.
During high-performance mode, a principal server can develop a backlog of unsent log records that still
need to be sent from the principal server to the mirror server. Furthermore, in any operating mode, the
mirror server can develop a backlog of unrestored log records that have been written to the log file but
still need to be restored on the mirror database.
Determine how much data was lost when the principal server instance becomes unavailable during high-
performance mode.
You can determine data loss by looking at the amount of unsent transaction log (if any) and the time
interval in which the lost transactions were committed at the principal.
Compare current performance with past performance.
When problems are occurring, a database administrator can view a history of the mirroring performance
to help in understanding the current state. Looking at the history can allow the user to detect trends in
performance, identify patterns of performance problems (such as times of day when the network is slow
or the number of commands entering the log is very large).
Troubleshoot the cause of reduced data flow between mirroring partners.
Set warning thresholds on key performance metrics.
If a new status row contains a value that exceeds a threshold, an informational event is sent to the
Windows event log. A system administrator can then manually configure alerts based on these events.
For more information, see Use Warning Thresholds and Alerts on Mirroring Performance Metrics (SQL
Server).
Tools for Monitoring Database Mirroring Status
Mirroring status can be monitored using either Database Mirroring Monitor or the sp_dbmmonitorresults
system stored procedure. These tools can be used to monitor database mirroring on any mirrored database on
the local server instance by both System administrators, that is, members of the sysadmin fixed server role, and
user who have been added to the dbm_monitor fixed database role in the msdb database by a system
administrator. When using either tool, a system administrator can also manually refresh mirroring status.

NOTE
System administrators can also configure and view warning thresholds for key performance metrics. For more information,
see Use Warning Thresholds and Alerts on Mirroring Performance Metrics (SQL Server).

Database Mirroring Monitor


Database Mirroring Monitor is a graphical user interface tool that enables system administrators to view
and update status and to configure warning thresholds on several key performance metrics. Database
Mirroring Monitor can also be used by members of the dbm_monitor fixed database role to view the
most recent row of the mirroring status table, though they cannot update the status table.
The monitor displays the status, including performance metrics, for a selected database on the Status
tabbed page. The content of this page comes from both the principal and mirror server instances. The
page is filled asynchronously as status is gathered through separate connections to the principal and
mirror server instances. The monitor tries to update the status table at 30-second intervals. The update
succeeds only if the table has not been updated within 15 seconds and the user is a member of the
sysadmin fixed server role. For a summary of the information reported on the Status page, see Status
Displayed by the Database Mirroring Monitor, later in this topic.
For an introduction to the Database Mirroring Monitor interface, see Database Mirroring Monitor
Overview. For information on launching Database Mirroring Monitor, see Start Database Mirroring
Monitor (SQL Server Management Studio).
System stored procedures
You can also retrieve or update the current status by running the sp_dbmmonitorresults system stored
procedure. Other dbmmonitor stored procedures enable you to set up monitoring, change monitoring
parameters, view the current update period, and drop monitoring on the server instance.
The following table introduces the stored procedures for managing and using database mirroring
monitoring independently of the Database Mirroring Monitor.
PROCEDURE DESCRIPTION

sp_dbmmonitoraddmonitoring Creates a job that periodically updates the status


information for every mirrored database on the server
instance.

sp_dbmmonitorchangemonitoring Changes the value of a database mirroring monitoring


parameter.

sp_dbmmonitorhelpmonitoring Returns the current update period.

sp_dbmmonitorresults Returns status rows for a monitored database and allows


you to choose whether the procedure obtains the latest
status beforehand.

sp_dbmmonitordropmonitoring Stops and deletes the mirroring monitor job for all the
databases on the server instance.

The dbmmonitor system stored procedures can be used as an adjunct to the Database Mirroring
Monitor. For example, even if monitoring was configured using sp_dbmmonitoraddmonitoring,
Database Mirroring Monitor can be used to view the status.
How Monitoring Works
This section introduces the database mirroring status table, database mirroring monitor job and the monitor,
how users can monitor database mirroring status, and how the monitoring job can be dropped.
Database Mirroring Status Table
Database mirroring status is stored in an internal, undocumented database mirroring status table in the msdb
database. This status table is automatically created the first time the mirroring status is updated on the server
instance.
The status table may be updated either automatically or manually by a system administrator, with a minimum
update interval of 15 seconds. The 15 second minimum prevents server instances from being overloaded with
status requests.
The status table is updated automatically by both Database Mirroring Monitor and the database mirroring
monitor job, if running. Database Mirroring Monitor Job updates the table once a minute by default (a
system administrator can specify an update period of 1 to 120 minutes). Database Mirroring Monitor, in contrast,
updates the table automatically every 30 seconds. For these updates, Database Mirroring Monitor Job and
Database Mirroring Monitor call sp_dbmmonitorupdate.
The first time sp_dbmmonitorupdate runs, it creates the database mirroring status table and the
dbm_monitor fixed database role in the msdb database. sp_dbmmonitorupdate usually updates the
mirroring status by inserting a new row into the status table for every mirrored database on the server instance;
for more information, see "Database Mirroring Status Table," later in this topic. This procedure also evaluates the
performance metrics in the new rows and truncates rows older than the current retention period (the default is 7
days). For more information, see sp_dbmmonitorupdate (Transact-SQL ).

NOTE
Unless Database Mirroring Monitor is currently being used by a member of the sysadmin fixed server role, the status
table is automatically updated only if the Database Mirroring Monitor Job exists and SQL Server Agent is running.

Database Mirroring Monitor Job


The database mirroring monitoring job, Database Mirroring Monitor Job, operates independently of
Database Mirroring Monitor. Database Mirroring Monitor Job is created automatically only if SQL Server
Management Studio is used to start a mirroring session. If ALTER DATABASE database_name SET PARTNER
commands are always used to start mirroring, the job exists only if the system administrator runs the
sp_dbmmonitoraddmonitoring stored procedure.
After Database Mirroring Monitor Job is created, assuming that SQL Server Agent is running, the job is
called once a minute, by default. The job then calls the sp_dbmmonitorupdate system stored procedure.
SQL Server Agent calls Database Mirroring Monitor Job once a minute, by default, and the job calls
sp_dbmmonitorupdate to update the status table. System administrators can change the update period by
using the sp_dbmmonitorchangemonitoring system stored procedure, and they can view the current update
period by using the sp_dbmmonitorchangemonitoring system stored procedure. For more information, see
sp_dbmmonitoraddmonitoring (Transact-SQL ) and sp_dbmmonitorchangemonitoring (Transact-SQL ).
Monitoring Database Mirroring Status (by System Administrators )
Members of the sysadmin fixed server role can view and update the status table
Using Database Mirroring Monitor
When using Database Mirroring Monitor, a system administrator can manually refresh the Status page,
navigation tree, or History page. This also updates the status table, unless it has already been updated
within the previous 15 seconds.
To view the history of mirroring status on a given server instance, the system administrator can also click
the History button for a server instance (on the Status page). The history is displayed in the Database
Mirroring History dialog box. There, the system administrator can view some or all of the rows in the
status table of the server instance.
For information about the Status page metrics, see Performance Metrics Displayed by the "Database
Mirroring Monitor," later in this topic.
Using sp_dbmmonitorresults
System administrators can use the sp_dbmmonitorresults system stored procedure to view and,
optionally, to update the status table, if it has not been updated within the previous 15 seconds. This
procedure calls the sp_dbmmonitorupdate procedure and returns one or more history rows, depending
on the amount requested in the procedure call. For information about the status in its results set, see
sp_dbmmonitorresults (Transact-SQL ).
Monitoring Database Mirroring Status (by dbm_monitor Members )
As mentioned, the first time sp_dbmmonitorupdate runs, it creates the dbm_monitor fixed database role in
the msdb database. Members of the dbm_monitor fixed database role can view the existing mirroring status by
using either Database Mirroring Monitor or the sp_dbmmonitorresults stored procedure. But these users
cannot update the status table. To learn the age of the displayed status a user can look at the times in the
Principal log (<time>) and Mirror log (<time>) labels on the Status page.
Members of the dbm_monitor fixed database role depend on the Database Mirroring Monitor Job to update
the status table at regular intervals. If the job does not exist or SQL Server Agent is stopped, the status becomes
increasingly stale and may no longer reflect the configuration of the mirroring session. For example, after a
failover, the partners might appear to share the same role—principal or mirror, or the current principal server
might be shown as the mirror, while the current mirror server is shown as the principal.
Dropping the Database Mirroring Monitor Job
The database mirroring monitor job, Database Mirroring Monitor Job, remains until it is dropped. The
monitoring job must be managed by the system administrator. To drop Database Mirroring Monitor Job, use
sp_dbmmonitordropmonitoring. For more information, see sp_dbmmonitordropmonitoring (Transact-SQL ).
Status Displayed by the Database Mirroring Monitor
The Status page of the Database Mirroring Monitor describes the partners, and also the state of the mirroring
session. The status includes performance metrics such as the state of the transaction log and other information
that is intended to help currently estimate the time required to complete a failover and the potential of data loss,
if the session is not synchronized. In addition, the Status page displays status and information about the
mirroring session in general.

NOTE
For an introduction to the Database Mirroring Monitor and Status page, see Tools for Monitoring Database Mirroring
Status, earlier in this topic.

The information provided for each of these is summarized in the following sections.
Partners
The Status page displays the following information for each of the partners:
Server instance
Name of the server instance whose status is displayed in the Status row.
Current role
Current role of the server instance. The possible states are:
Principal
Mirror
Mirroring state
The possible states are:
Unknown
Synchronizing
Synchronized
Suspended
Disconnected
Witness connection
Connection status of the witness. The possible states are:
Unknown
Connected
Disconnected.
Log on the Principal Server
The Status page displays the following information about the status of the log on the principal server as of the
indicated time:
Unsent log
The amount of log waiting in the send queue in kilobytes (KB ).
Oldest unsent transaction
Age of the oldest unsent transaction in the send queue. The age of this transaction indicates how many
minutes of transactions have not yet been sent to the mirror server instance. This value helps measure the
potential for data loss in terms of time.
Time to send log (estimated)
Estimated number of minutes the principal server instance requires to send the log that is currently in the
send queue to the mirror server instance based on the current send rate. The actual time to send the log
will be affected by the rate of incoming transactions, which can vary significantly. However, the Time to
send log (estimated) value can be useful for roughly estimating the time required for a manual failover.
Current send rate
Rate at which transactions are being sent to the mirror server instance in KB per second.
Current rate of new transactions
Rate at which incoming transactions are being entered into the principal's log in KB per second. To
determine whether mirroring is falling behind, staying up, or catching up, compare this value to the
Estimated time to send log value.
Log on the Mirror Server
The Status page displays the following information about the status of the log on the mirror server as of the
indicated time:
Unrestored log
The amount of log waiting in the redo queue in KB.
Time to restore log (estimated)
Approximate number of minutes required for the log currently in the redo queue to be applied to the
mirror database.
Current restore rate
Rate at which transactions are being restored into the mirror database (in KB per second).
Mirroring Session
In addition, the Status page displays the following information about the mirroring session:
Mirroring commit overhead
Average delay per transaction in milliseconds (relevant only in high-safety mode). This delay is the
amount of overhead incurred while the principal server instance waits for the mirror server instance to
write the transaction's log record into the redo queue.
Time to send and restore all current log (estimated)
Estimated time needed to send all of the unsent log that has been committed at the principal and to
restore all of the log currently in the redo queue. This estimate may be less than the sum of the values of
the Time to send log (estimated) and Time to restore log (estimated) fields, because sending and
restoring can operate in parallel.
Witness address
Network address of the witness server instance. For information about the format of this address, see
Specify a Server Network Address (Database Mirroring).
Operating mode
The operating mode of the database mirroring session:
High performance (asynchronous)
High safety without automatic failover (synchronous)
High safety with automatic failover (synchronous)

Additional Sources of Information About a Mirrored Database


In addition to using the Database Mirroring Monitor and dbmmonitor stored procedures to monitor a mirrored
database and set up alerts on monitored performance variables, SQL Server 2017 provides catalog views,
performance counters, and event notifications for database mirroring.
In This Section:
Database Mirroring Metadata
Database Mirroring Performance Counters
Database Mirroring Event Notifications
Database Mirroring Metadata
Each database mirroring session is described in metadata that is exposed through the following catalog or
dynamic management views:
sys.database_mirroring
This view displays the database mirroring metadata for each mirrored database in a server instance. For
more information, see sys.database_mirroring (Transact-SQL ).
sys.database_mirroring_endpoints
The sys.database_mirroring_endpoints catalog view displays information about the database mirroring
endpoint of the server instance. For more information, see sys.database_mirroring_endpoints (Transact-
SQL ).
sys.database_mirroring_witnesses
This catalog view displays the database mirroring metadata for each session in which a server instance is
the witness. For more information, see sys.database_mirroring_witnesses (Transact-SQL ).
sys.dm_db_mirroring_connections
This dynamic management view returns a row for each database mirroring network connection.
For more information, see sys.dm_db_mirroring_connections (Transact-SQL ).
Database Mirroring Performance Counters
Performance counters let you monitor database mirroring performance. For example, you can examine the
Transaction Delay counter to see if database mirroring is impacting performance on the principal server, you
can examine the Redo Queue and Log Send Queue counters to see how well the mirror database is keeping
up with the principal database. You can examine the Log Bytes Sent/sec counter to monitor the amount of log
sent per second.
In Performance Monitor on either partner, performance counters are available in the database mirroring
performance object (SQLServer:Database Mirroring). For more information, see SQL Server, Database
Mirroring Object.
To start the performance monitor
Start System Monitor (Windows)
Database Mirroring Event Notifications
Event notifications are a special kind of database object. Event notifications execute in response to a variety of
Transact-SQL data definition language (DDL ) statements and SQL Trace events and send information about
server and database events to a Service Broker service.
The following events are available for database mirroring:
Database Mirroring State Change event class
This indicates when the mirroring state of a mirrored database changes. For more information, see
Database Mirroring State Change Event Class.
Audit Database Mirroring Login event class
This reports audit messages related to database mirroring transport security. For more information, see
Audit Database Mirroring Login Event Class.

Related Tasks
Use Warning Thresholds and Alerts on Mirroring Performance Metrics (SQL Server)
Start Database Mirroring Monitor (SQL Server Management Studio)
View the State of a Mirrored Database (SQL Server Management Studio)
Stored procedures
sp_dbmmonitoraddmonitoring (Transact-SQL )
sp_dbmmonitorchangealert (Transact-SQL )
sp_dbmmonitorchangemonitoring (Transact-SQL )
sp_dbmmonitordropalert (Transact-SQL )
sp_dbmmonitordropmonitoring (Transact-SQL )
sp_dbmmonitorhelpalert (Transact-SQL )
sp_dbmmonitorhelpmonitoring (Transact-SQL )
sp_dbmmonitorresults (Transact-SQL )
sp_dbmmonitorupdate (Transact-SQL )

See Also
Database Mirroring (SQL Server)
WMI Provider for Server Events Concepts
Use Warning Thresholds and Alerts on Mirroring
Performance Metrics (SQL Server)
6/12/2018 • 5 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
This topic contains information about the SQL Server events for which warning thresholds can be configured and
managed for database mirroring. You can use the Database Mirroring Monitor or the
sp_dbmmonitorchangealert, sp_dbmmonitorhelpalert, and sp_dbmmonitordropalert stored procedures.
This topic also contains information about configuring alerts on database mirroring events.
After monitoring is established for a mirrored database, a system administrator can configure warning thresholds
on several key performance metrics. Also, an administrator can configure alerts on these and other database
mirroring events.
In This Topic:
Performance Metrics and Warning Thresholds
Setting Up and Managing Warning Thresholds
Using Alerts for a Mirrored Database
Related Tasks

Performance Metrics and Warning Thresholds


The following table lists the performance metrics for which warnings can be configured, describes the
corresponding warning threshold, and lists the corresponding Database Mirroring Monitor label.

PERFORMANCE METRIC WARNING THRESHOLD DATABASE MIRRORING MONITOR LABEL

Unsent log Specifies how many kilobytes (KB) of Warn if the unsent log exceeds the
unsent log generate a warning on the threshold
principal server instance. This warning
helps measure the potential for data
loss in terms of KB and is especially
relevant for high-performance mode.
However, the warning is also relevant
for high-safety mode when mirroring is
paused or suspended because the
partners become disconnected.
PERFORMANCE METRIC WARNING THRESHOLD DATABASE MIRRORING MONITOR LABEL

Unrestored log Specifies how many KB of unrestored Warn if the unrestored log exceeds
log generate a warning on the mirror the threshold
server instance. This warning helps
measure failover time. Failover time
consists mainly of the time that the
former mirror server requires to roll
forward any log remaining in its redo
queue, plus a short additional time.

Note: For an automatic failover, the


time for the system to notice the error
is independent of the failover time.

For more information, see Estimate the


Interruption of Service During Role
Switching (Database Mirroring).

Oldest unsent transaction Specifies the number of minutes worth Warn if the age of the oldest unsent
of transactions that can accumulate in transaction exceeds the threshold
the send queue before a warning is
generated on the principal server
instance. This warning helps measure
the potential for data loss in terms of
time and is especially relevant for high-
performance mode. However, the
warning is also relevant for high-safety
mode when mirroring is paused or
suspended because the partners
become disconnected.

Mirror commit overhead Specifies the number of milliseconds of Warn if the mirror commit
average delay per transaction that are overhead exceeds the threshold
tolerated before a warning is generated
on the principal server. This delay is the
amount of overhead incurred while the
principal server instance waits for the
mirror server instance to write the
transaction's log record into the redo
queue. This value is relevant only in
high-safety mode.

For any one of these performance metrics, a system administrator can specify a threshold on a mirrored database.
For more information, see Setting Up and Managing Warning Thresholds, later in this topic.

Setting Up and Managing Warning Thresholds


A system administrator can configure one or more warning thresholds for the key mirroring performance metrics.
We recommend setting a threshold for a given warning on both partners to make sure that the warning persists if
the database fails over. The appropriate threshold on each partner depends on the performance capabilities of that
partner's system.
Warning thresholds can be configured and managed by using either of the following:
Database Mirroring Monitor
In Database Mirroring Monitor, the administrator can view the current configuration of warnings for a
selected database at both the principal and mirror server instances at the same time by selecting the
Warnings tabbed page. From there, the administrator can open the Set Warning Thresholds dialog box
to enable and configure one or more warning thresholds.
For an introduction to the Database Mirroring Monitor interface, see Database Mirroring Monitor
Overview. For information about launching Database Mirroring Monitor, see Start Database Mirroring
Monitor (SQL Server Management Studio).
System stored procedures
The following set of system stored procedures enable an administrator to set up and manage warning
thresholds on mirrored databases of one partner at a time.

PROCEDURE DESCRIPTION

sp_dbmmonitorchangealert (Transact-SQL) Adds or changes warning threshold for a specified


mirroring performance metric.

sp_dbmmonitorhelpalert (Transact-SQL) Returns information about warning thresholds on one or


all of several key database mirroring monitor performance
metrics.

sp_dbmmonitordropalert (Transact-SQL) Drops the warning for a specified performance metric.

Performance-Threshold Events Sent to the Windows Event Log


If warning thresholdis defined for a performance metric, when the status table is updated, the latest value is
evaluated against the threshold. If the threshold has been reached, the update procedure,
sp_dbmmonitorupdate, generates an informational event—a performance-threshold event— for the metric and
writes the event to the Microsoft Windows event log. The following table lists the event IDs of the performance-
threshold events.

PERFORMANCE METRIC EVENT ID

Unsent log 32042

Unrestored log 32043

Oldest unsent transaction 32040

Mirror commit overhead 32044

NOTE
An administrator can define alerts on any one or more of these events. For more information, see Using Alerts for a
Mirrored Database, later in this
topic.

Using Alerts for a Mirrored Database


An important part of monitoring a mirrored database is configuring alerts on significant database mirro events.
SQL Server generates the following types of database mirroring events:
Performance threshold events
For more information, see "Performance-Threshold Events Sent to the Windows Event Log" earlier in this
topic.
State-change events
These are Windows Management Instrumentation (WMI) events that are generated when changes occur in
the internal state of a database mirroring session.

NOTE
For more information, see WMI Provider for Server Events Concepts.

A system administrator can configure alerts on these by using SQL Server Agent or other applications,
such as Microsoft Operations Manager.
When you define alerts on database mirroring events, we recommend that you define warning thresholds
and alerts at both partner server instances. Individual events are generated at either the principal server or
the mirror server, but each partner can perform either role at any time. To make sure that an alert continues
to operate after a failover, the alert must be defined at both partners.
For more information, see the white paper about alerting on database mirroring events at this SQL Server
Web site. This white paper contains information about how to configure alerts using SQL Server Agent, the
database mirroring WMI events, and sample scripts.

IMPORTANT
For all mirroring sessions, we strongly recommend that you configure the database to send an alert on any state-change
events. Unless a state change is expected as the result of a manual configuration change, something has occurred that could
compromise your data. To help protect your data, identify and fix the cause of an unexpected state change.

Related Tasks
To create an alert using SQL Server Management Studio
Create an Alert Using an Error Number
Create a WMI Event Alert
To monitor database mirroring
Start Database Mirroring Monitor (SQL Server Management Studio)
sp_dbmmonitoraddmonitoring (Transact-SQL )
sp_dbmmonitorchangealert (Transact-SQL )
sp_dbmmonitorchangemonitoring (Transact-SQL )
sp_dbmmonitordropalert (Transact-SQL )
sp_dbmmonitordropmonitoring (Transact-SQL )
sp_dbmmonitorhelpalert (Transact-SQL )
sp_dbmmonitorhelpmonitoring (Transact-SQL )
sp_dbmmonitorresults (Transact-SQL )
sp_dbmmonitorupdate (Transact-SQL )
See Also
Database Mirroring (SQL Server)
Monitoring Database Mirroring (SQL Server)
Start Database Mirroring Monitor (SQL Server
Management Studio)
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse
Parallel Data Warehouse
The Database Mirroring Monitor is part of the SQL Server Monitor, which is launched from SQL Server
Management Studio.

NOTE
Database Mirroring Monitor is not available in every edition of Microsoft SQL Server. For a list of features that are
supported by the editions of SQL Server, see Features Supported by the Editions of SQL Server 2016.

To launch the Database Mirroring Monitor


1. After connecting to the principal server instance, in Object Explorer, click the server name to expand the
server tree.
2. Expand Databases, and select the database to be monitored.
3. Right-click the database, select Tasks, and then click Launch Database Mirroring Monitor.
4. In the Database Mirroring Monitor dialog box, click Register Mirrored Database to register one or
more mirrored database.

NOTE
When you register a database at one partner, the database is automatically registered at the other partner. If the
monitor already has connection credentials for the other partner instance, those are used to connect. Otherwise
the monitor attempts to connect using Windows Authentication. If you want to change the credentials used to
connect to either server instance, click Show the Manage Server Connections dialog box when I click OK.

For more information about Database Mirroring Monitor, see Database Mirroring Monitor Overview.

See Also
Database Mirroring (SQL Server)
Establish a Database Mirroring Session Using Windows Authentication (SQL Server Management Studio)
Database Mirroring Monitor Overview
6/12/2018 • 6 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
If you have the correct permissions, you can use Database Mirroring Monitor to monitor any subset of the
mirrored databases on a server instance. Monitoring enables you to verify whether and how well data is flowing in
the database mirroring session. Database Mirroring Monitor is also useful for troubleshooting the cause of
reduced data flow.
You can register any of your mirrored databases for monitoring on each of the failover partners individually.
When you register a database, Database Mirroring Monitor caches the following information about the database:
Database name
The names of the two partner server instances
The last known roles of each partner (principal or mirror)

Permissions
To monitor database mirroring, you must be a member of either the sysadmin fixed server role or the
dbm_monitor fixed database role in the msdb database on the server instance. If you are a member of
sysadmin or dbm_monitor on only one of the partner server instances, the monitor can connect only to that
partner; the monitor cannot retrieve information from the other partner.
If you are a member of just dbm_monitor on a server instance, you will have limited permissions on that server
instance. You will only be able to view the most recent status row. If you connect to a server instance using
dbm_monitor permissions, Database Mirroring Monitor informs you that you have limited permissions.

IMPORTANT
The dbm_monitor fixed database role is created in the msdb database when the first database is registered in Database
Mirroring Monitor. The new dbm_monitor role has no members until a system administrator assigns users to the role.

Navigation Tree
If any databases have been registered for monitoring by the Database Mirroring Monitor, a list of registered
databases is displayed in the navigation tree. The tree automatically refreshes every 30 seconds. To see the status
of a registered database, select it. For more information, see "Detail Pane," later in this topic.
For each registered database, the following information is displayed:
<Database_name> ( <Status> , <PRINCIPAL_SERVER> -> <MIRROR_SERVER> )
<Database_name>
The name of a mirrored database that is registered with the Database Mirroring Monitor.
<Status>
The possible statuses and their associated icons are as follows:
ICON STATUS DESCRIPTION

Warning icon Unknown The monitor is not connected to either


partner. The only available information
is what has been cached by the
monitor.

Warning icon Synchronizing The contents of the mirror database are


lagging behind the contents of the
principal database. The principal server
instance is sending log records to the
mirror server instance, which is
applying the changes to the mirror
database to roll it forward.

At the start of a database mirroring


session, the mirror and principal
databases are in this state.

Standard database cylinder Synchronized When the mirror server becomes


sufficiently caught up to the principal
server, the database state changes to
Synchronized. The database remains
in this state as long as the principal
server continues to send changes to
the mirror server and the mirror server
continues to apply changes to the
mirror database.

For high-safety mode, automatic


failover and manual failover are both
possible, without any data loss.

For high-performance mode, some data


loss is always possible, even in the
Synchronized state.

Warning icon Suspended The principal database is available but is


not sending any logs to the mirror
server.

Error icon Disconnected The server instance cannot connect to


its partner.

<PRINCIPAL_SERVER>
The name of the partner that is currently the principal server instance. The name is in the following format:
<SYSTEM_NAME>[\<instance_name>]
where <SYSTEM_NAME> is the name of the system on which the server instance resides. For a non-default
server instance, the instance name is also displayed: <SYSTEM_NAME>\<instance_name>.
<MIRROR_SERVER>
The name of the partner that is currently the mirror server instance. The format is the same as for the principal
server.

Detail Pane
The appearance of the monitor depends on whether a database is selected. When you open the monitor, the detail
pane displays a Register mirrored database link. Click this to register a database. Registered databases are listed
below the Database Mirroring Monitor node in the navigation tree. Database Mirroring Monitor always tries to
connect to every server instance for which it has stored credentials.
When you select a database, its status is displayed on the Status tabbed page in the detail pane. The content of
this page comes from both the principal and mirror server instances. The page is filled asynchronously as status is
gathered through separate connections to the principal and mirror server instances. The status automatically
refreshes at 30-second intervals.

NOTE
You cannot change the monitor's refresh rate, but you can refresh the status table from the Database Mirroring History
dialog box.

A system administrator can view the current configuration of warnings for the database by selecting the
Warnings tabbed page. From there, the administrator can launch the Set Warning Thresholds dialog box to
enable and configure one or more warning thresholds.
In the banner above the tabs, the detail pane displays the last time the monitor refreshed the status information as,
Last refresh:<date><time>. Usually, the Database Mirroring Monitor retrieves status information from the
principal and mirror server instances at different times. The older of these two refresh times is displayed.

Action Menu
The Action menu always contains the following commands:

COMMAND DESCRIPTION

Register Mirrored Database... Opens the Register Mirrored Database dialog box. Use this
dialog box to register one or more mirrored databases on a
given server instance by adding the database or databases to
the Database Mirroring Monitor. When a database is added,
Database Mirroring Monitor locally caches information about
the database, its partners, and how to connect to the
partners.

Manage Server Instance Connections… When you select this command, the Manage Server
Connections dialog box opens. There, you can choose a
server instance for which you want to specify credentials for
the monitor to use when connecting to a given partner.

To edit the credentials for a partner, locate its entry in the


Server instances grid, and click Edit on that row. The
Connect to Server dialog box appears with the server
instance name fixed and the credential controls initialized to
the current cached value. Change the authentication
information as necessary and click Connect. If the credentials
have sufficient privileges, the Connect Using column is
updated with the new credentials.

If you select a database, the Action menu also contains the following commands.

COMMAND DESCRIPTION

Unregister This Database Removes the selected database from Database Mirroring
Monitor.
COMMAND DESCRIPTION

Set Warning Thresholds… Opens the Set Warning Thresholds dialog box. There a
system administrator can enable or disable warnings for the
database on each of the partners and change the threshold of
each warning. We recommend setting a threshold for a given
warning on both partners to ensure that the warning persists
if the database fails over. The appropriate threshold for each
partner depends on the performance capabilities of that
partner's system.

An event is written to the event log for a performance only if


its value is at or above its threshold when the status table is
being updated. If a peak value reaches the threshold
momentarily between status updates that peak is missed.

To monitor database mirroring by using SQL Server Management Studio to


Start Database Mirroring Monitor (SQL Server Management Studio)

See Also
Monitoring Database Mirroring (SQL Server)
Start the Configuring Database Mirroring Security Wizard (SQL Server Management Studio)
Register Mirrored Database
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
Use this dialog box to register one or more mirrored databases on a given server instance by adding the database
or databases to the Database Mirroring Monitor. When a database is added, Database Mirroring Monitor locally
caches information about the database, its partners, and how to connect to the partners.

IMPORTANT
If you are a member of the sysadmin fixed server role on the principal server instance but not on the mirror server instance,
you can only see status on the principal server instance.

To use SQL Server Management Studio to monitor database mirroring


Start Database Mirroring Monitor (SQL Server Management Studio)

Options
Server instance
Select a server instance from the list, which contains server instances to which Database Mirroring Monitor already
has a connection stored, or click Connect. To specify new credentials for a listed server instance, click Connect and
connect using the new credentials.

NOTE
To register databases on multiple server instances, after you finish checking the desired databases for one server instance,
click Apply, and then select another server instance.

Connect
To specify new credentials for the server instance, click Connect and connect using the new credentials. While
connecting to a server instance, Database Mirroring Monitor displays Waiting for data.
Mirrored databases
The Mirrored databases grid lists the mirrored databases on the server instance.
The grid contains the following columns:

COLUMN NAME DESCRIPTION

Register Check each of the databases that you want to register. If a


database is currently monitored, its check box is checked and
is disabled.

Note: To unregister a database, close the Registered


Mirrored Database dialog box, select the database in the
navigation tree, and select Unregister from the Action menu.

Database The name of a mirrored database on the selected server


instance.
COLUMN NAME DESCRIPTION

Current Role The current mirroring role of the database, either Principal or
Mirror, on the selected server instance.

Partner (Connect as) The name of the failover partner for the database. Either
Windows Authentication of console user or SQL Server
Authentication of login '<login name>' is displayed within
the parentheses. This is the authentication information
currently used, if the instance has been added before, or that
will be used, if this instance has not been added to the
monitor.

Show the Manage Server Connections dialog box when I click OK.
By default, Database Mirroring Monitor uses Windows Authentication credentials for partner server instances for
which credentials have not been previously given. Enable this option to change the credentials for one or more
server instances when you finish registering databases.
If this option is enabled, when you click OK, the Manage Server Connections dialog box opens. There, you can
choose a server instance for which you want to specify credentials for the monitor to use when connecting to a
given failover partner.
To edit the credentials for a partner, locate its entry in the Server instances grid, and click Edit on that row. This
opens the Connect to Server dialog box for that server instance name, with the credential controls initialized to
the current cached value. Change the credentials as necessary and click Connect. If the credentials have sufficient
privileges, the Connect Using column is updated with the new credentials.
Apply
Click this button to register the selected databases (and save credentials for the partner server instances) while
keeping the dialog box open.

See Also
Start Database Mirroring Monitor (SQL Server Management Studio)
Monitoring Database Mirroring (SQL Server)
Start the Configuring Database Mirroring Security Wizard (SQL Server Management Studio)
Database Mirroring Monitor (Status Page)
6/12/2018 • 5 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
This read-only page displays the most recent mirroring status for the principal and mirror server instances of the
database currently selected in the navigation tree. If information about an instance is currently unavailable, some of
the cells in the Status grid corresponding to that instance are grayed out and display Unknown.
To use SQL Server Management Studio to monitor database mirroring
Start Database Mirroring Monitor (SQL Server Management Studio)

Options
Status
Displays a grid containing the most recent high-level mirroring status of each of the principal and mirror server
instances. The rows of the Status grid are in the following order:
Principal server instance
Mirror server instance
The columns are as follows:

COLUMN NAME DESCRIPTION

Server Instance Name of the server instance whose status is displayed in the
Status row.

Current Role Current role of the server instance, either Principal or Mirror.
COLUMN NAME DESCRIPTION

Mirroring State The mirroring state reported by the server instance and an
icon that indicates the severity of the state. The possible
statuses and their associated icons are as follows:

Icon: —, status Unknown. The monitor is not connected to


either partner. The only available information is what has been
cached by the monitor.

Icon: Warning icon, status Synchronizing. The contents of the


mirror database are lagging behind the contents of the
principal database. The principal server instance is sending log
records to the mirror server instance, which is applying the
changes to the mirror database to roll it forward. At the start
of a database mirroring session, the mirror and principal
databases are in this state.

Icon: Standard database cylinder, status Synchronized. When


the mirror server becomes sufficiently caught up to the
principal server, the database state changes to Synchronized.
The database remains in this state as long as the principal
server is sending changes to the mirror server and the mirror
server is applying changes to the mirror database. For high-
safety mode, automatic failover and manual failover are both
possible, without any data loss. For high-performance mode,
some data loss is always possible, even in the Synchronized
state.

Icon: Warning icon, status Suspended.


The principal database is available but is not sending any logs
to the mirror server.

Icon: Error icon, status Disconnected. The server instance


cannot connect to its partner.

Witness Connection Connection status of the witness, preceded by a status icon,


Unknown, Connected, or Disconnected.

History Click to display the history of mirroring on the server instance.


This opens the Database Mirroring History dialog box,
which displays the history of mirroring status and statistics for
a mirrored database on a given server instance.

The History button is dimmed if the monitor is not connected


to the server instance.

Principal log ( <time> )


Status of the log on the principal server instance as of the local time on the server instance, indicated by <time>.
The following parameters are displayed:
Unsent log
The amount of log waiting in the send queue (in kilobytes).
Oldest unsent transaction
Age of the oldest unsent transaction in the send queue. The age of this transaction indicates how many minutes of
transactions have not yet been sent to the mirror server instance. This value helps measure the potential for data
loss in terms of time.
Time to send log (estimated)
Approximate amount of time the principal server instance requires to send the log that is currently in the send
queue to the mirror server instance (the send rate). Because the rate of incoming transactions can vary significantly,
the time to send log is an estimate. However, the send rate can be useful for roughly estimating the time required
for a manual failover.
Current send rate
Rate at which transactions are being sent to the mirror server instance in kilobytes (KB ) per second.
Current rate of new transactions
Rate at which incoming transactions are being entered into the principal's log in KB per second. To determine
whether mirroring is falling behind, staying up, or catching up, compare this value to the Estimated time to send
log value.
Mirror log ( <time> )
Log status on the mirror server instance as of the local time on the server instance, indicated by <time>. The
following parameters are displayed:
Unrestored log
The amount of log waiting in the redo queue (in KB ).
Time to restore log (estimated)
Approximate number of minutes required for the log currently in the redo queue to be applied to the mirror
database.
Current restore rate
Rate at which transactions are being restored into the mirror database (in KB per second).
Mirroring commit overhead
Number of milliseconds of average delay per transaction tolerated before a warning is generated on the principal
server. This delay is the amount of overhead incurred while the principal server instance waits for the mirror server
instance to write the transaction's log record into the redo queue. This value is relevant only in high-safety mode.
Time to send and restore all current log (estimated)
Time needed to send and restore all of the log that has been committed at the principal as of the current time. This
time may be less than the sum of the values of the Time to send log (estimated) and Time to restore log
(estimated) fields, because sending and restoring can operate in parallel. This estimate does predict the time
required to send and restore new transactions committed at the principal while working through backlogs in the
send queue.
Witness address
Network address of the witness server instance. For information about the format of this address, see Specify a
Server Network Address (Database Mirroring).
Operating mode
The operating mode of the database mirroring session:
High performance (asynchronous)
High safety without automatic failover (synchronous)
High safety with automatic failover (synchronous)

Remarks
Members of the dbm_monitor fixed database role can view the existing mirroring status by using either Database
Mirroring Monitor or the sp_dbmmonitorresults stored procedure. But these users cannot update the status
table. They depend on the Database Mirroring Monitor Jobto update the status table at regular intervals. To
learn the age of the displayed status a user can look at the times in the Principal log (<time>) and Mirror log
(<time>) labels.
If this job does not exist or SQL Server Agent is stopped, the status becomes increasingly stale and may no longer
reflect the configuration of the mirroring session. For example, after a failover, the partners might appear to share
the same role—principal or mirror, or the current principal server might be shown as the mirror, while the current
mirror server is shown as the principal.

See Also
Start Database Mirroring Monitor (SQL Server Management Studio)
Monitoring Database Mirroring (SQL Server)
Start the Configuring Database Mirroring Security Wizard (SQL Server Management Studio)
Database Mirroring History
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
Use this dialog box to view the history of mirroring status for a mirrored database on a specified server instance.
To use SQL Server Management Studio to monitor database mirroring
Start Database Mirroring Monitor (SQL Server Management Studio)

Options
Server instance
Name of the server instance from which the history is being reported.
Database
Name of the database whose history is being reported.
Filter list by
Lists filter values. Choosing a new value refreshes the grid automatically.
The possible filter values are:
Last two hours
Last four hours
Last eight hours
Last day
Last two days
Last 100 records
Last 500 records
Last 1000 records
All records
Refresh
Click to refresh the history list.

NOTE
This dialog box does not automatically refresh the history list. To refresh the list, either click Refresh or choose another filter
option. Only members of the sysadmin fixed server role can update the mirroring history.

History
Displays the history list. Clicking on a column header sorts the grid by that column. The list contains the following
columns:
COLUMN NAME DESCRIPTION

Time Recorded Timestamp of the history row.

Role Current mirroring role of the server instance for this database,
either Principal or Mirror.

Mirroring State State of the database:

Disconnected

Pending Failover

Suspended

Synchronized

Synchronizing

Unknown

Witness Connection State of the witness connection in the mirroring session of the
database, either Connected or Disconnected. If there is no
witness, the value is NULL.

Unsent Log Size, in kilobytes (KB), of the unsent log in the send queue on
the principal server instance.

Time to Send Approximate amount of time the principal server instance will
require to send the log that is currently in the send queue to
the mirror server instance (the send rate). Because the rate of
incoming transactions can vary significantly, the time to send
log is an estimate. However, the send rate can be useful for
roughly estimating the time required for a manual failover.

Send Rate Rate at which transactions are being sent to the mirror server
instance, in KB per second.

New Transaction Rate Rate at which incoming transactions are being entered into
the principal's log, in KB per second. To determine whether
mirroring is falling behind, staying up, or catching up, compare
this value to the Time to Send value.

Oldest Unsent Transaction Age of the oldest unsent transaction in the send queue. The
age of this transaction indicates how many minutes of
transactions have not yet been sent to the mirror server
instance. This value helps measure the potential for data loss
in terms of time.

Unrestored Log The amount of log waiting in the redo queue, in KB.

Time to Restore Approximate number of minutes required for the log currently
in the redo queue to be applied to the mirror database.

Restore Rate Rate at which transactions are being restored into the mirror
database, in KB per second.
COLUMN NAME DESCRIPTION

Mirror Commit Overhead Average delay per transaction in milliseconds (only in


synchronous modes). This delay is the amount of overhead
incurred while the principal server instance waits for the mirror
server instance to write the transaction's log record into the
redo queue.

See Also
Start Database Mirroring Monitor (SQL Server Management Studio)
Monitoring Database Mirroring (SQL Server)
Start the Configuring Database Mirroring Security Wizard (SQL Server Management Studio)
Database Mirroring Monitor (Warnings Page)
6/12/2018 • 4 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
Displays a read-only list of warnings supported on database mirroring events and the specified warning threshold
values, if available.
To use SQL Server Management Studio to monitor database mirroring
Start Database Mirroring Monitor (SQL Server Management Studio)

Columns
Warning
The warnings for which you can define a threshold include:

WARNING THRESHOLD

Warn if the unsent log exceeds the threshold Specifies how many kilobytes (KB) of unsent log will generate a
warning on the principal server instance. This warning helps
measure the potential for data loss in terms of KB, and is
particularly relevant for high-performance mode. However, the
warning is also relevant for high-safety mode when mirroring
is paused or suspended because the partners become
disconnected.

Warn if the unrestored log exceeds the threshold Specifies how many KB of unrestored log will generate a
warning on the mirror server instance. This warning is useful
for measuring failover time in terms of kilobytes. Failover time
consists mainly of the time that the former mirror server
requires to roll forward any log remaining in its redo queue,
plus a short additional time.

Note: For an automatic failover, the time for the system to


notice the error is independent of the failover time.

For more information, see Estimate the Interruption of Service


During Role Switching (Database Mirroring).

Warn if the age of the oldest unsent transaction exceeds Specifies the number of minutes worth of transactions that
the threshold can accumulate in the send queue before a warning is
generated on the principal server instance. This warning helps
measure the potential for data loss in terms of time, and is
particularly relevant for high-performance mode. However, the
warning is also relevant for high-safety mode when mirroring
is paused or suspended because the partners become
disconnected.

Warn if the mirror commit overhead exceeds the Specifies the number of milliseconds of average delay per
threshold transaction tolerated before a warning is generated on the
principal server. This delay is the amount of overhead incurred
while the principal server instance waits for the mirror server
instance to write the transaction's log record into the redo
queue. This value is relevant only in high-safety mode.
Threshold at ' <server_instance> '
For each of the warnings, displays the current user-specified threshold, if any, for one of the server instances. The
full instance name of the server instance is indicated in the corresponding column heading.
For more information, see "Remarks," later in this topic.
Set Thresholds
Click this button to set a threshold for one warning on each of the failover partners.
For more information, see "Remarks," later in this topic.

Remarks
If information is currently unavailable for a server instance, the cells of the corresponding Threshold at column
display a gray background and watermark text. If the monitor is not connected to the server instance, in every cell
the grid displays either Not connected to <SYSTEM_NAME> or Not connected to
<SYSTEM_NAME>\<instance_name>, depending on whether the instance is the default instance or a named
instance. If the monitor is waiting for a query to return, the grid displays Waiting for data… in every cell.
When information is available, the cell for each warning displays either a specified threshold value (and unit of
measurement), or Not enabled.
If a threshold is exceeded at the time the status table is refreshed, an event is logged to the Windows event log
when the status row is recorded. By default, the status row is recorded once a minute if the monitor is not running.
You can configure an alert on each type of logged event by using the SQL Server Agent or another program, such
as Microsoft Management Operations Manager (MOM ).
On a given partner, the events logged depend on its current role, principal or mirror. However, we recommend that
you set a warning threshold for a given event on both partners to ensure that the warning persists if the database
fails over. The appropriate threshold for each partner depends on the performance capabilities of that partner's
system.

NOTE
You can also use the sp_dbmmonitorchangealert system stored procedure to configure thresholds for the equivalent
events—unsent log, unrecovered log, oldest unsent transaction, and mirror commit overhead. For more information, see
sp_dbmmonitorchangealert (Transact-SQL).

The following table shows the event ID associated with each warning.

DATABASE MIRRORING MONITOR


WARNING EVENT NAME EVENT ID

Warn if the unsent log exceeds the Unsent log 32042


threshold

Warn if the unrestored log exceeds Unrestored log 32043


the threshold

Warn if the age of the oldest unsent Oldest unsent transaction 32044
transaction exceeds the threshold

Warn if the mirror commit overhead Mirror commit overhead 32045


exceeds the threshold
Permissions
For full access, requires membership in the sysadmin fixed server role. Only members of sysadmin can configure
and view warning thresholds for key performance metrics.
Membership in the dbm_monitor role enables you to view only the most recent status row on the Warnings
Page.

See Also
Start Database Mirroring Monitor (SQL Server Management Studio)
Monitoring Database Mirroring (SQL Server)
Start the Configuring Database Mirroring Security Wizard (SQL Server Management Studio)
Set Warning Thresholds
6/12/2018 • 3 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
Use this dialog box to enable and configure one or more warning thresholds for the database selected in the
navigation tree of the Database Mirroring Monitor dialog box.
The dialog box tries to connect to both server instances. These connections are established asynchronously. The
dialog shows the connection status of each partner. If the partner is not connected, you can click Connect.
To use SQL Server Management Studio to monitor database mirroring
Start Database Mirroring Monitor (SQL Server Management Studio)

Options
Server instance and its connection status
Name of a partner server instance in the form SYSTEM\INSTANCE_NAME. For a default server instance, only the
system name is displayed.
This field also indicates whether the monitor is currently connected to this server instance. The possible connection
statuses are:
Not connected to server_instance_name
Trying to connect to server_instance_name
Connected to server_instance_name

NOTE
If you do are not a member of the sysadmin fixed server role, this status is Connected to server_instance_name
(Limited permissions).

The name of each of the partner server instances is displayed in a separate Server instance and its
connection status field. The top field lists the principal server when the monitor started running.
Connect/Cancel
A Connect/Cancel button is associated with each Server instance and its connection status fields. The state
of the button depends on the connection status:
If there is no connection to the server instance, the button text is Connect. Click to connect to the server
instance.
When a connection attempt is in progress, the button text is Cancel. Click to cancel the connection attempt.
If the server is connected, the button text is Connected, and the button is dimmed.
Thresholds
The Thresholds grid displays the warnings settings for the two server instances.
NOTE
If a server instance is not connected, its columns are displayed with empty cells and a gray background. When the connection
opens, the grid automatically displays the content from the instance.

The grid contains the following columns:


Warnings
Lists the supported warnings:

WARNING DESCRIPTION

Warn if the unsent log exceeds the threshold The threshold indicates the number of kilobytes (KB) of the
unsent log in the send queue on the principal.

Warn if the unrestored log exceeds the threshold The threshold indicates the number of KB of the redo queue
on the mirror server instance.

Warn if the age of the oldest unsent transaction exceeds The threshold indicates the number of minutes of transactions
the threshold that have not yet been sent from the send queue to the
mirror server instance. This value helps measure the potential
for data loss in terms of time.

Warn if the mirror commit overhead exceeds the The threshold indicates the number of milliseconds of delay
threshold per transaction (relevant only in high-safety mode). This delay
is the amount of overhead incurred while the principal server
instance waits for the mirror server instance to write the
transaction's log record into the redo queue.

Enabled at ' <server instance> '


A blank check box indicates that the warning is currently disabled on the server instance. To enable a warning, click
its check box.
Threshold at ' <server instance> '
When a warning is enabled, set the threshold on the left side of this column. An event occurs if the specified
threshold has been reached when the status table is updated. If you disable a threshold after configuring a value,
your value remains in this field and will be used if you re-enable the warning.
When a warning is not enabled, this field is inactive.
OK
Clicking OK closes this dialog box and displays the currently specified values of warning thresholds in the
Thresholds grid on the Warningstabbed page.

Remarks
A threshold is only applicable at one partner at a time, but we recommend that you set a threshold for a given
event on both partners to ensure that the warning persists if the database fails over. The appropriate threshold for
each partner depends on the performance capabilities of that partner's system.
An event is written to the event log for a performance only if its value is at or above its threshold when the status
table is being updated. If a peak value reaches the threshold momentarily between status updates that peak is
missed.

See Also
Start Database Mirroring Monitor (SQL Server Management Studio)
Monitoring Database Mirroring (SQL Server)
Start the Configuring Database Mirroring Security Wizard (SQL Server Management Studio)
View the State of a Mirrored Database (SQL Server
Management Studio)
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
During a database mirroring session, you can view the status on the Mirroring page of the Database Properties
dialog box.
To view the status of a database mirroring session
1. After connecting to the principal server instance, in Object Explorer, click the server name to expand the
server tree.
2. Expand Databases, and select the database to be mirrored.
3. Right-click the database, select Tasks, and then click Mirror. This opens the Mirroring page of the
Database Properties dialog box.
4. After mirroring begins, the Status panel displays the status of the database mirroring session as of when
you selected the Mirroring page or clicked the Refresh button. The possible states are as follows:

STATES EXPLANATION

<blank> No database mirroring session exists and there is no


activity to report on the Mirroring page.

Paused The principal database is running but is not sending any


logs to the mirror server. The mirror copy of the database
is not available.

No connection The principal server instance cannot connect to its partner


or to the witness server instance (if any)

Synchronizing The contents of the mirror database are lagging behind


the contents of the principal database. The principal server
instance is sending log records to the mirror server
instance, which is applying the changes to the mirror
database to roll it forward.

At the start of a database mirroring session, the mirror


and principal databases are in the synchronizing state.

Failover On the principal server instance, a manual failover (role


swap) has begun but has not yet accepted by the mirror.

Synchronized The mirror database contains the same data as the


principal database. Manual and automatic failover are
possible only in the synchronized state.

See Also
Mirroring States (SQL Server)
Database Mirroring: Interoperability and Coexistence
(SQL Server)
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
Database mirroring can be used with the following features or components of SQL Server:
Always On Failover Cluster Instances (SQL Server Failover Clustering)
Change data capture (and change tracking)
Database snapshots
Full-text catalogs
Log shipping
Replication
Database mirroring does not interoperate with the following:
Cross-database transactions/distributed transactions
For information about why such transactions are not supported, see Cross-Database Transactions and
Distributed Transactions for Always On Availability Groups and Database Mirroring (SQL Server).
Always On availability groups

See Also
Database Mirroring (SQL Server)
Database Mirroring and SQL Server Failover Cluster
Instances
6/12/2018 • 4 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
A failover cluster is a combination of one or more physical disks in a Microsoft Cluster Service (MSCS ) cluster
group, known as a resource group, that are participating nodes of the cluster. The resource group is configured as a
failover clustered instance that hosts an instance of SQL Server. A SQL Server failover clustered instance appears
on the network as if it were a single computer, but has functionality that provides failover from one node to
another if one node becomes unavailable. For more information, see Always On Failover Cluster Instances (SQL
Server).
Failover clusters provide high-availability support for an entire Microsoft SQL Server instance, in contrast to
database mirroring, which provides high-availability support for a single database. Database mirroring works
between failover clusters and, also, between a failover cluster and a nonclustered host.

NOTE
For an introduction to database mirroring, see Database Mirroring (SQL Server).

Mirroring and Clustering


Typically, when mirroring is used with clustering, the principal server and mirror server both reside on clusters,
with the principal server running on the failover clustered instance of one cluster and the mirror server running on
the failover clustered instance of a different cluster. You can establish a mirroring session in which one partner
resides on the failover clustered instance of a cluster and the other partner resides on a separate, unclustered
computer, however.
If a cluster failover makes a principal server temporarily unavailable, client connections are disconnected from the
database. After the cluster failover completes, clients can reconnect to the principal server on the same cluster, or
on a different cluster or an unclustered computer, depending on the operating mode. Therefore, when deciding
how to configure database mirroring in a clustered environment, the operating mode you use for mirroring is
significant.
High-Safety mode Session with Automatic Failover
If you intend to mirror a database in high-safety mode with automatic failover, a two-cluster configuration is
recommended for the partners. This configuration provides maximum availability. The witness can reside either on
a third cluster or on an unclustered computer.
If the node running the current principal server fails, automatic failover of the database begins within a few
seconds, while the cluster is still failing over to another node. The database mirroring session fails over to the
mirror server on the other cluster or unclustered computer, and the former mirror server becomes the principal
server. The new principal server rolls forward its copy of the database as quickly as possible and brings it online as
the principal database. After the cluster failover completes, which typically takes several minutes, the failover
clustered instance that was formerly the principal server becomes the mirror server.
The following illustration shows an automatic failover between clusters in a mirroring session running in high-
safety mode with a witness (which supports automatic failover).
The three server instances in the mirroring session reside on three distinct clusters: Cluster_A, Cluster_B, and
Cluster_C. On each cluster, a default instance of SQL Server is running as a SQL Server failover clustered
instance. When the mirroring session starts, the failover clustered instance on Cluster_A is the principal server, the
failover clustered instance on Cluster_B is the mirror server, and the failover clustered instance on Cluster_C is
the witness in the mirroring session. Eventually, the active node on Cluster_A fails, which causes the principal
server to become unavailable.
Before the cluster has time to fail over, the loss of the principal server is detected by the mirror server, with the help
of the witness. The mirror server rolls forward its database and brings it online as the new principal database as
quickly as possible. When Cluster_A finishes failing over, the former principal server is now the mirror server, and
it synchronizes its database with the current principal database on Cluster_B.
High-Safety Mode Session Without Automatic Failover
If you are mirroring a database in high-safety mode without automatic failover, another node in the cluster will act
as the principal server if the node running the current principal server fails. Note that while the cluster is
unavailable, the database is unavailable.
High-Performance Mode Session
If you intend to mirror a database in high-performance mode, consider placing the principal server on the failover
clustered instance of a cluster and placing the mirror server on an unclustered server in a remote location. If the
cluster fails over to a different node, the failover clustered instance will continue as the principal server in the
mirroring session. If the entire cluster has problems, you can force service onto the mirror server.
To set up a new SQL Server failover cluster
Create a New SQL Server Failover Cluster (Setup)
To set up database mirroring
Setting Up Database Mirroring (SQL Server)
Establish a Database Mirroring Session Using Windows Authentication (SQL Server Management Studio)

See Also
Database Mirroring (SQL Server)
Database Mirroring Operating Modes
Always On Failover Cluster Instances (SQL Server)
Database Mirroring and Log Shipping (SQL Server)
6/12/2018 • 6 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
A given database can be mirrored or log shipped; it can also be simultaneously mirrored and log shipped. To
choose what approach to use, consider the following:
How many destination servers do you require?
If you require only a single destination database, database mirroring is the recommended solution.
If you require more than one destination database, you need to use log shipping, either alone or with
database mirroring. Combining these approaches gives you the benefits of database mirroring along with
the support for multiple destinations provided by log shipping.
If you need to delay restoring log on the destination database (typically, to protect against logical errors),
use log shipping, alone or with database mirroring.
This topic discusses considerations for combining log shipping and database mirroring.

NOTE
For introductions to these technologies, see Database Mirroring (SQL Server) and About Log Shipping (SQL Server).

Combining Log Shipping and Database Mirroring


The principal database in a mirroring session can also act as the primary database in a log shipping configuration,
or vice versa, as the log shipping backup share is intact. The database mirroring session run in any operating
mode, whether synchronous (with transaction safety set to FULL ) or asynchronous (with transaction safety set to
OFF ).

NOTE
To use database mirroring on a database, the full recovery model is always required.

Typically, when combining log shipping and database mirroring, the mirroring session is established before log
shipping, although this is not required. Then the current principal database is configured as the log shipping
primary (the principal/primary database), along with one or more remote secondary databases. Also, the mirror
database must be configured as a log shipping primary (the mirror/primary database). The log shipping
secondary databases should be on different server instances than either the principal/primary server or
mirror/primary server.

NOTE
The case sensitivity settings of the servers involved in log shipping should match.

During a log shipping session, backup jobs on the primary database create log backups in a backup folder. From
there, the backups are copied by the copy jobs of the secondary servers. For the backup jobs and copy jobs to
succeed, they must have access to the log shipping backup folder. To maximize availability of the primary server,
we recommend that you establish the backup folder in a shared backup location on a separate host computer.
Ensure that all the log shipping servers, including the mirror/primary server, can access the shared backup
location (known as a backup share).
To allow log shipping to continue after database mirroring fails over, you must also configure the mirror server as
a primary server, using the same configuration you use for the primary on the principal database. The mirror
database is in the restoring state, which prevents the backup jobs from backing up the log on the mirror database.
This ensures that the mirror/primary database does not interfere with the principal/primary database whose log
backups are currently being copied by secondary servers. To prevent spurious alerts, after the backup job executes
on the mirror/primary database, the backup job logs a message to the log_shipping_monitor_history_detail
table, and the agent job returns a status of success.
The mirror/primary database is inactive in the log shipping session. However, if mirroring fails over, the former
mirror database comes online as the principal database. At that point, that database also becomes active as the log
shipping primary database. The log shipping backup jobs that were previously unable to ship log on that
database, begin shipping log. Conversely, a failover causes the former principal/primary database to become the
new mirror/primary database and enter the restoring state, and backup jobs on that database cease to backup log.

NOTE
In the event of an automatic failover, the switch to the mirror role occurs when the former principal/primary database rejoins
the mirroring session.

To run in high-safety mode with automatic failover the mirroring session is configured with an additional server
instance known as the witness. If the principal database is lost for any reason after the database is synchronized
and if the mirror server and witness can still communicate with each other, automatic failover occurs. An
automatic failover causes mirror server to assume the principal role and bring its database online as the principal
database. If the log shipping backup location is accessible to the new principal/primary server, its backup jobs
begin to ship log backups to that location. The database mirroring synchronous mode guarantees that the log
chain is unaffected by a mirroring failover and that only valid log is restored. The secondary servers continue to
copy log backups without knowing that a different server instance has become the primary server.
When using a local log shipping monitor, no special considerations are necessary to accommodate this scenario.
For information about using a remote monitoring instance with this scenario, see, "The Impact of Database
Mirroring on a Remote Monitoring Instance," later in this topic.

Failing over from the Principal to the Mirror database


The following figure shows how log shipping and database mirroring work together when mirroring is running in
high-safety mode with automatic failover. Initially, Server_A is both the principal server for mirroring and the
primary server for log shipping. Server_B is the mirror server and is also configured as a primary server, which is
currently inactive. Server_C and Server_D are log shipping secondary servers. To maximize availability of the log
shipping session, the backup location is on a share directory on a separate host computer.
After a mirroring failover, the primary server name defined on the secondary server is unchanged. .

The Impact of Database Mirroring on a Remote Monitoring Instance


When log shipping uses with a remote monitoring instance, combining the log shipping session and database
mirroring affects the information in the monitor tables. The information about the primary is a combination of the
one configured at the principal/primary and the monitor configured on each secondary.
To keep monitoring as seamless as possible, when you use a remote monitor, we recommend that you specify the
original primary name when configuring the primary at the secondary. This approach also facilitates changing the
log shipping configuration from Microsoft SQL Server Agent. For more information about monitoring, see
Monitor Log Shipping (Transact-SQL ).

Setting Up Mirroring and Log Shipping Together


To set up database mirroring and log shipping together, the following steps are required:
1. Restore backups of the principal/primary database with NORECOVERY onto another server instance to be
later used as database mirroring mirror database for the principal/primary database. For more information,
see Prepare a Mirror Database for Mirroring (SQL Server).
2. Set up database mirroring. For more information, see Establish a Database Mirroring Session Using
Windows Authentication (SQL Server Management Studio) or Setting Up Database Mirroring (SQL
Server).
3. Restore backups of the principal/primary database to other server instances to be later used as log
shipping secondary databases for the primary database.
4. Set up log shipping on the principal database as the primary database for one or more secondary
databases.
You should set up a single share as the backup directory (a backup share). This ensures that after role
switching between the principal and mirror servers, backup jobs continue to write to the same directory as
before. A best practice is to ensure that this share is located on a different physical server from the servers
hosting the databases involved in mirroring and log shipping.
For more information, see Configure Log Shipping (SQL Server).
5. Manually failover from the principal to the mirror.
To perform a manual failover:
Manually Fail Over a Database Mirroring Session (SQL Server Management Studio)
Manually Fail Over a Database Mirroring Session (Transact-SQL )
6. Set up log shipping on the new principal (previously mirror) as the primary database.

IMPORTANT
Do not perform any setup from a secondary.

You must use the same backup share that you used in step 4.
The Transaction Log Shipping interface in SQL Server Management Studio supports only one primary
database per log shipping configuration. Therefore, you must use stored procedures to set up the new
principal as primary.
7. Perform another manual failover to fail back to the original principal.
Database Mirroring and Full-Text Catalogs (SQL
Server)
6/12/2018 • 2 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
To mirror a database that has a full-text catalog, use backup as usual to create a full database backup of the
principal database, and then restore the backup to copy the database to the mirror server. For more information,
see Prepare a Mirror Database for Mirroring (SQL Server).

Full-Text Catalog and Indexes Before Failover


In a newly created mirror database, the full-text catalog is the same as when the database was backed up. After
database mirroring starts, any catalog-level changes that were made by DDL statements (CREATE FULLTEXT
CATALOG, ALTER FULLTEXT CATALOG, DROP FULLTEXT CATALOG ) are logged and sent to the mirror server
to be replayed on the mirror database. However, index-level changes are not reproduced on the mirror database
because it is not logged on to the principal server. Therefore, as the contents of the full-text catalog change on the
principal database, the contents of the full-text catalog on the mirror database are unsynchronized.

Full-Text Indexes After Failover


After a failover, a full crawl of a full-text index on the new principal server might be required or useful in the
following situations:
If change-tracking is turned OFF on a full text index, you must start a full crawl on that index by using the
following statement:
ALTER FULLTEXT INDEX ON table_name START FULL POPUL ATION
If a full-text index is configured for automatic change tracking, the full-text index is automatically
synchronized. However, synchronization slows full-text performance somewhat. If performance is too slow,
you can cause a full crawl by setting change tracking off and then resetting it to automatic:
To set change tracking off:
ALTER FULLTEXT INDEX ON table_name SET CHANGE_TRACKING OFF
To set on automatic change tracking to automatic:
ALTER FULLTEXT INDEX ON table_name SET CHANGE_TRACKING AUTO

NOTE
To see whether auto change tracking is on, you can use the OBJECTPROPERTYEX function to query the
TableFullTextBackgroundUpdateIndexOn property of the table.

For more information, see ALTER FULLTEXT INDEX (Transact-SQL ).


NOTE
Starting a crawl after failover works the same as starting a crawl after a restore.

After Forcing Service


After service is forced to the mirror server (with possible data loss), start a full crawl. The method to use for
starting a full crawl depends on whether the full-text index is change tracked. For more information, see "Full-Text
Indexes After Failover," earlier in this topic.

See Also
ALTER FULLTEXT INDEX (Transact-SQL )
CREATE FULLTEXT INDEX (Transact-SQL )
DROP FULLTEXT INDEX (Transact-SQL )
Database Mirroring (SQL Server)
Back Up and Restore Full-Text Catalogs and Indexes
Database Mirroring and Database Snapshots (SQL
Server)
6/12/2018 • 3 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
You can take advantage of a mirror database that you are maintaining for availability purposes to offload
reporting. To use a mirror database for reporting, you can create a database snapshot on the mirror database and
direct client connection requests to the most recent snapshot. A database snapshot is a static, read-only,
transaction-consistent snapshot of its source database as it existed at the moment of the snapshot's creation. To
create a database snapshot on a mirror database, the database must be in the synchronized mirroring state.
Unlike the mirror database itself, a database snapshot is accessible to clients. As long as the mirror server is
communicating with the principal server, you can direct reporting clients to connect to a snapshot. Note that
because a database snapshot is static, new data is not available. To make relatively recent data available to your
users, you must create a new database snapshot periodically and have applications direct incoming client
connections to the newest snapshot.
A new database snapshot is almost empty, but it grows over time as more and more database pages are updated
for the first time. Because every snapshot on a database grows incrementally in this way, each database snapshot
consumes as much resources as a normal database. Depending on the configurations of the mirror server and
principal server, having an excessive number of database snapshots on a mirror database might decrease
performance on the principal database. Therefore, we recommend that you keep only a few relatively recent
snapshots on your mirror databases. Typically, after you create a replacement snapshot, you should redirect
incoming queries to the new snapshot and drop the earlier snapshot after any current queries complete.

NOTE
For more information about database snapshots, see Database Snapshots (SQL Server).

If role switching occurs, the database and its snapshots are restarted, temporarily disconnecting users. Afterwards,
the database snapshots remain on the server instance where they were created, which has become the new
principal database. Users can continue to use the snapshots after the failover. However, this places an additional
load on the new principal server. If performance is a concern in your environment, we recommend that you create
a snapshot on the new mirror database when it becomes available, redirect clients to the new snapshot, and drop
all of the database snapshots from the former mirror database.

NOTE
For a dedicated reporting solution that scales out well, consider replication. For more information, see SQL Server Replication.

Example
This example creates snapshots on a mirrored database.
Assume that the database of a database mirroring session is AdventureWorks2012. This example creates three
database snapshots on the mirror copy of the AdventureWorks database, which resides on the F drive. The
snapshots are named AdventureWorks_0600 , AdventureWorks_1200 , and AdventureWorks_1800 to identify their
approximate creation times.
1. Create the first database snapshot on the mirror of AdventureWorks2012.

CREATE DATABASE AdventureWorks_0600


ON (NAME = 'datafile', FILENAME = 'F:\AdventureWorks_0600.SNP')
AS SNAPSHOT OF AdventureWorks2012

2. Create the second database snapshot on the mirror of AdventureWorks2012. Users who are still using
AdventureWorks_0600 can continue to use it.

CREATE DATABASE AdventureWorks_1200


ON (NAME = 'datafile', FILENAME = 'F:\AdventureWorks_1200.SNP')
AS SNAPSHOT OF AdventureWorks2012

At this point, new client connections can be programmatically directed to the latest snapshot.
3. Create the third snapshot on the mirror AdventureWorks2012. Users who are still using
AdventureWorks_0600 or AdventureWorks_1200 can continue to use them.

CREATE DATABASE AdventureWorks_1800


ON (NAME = 'datafile', FILENAME = 'F:\AdventureWorks_1800.SNP')
AS SNAPSHOT OF AdventureWorks2012

At this point, new client connections can be programmatically directed to the latest snapshot.

Related Tasks
Create a Database Snapshot (Transact-SQL )
View a Database Snapshot (SQL Server)
Drop a Database Snapshot (Transact-SQL )

See Also
Database Snapshots (SQL Server)
Connect Clients to a Database Mirroring Session (SQL Server)
Database Mirroring and Replication (SQL Server)
6/12/2018 • 8 minutes to read • Edit Online

THIS TOPIC APPLIES TO: SQL Server Azure SQL Database Azure SQL Data Warehouse Parallel
Data Warehouse
Database mirroring can be used in conjunction with replication to improve availability for the publication
database. Database mirroring involves two copies of a single database that typically reside on different
computers. At any given time, only one copy of the database is currently available to clients. This copy is known as
the principal database. Updates made by clients to the principal database are applied on the other copy of the
database, known as the mirror database. Mirroring involves applying the transaction log from every insertion,
update, or deletion made on the principal database onto the mirror database.
Replication failover to a mirror is fully supported for publication databases, with limited support for subscription
databases. Database mirroring is not supported for the distribution database. For information about recovering a
distribution database or subscription database without any need to reconfigure replication, see Back Up and
Restore Replicated Databases.

NOTE
After a failover, the mirror becomes the principal. In this topic, "principal" and "mirror" always refer to the original principal
and mirror.

Requirements and Considerations for Using Replication with Database


Mirroring
Be aware of the following requirements and considerations when using replication with database mirroring:
The principal and mirror must share a Distributor. We recommend that this be a remote Distributor, which
provides greater fault tolerance if the Publisher has an unplanned failover.
Replication supports mirroring the publication database for merge replication and for transactional
replication with read-only Subscribers or queued updating Subscribers. Immediate updating Subscribers,
Oracle Publishers, Publishers in a peer-to-peer topology, and republishing are not supported.
Metadata and objects that exist outside the database are not copied to the mirror, including logins, jobs,
linked servers, and so on. If you require the metadata and objects at the mirror, you must copy them
manually. For more information, see Management of Logins and Jobs After Role Switching (SQL Server).

Configuring Replication with Database Mirroring


Configuring replication and database mirroring involves five steps. Each step is described in more detail in the
following section.
1. Configure the Publisher.
2. Configure database mirroring.
3. Configure the mirror to use the same Distributor as the principal.
4. Configure replication agents for failover.
5. Add the principal and mirror to Replication Monitor.
Steps 1 and 2 can also be performed in the opposite order.
To configure database mirroring for a publication database
1. Configure the Publisher:
a. We recommend using a remote Distributor. For more information about configuring distribution,
see Configure Distribution.
b. You can enable a database for snapshot and transactional publications and/or merge publications.
For mirrored databases that will contain more than one type of publication, you must enable the
database for both types at the same node using sp_replicationdboption. For example, you could
execute the following stored procedure calls at the principal:

exec sp_replicationdboption @dbname='<PublicationDatabase>', @optname='publish', @value=true;


exec sp_replicationdboption @dbname='<PublicationDatabase>', @optname='mergepublish',
@value=true;

For more information about creating publications, see Publish Data and Database Objects.
2. Configure database mirroring. For more information, see Establish a Database Mirroring Session Using
Windows Authentication (SQL Server Management Studio) and Setting Up Database Mirroring (SQL
Server).
3. Configure distribution for the mirror. Specify the mirror name as the Publisher, and specify the same
Distributor and snapshot folder that the principal uses. For example, if you are configuring replication with
stored procedures, execute sp_adddistpublisher at the Distributor; and then execute sp_adddistributor at
the mirror. For sp_adddistpublisher:
Set the value of the @publisher parameter to the network name of the mirror.
Set the value of the @working_directory parameter to the snapshot folder used by the principal.
4. Specify the mirror name for the –PublisherFailoverPartner agent parameter. Agent This parameter is
required for the following agents to identify the mirror after failover:
Snapshot Agent (for all publications)
Log Reader Agent (for all transactional publications)
Queue Reader Agent (for transactional publications that support queued updating subscriptions)
Merge Agent (for merge subscriptions)
SQL Server replication listener (replisapi.dll: for merge subscriptions synchronized using Web
synchronization)
SQL Merge ActiveX Control (for merge subscriptions synchronized with the control)
The Distribution Agent and Distribution ActiveX Control do not have this parameter because they
do not connect to the Publisher.
Agent parameter changes take effect the next time the agent is started. If the agent runs
continuously, you must stop and restart the agent. Parameters can be specified in agent profiles and
from the command prompt. For more information, see:
View and Modify Replication Agent Command Prompt Parameters (SQL Server Management
Studio)
Replication Agent Executables Concepts
We recommend adding the –PublisherFailoverPartner to an agent profile, and then specifying the
mirror name in the profile. For example, if you are configuring replication with stored procedures:

-- Execute sp_help_agent_profile in the context of the distribution database to get the list of
profiles.
-- Select the profile id of the profile that needs to be updated from the result set.
-- In the agent_type column returned by sp_help_agent_profile:
-- 1 = Snapshot Agent; 2 = Log Reader Agent; 3 = Distribution Agent; 4 = Merge Agent; 9 = Queue Reader
Agent.

exec sp_help_agent_profile;

-- Setting the -PublisherFailoverPartner parameter in the default Snapshot Agent profile (profile 1).
-- Execute sp_add_agent_parameter in the context of the distribution database.
exec sp_add_agent_parameter @profile_id = 1, @parameter_name = N'-PublisherFailoverPartner',
@parameter_value = N'<Failover Partner Name>';

-- Setting the -PublisherFailoverPartner parameter in the default Merge Agent profile (profile 6).
-- Execute sp_add_agent_parameter in the context of the distribution database.
exec sp_add_agent_parameter @profile_id = 6, @parameter_name = N'-PublisherFailoverPartner',
@parameter_value = N'<Failover Partner Name>';

5. Add the principal and mirror to Replication Monitor. For more information, see Add and Remove
Publishers from Replication Monitor.

Maintaining a Mirrored Publication Database


Maintaining a mirrored publication database is essentially the same as maintaining a non-mirrored database, with
the following considerations:
Administration and monitoring must occur at the active server. In SQL Server Management Studio,
publications appear under the Local Publications folder only for the active server. For example, if you
failover to the mirror, the publications are displayed at the mirror and are no longer displayed at the
principal. If the database fails over to the mirror, you might need to manually refresh Management Studio
and Replication Monitor for the change to be reflected.
Replication Monitor displays Publisher nodes in the object tree for both the principal and the mirror. If the
principal is the active server, publication information is displayed only under the principal node in
Replication Monitor.
If the mirror is the active server:
If an agent has an error, the error is indicated only on the principal node, not on the mirror node.
If the principal is unavailable, the principal and mirror nodes display identical lists of publications.
Monitoring should be performed on the publications under the mirror node.
When using stored procedures or Replication Management Objects (RMO ) to administer replication at the
mirror, for cases in which you specify the Publisher name, you must specify the name of the instance on
which the database was enabled for replication. To determine the appropriate name, use the function
publishingservername.
When a publication database is mirrored, the replication metadata stored in the mirrored database is
identical to the metadata stored in the principal database. Consequently, for publication databases enabled
for replication at the principal, the Publisher instance name stored in system tables at the mirror is the
name of the principal, not the mirror. This affects replication configuration and maintenance if the
publication database fails over to the mirror. For example, if you are configuring replication with stored
procedures on the mirror after a failover, and you want to add a pull subscription to a publication database
that was enabled at the principal, you must specify the principal name rather than the mirror name for the
@publisher parameter of sp_addpullsubscription or sp_addmergepullsubscription.
If you enable a publication database at the mirror after failover to the mirror, the Publisher instance name
stored in system tables is the name of the mirror; in this case, you would use the name of the mirror for the
@publisher parameter.

NOTE
In some cases, such as sp_addpublication, the @publisher parameter is supported only for non- SQL Server
Publishers; in these cases, it is not relevant for SQL Server database mirroring.

To synchronize a subscription in Management Studio after a failover: synchronize pull subscriptions from
the Subscriber; and synchronize push subscriptions from the active Publisher.
Replication Behavior if Mirroring is Removed
Keep the following issues in mind if database mirroring is removed from a published database:
If the publication database at the principal is no longer mirrored, replication continues to work unchanged
against the original principal.
If the publication database fails over from the principal to the mirror and the mirroring relationship is
subsequently disabled or removed, replication agents will not function against the mirror. If the principal is
permanently lost, disable and then reconfigure replication with the mirror specified as the Publisher.
If database mirroring is removed completely, the mirror database is in a recovery state and must be
restored in order to become functional. The behavior of the recovered database with respect to replication
depends on whether the KEEP_REPLICATION option is specified. This option forces the restore operation
to preserve replication settings when restoring a published database to a server other than that on which
the backup was created. Use the KEEP_REPLICATION option only when the other publication database is
unavailable. The option is not supported if the other publication database is still intact and replicating. For
more information about KEEP_REPLICATION, see RESTORE (Transact-SQL ).

Log Reader Agent Behavior


The following table describes Log Reader Agent behavior for the various operating modes of database mirroring.

OPERATING MODE LOG READER AGENT BEHAVIOR IF THE MIRROR IS UNAVAILABLE

High-safety mode with automatic failover If the mirror is unavailable, the Log Reader Agent propagates
commands to the distribution database. The principal cannot
failover to the mirror until the mirror is back online and has all
transactions from the principal.

High-performance mode If the mirror is unavailable, the principal database is running


exposed (that is, unmirrored). However, the Log Reader Agent
only replicates those transactions that are hardened on the
mirror. If service is forced and the mirror server assumes the
role of the principal, the Log Reader Agent will work against
the mirror and start picking up the new transactions.

Be aware that replication latency will increase if the mirror falls


behind the principal.
OPERATING MODE LOG READER AGENT BEHAVIOR IF THE MIRROR IS UNAVAILABLE

High-safety mode without automatic failover All committed transactions are guaranteed to be hardened to
disk on the mirror. The Log Reader Agent replicates only those
transactions that are hardened on the mirror. If the mirror is
unavailable, the principal disallows further activity in the
database; therefore the Log Reader Agent has no transactions
to replicate.

See Also
Replication Features and Tasks
Log Shipping and Replication (SQL Server)

You might also like