Microsoft SQL Server Community (http://sqlcommunity.

com)

SQLFEST
Author: Saleem Hakani | http://sqlcommunity.com

COPYRIGHT AND TRADEMARK NOTICES:
All contents of the this article are: Copyright 2007 by www.sqlcommunity.com and/or its suppliers. All rights reserved.

Page | 1

Author: Saleem Hakani | SQL Server Community
Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
Table of contents:
Topic 1) Overview of Database Mirroring 2) Comparing log shipping with database mirroring 3) Comparing fail-over clustering with database mirroring 4) Database mirroring roles and participants 5) Forming a quorum 6) Transaction safety and operating modes 7) Client redirection 8) Endpoints: Communication mechanism for database mirroring 9) Understanding different types of failovers and role switching 10) Pre-requisites for setting up database mirroring 11) Database mirroring setup flow 12) Setting up database mirroring using T-SQL 13) Viewing the database mirroring state 14) Monitoring database mirroring 15) Setting up database mirroring thresholds 16) Querying the status of performance metrics 17) Database mirroring maintenance and operations Changing modes and transaction safety using T-SQL Steps to take when rebooting, applying hot fixes or service packs Changing the default auto-failover timeout value Performing manual failover Performing forced failover Setting up database mirroring on low-bandwidth networks / modems Setting up database mirroring on local area network Geo-redundancy with database mirroring Preparing the mirror server for failover Mirroring multiple databases 18) What happens when you lose a server? 19) Viewing database mirroring information using T-SQL 20) Monitoring database mirroring performance 21) Suspending and resuming a mirror session 22) Making replication mirror-aware 23) Implementing database mirroring in production environment 24) Querying mirrored database using database snapshots 25) Documenting database mirroring environment Page Numbers 2 3 3 5 6 7 9 10 11 13 14 15 19 20 22 24 25 25 27 28 28 29 29 30 30 31 32 33 34 37 38 40 41 42 43

Page | 2

Author: Saleem Hakani | SQL Server Community
Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

Overview of Database Mirroring

SQLFEST

With the introduction of SP1 in SQL Server 2005, Microsoft introduced a new high availability technology called Database Mirroring. It works by transferring transaction log records for a database from the primary server to the secondary server, thereby maintaining a hot standby server. As with normal SQL Server operation, with Database Mirroring data changes are recorded in the transaction log before any changes to actual data pages are made. The log records are first placed in the principal database‘s log buffer in memory and then hardened to disk. Those transaction log records are copied to and replayed on the mirror server‘s database. Because the mirror database replays the principal's transaction log records, it duplicates the principal‘s database changes on the mirror‘s database. Note: Database Mirroring was also available prior to SP1 for SQL Server 2005 but was disabled by default; you could enable it by using the trace flag –T1400 during SQL Server start-up. Database Mirroring gives SQL Server 2005 a nearly instant standby capability by providing database-level failover. When Database Mirroring is enabled and the primary/principal database fails, the mirrored database on the standby SQL Server system becomes available within a few seconds. Database Mirroring works with all the standard hardware that supports SQL Server 2005 and it enables zero data loss in the event of a database failure. The mirror database will always be updated with the current transaction that‘s being processed on the primary database server.

High Level Database Mirroring

Page | 3

Author: Saleem Hakani | SQL Server Community
Copyright 2007 by www.sqlcommunity.com

Both the technologies provide protection on a per database basis and utilize SQL Server recovery capabilities. every technology has its advantages and disadvantages.com) You might ask this question as to why was there a need of introducing a new high availability technology when we already have log shipping.com . etc? Well.sqlcommunity. sometimes takes seconds Role change is fully automatic Fully automatic with the use of . Note: Log shipping is available only for user databases and not for system databases (same as Database Mirroring).NET 2.0 Server Limitation Failover Failover duration Role Change Client Redirection Role change is manual Manual changes required Page | 4 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. and then transaction logs from the primary database are continuously applied to the secondary database. In many cases database mirroring offers the same level of data redundancy as log shipping with the advantage of higher availability and automatic failover. Some of the major differences are compared in the next topic.Microsoft SQL Server Community (http://sqlcommunity. Log shipping works by restoring a full database backup to a secondary server. fail-over clustering. SQLFEST Comparing Log Shipping with Database Mirroring Log shipping provides you a warm standby of your data that can be brought online in the event your primary system fails for any reason. The following table lists some of the differences between Log Shipping and Database Mirroring: Consideration Data Transfer Log Shipping T-Logs are backed up and transferred to secondary server Can be applied to multiple stand-by servers Manual Can take more than 30 mins Database Mirroring Individual T-Log records are transferred using TCP endpoints Can be applied to only one mirror server Automatic Failover is fast.

the operating system and SQL Server work together to provide automatic system for failover. Failover clustering now supports up to eight nodes when running on Microsoft Windows Server 2003 Datacenter edition. it provides instance-wide high availability which can help you with hardware failure or can help you with scheduled maintenance. sometime takes seconds. Distance Limitation Virtually no distance limit Hardware Standard SQL Server 2005 hardware Setup is easy and completely within SQL Server Setup Page | 5 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. The following table lists some of the differences between failover clustering and database mirroring: SQLFEST Consideration Standby Type Protection from Disks H/A Level Failover Duration Failover clustering Hot Standby If the shared disk crashes your entire cluster is down Instance Level > = 30 seconds + Database Recovery < = 100 miles. protection against storage failures. standard hardware.com . SQL Server 2005 also extends clustering functionality to enable you to use clustering in conjunction with Analysis Services and Full-Text Search. etc. such as faster failover.sqlcommunity. Database Mirroring offers several advantages over failover clustering.Microsoft SQL Server Community (http://sqlcommunity. low maintenance. With SQL Server 2005. more with geographically-dispersed clusters Specific hardware required Setup is more complex at the system level Database Mirroring Instant Standby Provides redundancy in the event of a server and or storage failure Database Level Failover is fast. In case of failure. You can configure one node to failover during scheduled maintenance.com) Comparing Failover Clustering with Database Mirroring Failover clustering is another technology for maintaining your database servers highly available.

The mirror Server role 3. Operating mode Endpoints Let‘s look at each of them in detail.com . Page | 6 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. configure.sqlcommunity. Auto-Redirect Minimal impact (Since the log records must be copied. response time may impact due to latency on commit) Yes Impact on throughput No Impact Zero work loss Yes So now you know that database mirroring can be the best H/A solution for many scenarios.Microsoft SQL Server Community (http://sqlcommunity. Reconnect to same IP Only user databases can be mirrored Yes Yes. The witness server role (optional) 1. let‘s look at how it can be implemented. The principal Server role 2. Only the principal database is accessible to client connections. When the principal database receives changes requested by clients. the principal server sends those active changes to the mirror server. Database Mirroring Roles and Participants There are three roles a database can take on when participating in database mirroring: 1. Principal database role: The role of the principal server is to serve the production database to clients. all system & user databases Yes Yes. Database mirroring comprises of the following components and learning these components will help you setup. and maintain database mirroring:     Roles Quorum Transaction Safety.com) SQLFEST Scope Failure Detection Transparent to client Whole instance.

Similarly. Mirror database role: SQLFEST Mirror server holds an exact point-in-time copy of the principal database and is always ready to take over the principal server role in the event of a failure on the principal server. This is because the mirror server replays the activities of principal databases changes.sqlcommunity. It uses quorum to identify which server holds the principal copy and which server holds the mirror copy of the database. If a witness is present. if the mirror and witness server cannot see the principal. The role of the witness is to verify whether a given partner server is up and functioning. (more information about quorum is explained in the next topic) Note: Witness server can be any computer that can support SQL Server 2005. but if it can see the witness and can form a quorum with the witness.Microsoft SQL Server Community (http://sqlcommunity. If the principal server can‘t see the mirror server. Witness server role: In the database mirroring topology you may have an optional third server called the witness. it places those changes in mirror databases log buffer and then commits them to disk as quickly as possible. disk configuration and database file placement should be exactly the same way principal server is configured so that in the event of the failover the mirror functions exactly the same way as your principal server. Each change is done only once and it is then rolled forward. the mirror can take on the role of the new principal server. but if it can see the witness and form a quorum with the witness. Internally. it can keep its database in service. the mirror server redoes the log on the mirror database with the oldest log record. Unlike principal and mirror servers. it doesn‘t have to be a high-end computer as long as it meets the recommended requirements for SQL Server 2005. When the principal server truncates or shrinks the log for the principal database. Page | 7 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. the mirror server also shrinks the log at the same point. Witness server is required for enabling automatic failover from principal to mirror server or vice-versa. Supporting automatic failover is the only function for witness server. the witness server does not serve the database. Note: Your mirror server hardware. Quorum is required only when a witness is setup for high availability in a database mirroring session. Forming a quorum: Quorum basically is a relationship among two or more SQL Servers participating in a database mirroring session. Redoing the log involves applying the pending or queued changes to the mirror database in sequence. record by record and as quickly as possible. It acts as a hot standby server. 3.com . a loss of either principal or mirror database leaves two servers to form a quorum.com) 2. starting with the oldest record. When the mirror receives the changes sent by the principal.

Partner to partner More on these quorums can be found in the below table.sqlcommunity. database mirroring will still continue to function as both Principal and witness can talk to each other.com) SQLFEST There can be three types of quorum in database mirroring: 1. Full quorum 2. This includes a witness and either partner (Principal / Mirror) P W M Full Quorum Witness to Partner Quorum P If the network connection between the partners is lost because one of the partners has been lost. In this case. the principal sets its database to DISCONNECTED state and runs with mirroring in a SUSPENDED state (this is called running exposed because the database is currently not being M W Witness to Principal Page | 8 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www.Microsoft SQL Server Community (http://sqlcommunity.com . and the principal server and witness retain quorum. Quorum Type A Full Quorum Description This includes all the 3 servers participating in database mirroring (Principal. The good thing about Full Quorum is that if the Principal is not available. Mirror & Witness). two cases are possible: 1) The mirror server is lost. Database Mirroring will continue to function as both Witness and Mirror can talk to each other and if the Mirror is not available. Partner to witness 3.

2) The principal server is lost. When a session has only a partnerto-partner quorum and if either partner loses quorum. Page | 9 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www.com) SQLFEST mirrored).Microsoft SQL Server Community (http://sqlcommunity. and the witness and the mirror server retain quorum. P If the witness is lost. the session resumes normal operation. W M If you expect the witness to remain disconnected for a significant amount of time. because if the witness server fails. it regains quorum as mirror and begins resynchronizing its copy of the database. P W M Witness to mirror Partner to Partner Quorum This happens when the witness server is not available.com . (Automatic failover will not be possible when the witness is lost but you can manually perform a failover) The witness should be setup only if you intend to use High-Safety (High-availability) mode with automatic failover (both will be covered in the next topic) and if you are using highperformance mode than it is recommended that you don‘t setup the witness server or set the witness property to OFF. the database continues in a SYNCHRONIZED state. When the mirror server rejoins the session. the database goes offline and remains unavailable until the principal server regains quorum with either the mirror server or witness. Note: The witness server is not considered as a single point of failure in database mirroring session. automatic failover is no longer possible. As long as both Principal and Mirror retains quorum. When the witness comes back up. it is recommended that you temporarily remove the witness from the session. and manual failover remains possible.sqlcommunity. the principal and mirror can continue to form a quorum.

com) Now as we know what the different database mirroring roles and type of quorums are. then the witness and the mirror will form a quorum of two and the mirror server will perform an automatic failover. Step 3 During this time the mirror server hardens/commits the log to the disk and returns an acknowledgement to the principal server Step 4 Once the principal server receives the acknowledgement from the mirror server it confirms this acknowledgement for this transaction and is ready to receive new transactions High availability (High-safety) mode protects your data by requiring the data to be synchronized between two places. or the principal‘s server is down. Note: For automatic redirection of your client application please look into ―Client Redirection‖ in the topics ahead. let‘s look into the different safety level and operating modes for database mirroring. This operating mode is best used where you have fast and very reliable communication between the servers and you require automatic failover for a single database. At this moment the principal server waits for an acknowledgement from the mirror server. In this mode Database Mirroring is self monitoring.sqlcommunity. and therefore the performance of the principal server may be affected by the capability of the mirror server. SQLFEST Transaction Safety & operating modes There are three types of operating modes and two types of transaction safety which helps determine the type of topology in database mirroring and the exact mode is based on the setting of transaction safety and whether a witness is a part of the mirroring session or not: 1) Synchronous with automatic failover 2) Synchronous without automatic failover 3) Asynchronous mode (Safety=FULL) (Safety=FULL) (Safety=OFF) Synchronous with automatic failover (Safety=FULL) (Also known as High Availability operating mode) supports maximum database availability with automatic failover to the mirror database. If the principal database suddenly becomes unavailable.Microsoft SQL Server Community (http://sqlcommunity. All the committed transactions are guaranteed to be written to disk on the mirror server. Page | 10 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. Following is the behavior of synchronous with automatic failover mode: Step 1 Principal receives a transaction from client and writes the transaction to the T-log of the principal database Step 2 While the principal server writes the transaction to the t-log on the principal server and once it has hardened the log it sends the log record to the mirror server. Please note: With High availability mode the principal server must wait briefly for responses from the mirror server.com .

Therefore automatic and manual failover is not enabled.com . it must be with the mirror server only. the communication between the principal and the mirror is asynchronous. It may involve potential data loss on the mirror when it is recovered if some of the transaction log blocks from the principal have not yet been received by the mirror. In this operating mode a witness server plays no role. Option Synchronous with automatic failover FULL SYNCHRONOUS Yes Yes Automatic or Manual Synchronous without automatic failover FULL SYNCHRONOUS Yes No Manual only Asynchronous Transaction Safety Transfer Mechanism Quorum Required Witness Server Failover Type OFF ASYNCHRONOUS No N/A Forced only If transaction safety is set to FULL. The principal server will not wait for an acknowledgement from the mirror that the mirror has hardened a block of transaction records. The forced service failover causes an immediate recovery of the mirror database.com) Synchronous without automatic failover (Safety=FULL) (also known as High Protection operating mode) does not have witness server as part of the mirroring session. and a quorum is not required. As the principal server first hardens its principal database log records to disk. The principal server does not wait for an acknowledgement from the mirror. and then sends them to the mirror. SQLFEST Asynchronous mode (SAFETY=OFF) (Also known as High Performance operating mode) has the transaction safety set to OFF. It only allows FORCED SERVICE failover. The mirror does its best to keep up with the principal. Normally you would switch to full safety. The principal then waits for a response from the mirror server.sqlcommunity. Only manual failover is possible in this role as there‘s no witness. but because there is no witness.Microsoft SQL Server Community (http://sqlcommunity. The principal database does not need to form a quorum. FORCED SERVICE will be rarely used. and the transfer of log records is asynchronous. but it is not guaranteed at any point in time that all the most recent transactions from the principal will be hardened in the mirrors transaction log. However. If the transaction safety is set to OFF. Following table lists some of the quick differences between operating modes. which is also a manual operation. The mirror will attempt to Page | 11 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. The mirror responds when it has hardened those same log records to the mirror‘s log disk. the principal and mirror servers operate in synchronous mode.

 No committed transactions are lost during failover.Microsoft SQL Server Community (http://sqlcommunity. The client does not get a transaction committed response until the mirror server has acknowledged the principal server. The principal server does not wait for acknowledgement from the mirror server. SQLFEST Key points of Synchronous with automatic failover operating mode:  The transaction safety is always set to FULL  The records are transferred synchronously. and the application attempts to reconnect to the same principal Page | 12 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. The client does not get a transaction committed response until the mirror server has acknowledged the principal server. some transactions are lost during failover.sqlcommunity. applications connecting to the Principal database must also be able to handle the connections during the failover of the Principal server to the Mirror server. for example.  Both the partners and the witness server are required to be present.  The failover is automatic and manual failover is also possible. (Generally this is never done as normally you would want to switch to full safety) Client Redirection: Client redirection is one of the most difficult process with other H/A technology. The new data access provider (MDAC) contains a connection object called “Transparent Client Redirect”.com . If an active connection to the principal database fails for any reason.com) keep up with the principal.  Quorum is not set and the witness server is not present. but some transactions may be lost if the principal suddenly fails and you force the mirror into service. This object allows the caching of both the Principal and the Mirror server name. due to a database mirroring failover. This process of caching is transparent and developers do not need to implement any code to implement this functionality.  The quorum between witness and partners is not required  Automatic failover is not possible as there‘s no witness server  No committed transactions are lost during failover Key points of asynchronous operating mode:  The transaction safety is always set to OFF  The records are transferred asynchronously. The client gets transaction committed response as soon as the principal server has written the transaction to the log.  During manual failover with safety OFF or FORCE_SERVICE. Key points of synchronous without automatic failover operating mode:  The transaction safety is always set to FULL  The records are transferred synchronously. This has always been a problem with Log shipping and Replication but Database Mirroring can handle this very nicely. by recording transactions as quickly as possible.

The client must issue a new connection request. Page | 13 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. the data access provider redirects the connection to the failover partner.Microsoft SQL Server Community (http://sqlcommunity. Each database mirroring endpoint listens on a unique TCP port number. the application needs to close the failed connection and open a new connection using the same connection string attributes. the only way that the application can reconnect to the mirror server is by supplying the failover partner name in its connection string. Also. if an application shuts down on losing the connection. The database mirroring endpoint of a server instance controls the port on which that instance listens for database mirroring messages from other server instances. Before establishing a database mirroring session. the data access provider (MDAC) can attempt to reconnect using the failover partner name stored in the client's cache. ENDPOINTS: Communication Mechanism for Database Mirroring Just to make it simple consider mirroring endpoints as a telephone which is used by 2 or more parties for communicating with each other. Then. You use a specific telephone number to connect to the remote party and same can be considered in the mirroring session where in order to communicate with each other all the servers involved in database mirroring use TCP endpoints to communicate with each other on a specific TCP port. SQLFEST Note: SQL 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. Note: All mirroring connections on a server instance use a single database mirroring endpoint. If the connection was lost because the principal server became unavailable. the data access provider does not attempt to reconnect. Important: If the client gets disconnected from the database. Reconnecting is not automatic. the application must become aware of the error.sqlcommunity. Database Mirroring endpoints use TCP protocol to send and receive messages between the server instances in database mirroring sessions.com) server.com . you must configure to establish the communication mechanism between all the servers participating in database mirroring. At this point. however. it will lose the cached partner names. This communication can be accomplished by creating endpoints on all the servers which controls the transmission control protocol (TCP) port to listen on.

In role switching. the roles can switch back and forth repeatedly. Page | 14 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. and its database becomes the new mirror database.Microsoft SQL Server Community (http://sqlcommunity. Understanding different types of failovers/Role Switching Failover (aka. configured with unique TCP port. assumes the mirror role. Shared Memory. r_3 rve s) Se itnes (W SQLFEST Mirroring Endpoint TCP Port: 5001 r_1 rve al) Se i n ci p (Pr r_ 2 rve ) Se irror (M int po nd 1 g E : 500 rin ort rro Mi C P P T Mi TCrrorin PP gE ort nd : 5 po 00 int 1 Note: 1) If your server has multiple instances of SQL Server participating in mirroring sessions.com . 2) Client connections to the principal server do not use database mirroring endpoint. Potentially. if available. The former principal server. each instance requires its own endpoint. When a failover occurs. Role switching) involves transferring the role of a principal database to a mirror database role and vice-versa. Named Pipes. Instead they use any of the available protocols using SQL network library which could either be TCPIP.sqlcommunity. the mirror server takes over the principal role and brings its copy of the database online as the new principal database.com) Below picture shows how database mirroring communicates with servers using TCP Port. After failover After switching the role Server_2 becomes the principal server and Server_1 becomes the mirror server. As can be seen from the below picture Server_1 acts as a Principal server before the role switch is done and after the role switch it becomes the mirror server and the former mirror server becomes the principal server and the logs are transferred the other way round. the mirror server acts as the failover partner for the principal server. VIA. Before failover Before switching the mirror role Server_1 is the principal server and server_2 is the Mirror server.

 Automatic failover could occur if the acting principal SQL Server shuts down or is rebooted or if the network connectivity is lost  Automatic failover could occur for any unplanned events caused by Hardware/software errors. The role of the witness is to verify whether a given partner server is up and functioning. for a successful automatic failover the database must already be synchronized.Microsoft SQL Server Community (http://sqlcommunity. the mirror server does not initiate a failover as the connection from witness to principal server is fine. and the witness must be connected to the mirror server. Key points to remember for automatic failover:  Automatic failover requires witness server and transaction safety must be set to full  Automatic failover will be initiated only when the ―failure‖ happens and when the partners are fully synchronized and both the partners and the witness are connected. Behind the scenes of Automatic failover: Several things happen behind the scenes whenever a failover occurs as listed below: What happens during automatic failover: Step1: All the client connections are terminated and the principal database state changes to ―DISCONNECTED‖ Step2: As there‘s a quorum between both the participants and the witness.sqlcommunity. If the mirror server loses its connection to the principal server.com . Step3: As the mirror database is in NORECOVERY mode. Also. mirror and a witness server configured. all the logs from the queue of the Page | 15 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. but the witness is still connected to the principal server. both mirror and the witness will detect the failure of principal database.com) SQLFEST P M M P Server_1 Server_2 Server_1 Server_2 There are three forms of role switching that exist with Database Mirroring: 1) Automatic Failover 2) Manual Failover 3) Forced Failover (Rarely done) Automatic failover Automatic failover can occur whenever either of the partner becomes unavailable. This requires mirroring to be in high-availability mode (safety=full) meaning you must have a Principal.

but in the reverse direction. and the database must already be synchronized. rebooting the box. failover is again possible. This is only possible if the principal server is disconnected from the mirror server in a mirroring session. The database is now available and clients can connect to the new principal and continue operation. it checks with the witness and decides that the database should now failover to the mirror.Microsoft SQL Server Community (http://sqlcommunity. Step4: Once the log is fully recovered. Forcing failover may involve some data loss. Manual failover requires SAFETY=FULL and can only be done if the operating mode is set to either High Availability or High Protection mode and the partners must be connected to each other. it will take on the role of the mirror server and will synchronize the database quickly as possible and once it is ready to serve as mirror. High-safety mode without automatic failover supports forcing service whenever the principal server is disconnected. Support for forced service depends on the operating mode and the state of the session. high-performance mode supports forcing service whenever the principal server is disconnected. as follows: Typically. Forced Failover (with possible data loss) allows you to use mirror server as a warm standby server.com . In this case. Once the former Principal comes back up. This usually takes seconds (based on your network and system performance) and if the principal database comes back before the mirror is fully recovered then failover is automatically cancelled. forcing service requires that the mirror server and witness are connected to each other. you should use this type of failover only if you are willing to risk losing some data in order to bring up the mirror database immediately. However. a witness can exist for a high-performance mode session. Step5: After all the above steps are performed. Manual failover You can manually perform failover from principal to mirror and vice-versa during planned maintenance like applying service packs or hotfix. Forced failover (with possible data loss) Forced failover is strictly a disaster recovery method. the mirror database is brought online and it assumes the role of the principal.com) SQLFEST principal server is applied on the mirror database to completely recover it. etc. though unnecessary. 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 Page | 16 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. Therefore. it finds out that its partner is now performing the principal role.sqlcommunity.

You must perform this type of failover with extra care and must use this type of failover only if you must restore service to the database immediately and are willing to risk losing data.Microsoft SQL Server Community (http://sqlcommunity. But if a witness exists. at the risk of possible data loss. just for your ease we are providing you with the following checklist: 1) 2) 3) 4) 5) 6) 7) 8) 9) Name of the Principal Server Name of the Mirror Server Name of the Witness Server Mirroring endpoint name for Principal server Mirroring endpoint name for Mirror server Mirroring endpoint name for Witness server Endpoint Port number for Principal server Endpoint Port number for Mirror server Endpoint Port number for Witness server Operating mode Safety Mode Principal server domain name Mirror server domain name Witness server domain name Name of the database to be mirrored Have you created exact partitions on the mirror server? Location where backups are stored? Page | 17 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www.sqlcommunity.com . Note: High performance mode is intended to run without a witness.com) 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). once the new principal database comes online. the client applications can recover quickly by reconnecting to the database. The effect of forcing failover is similar to removing mirroring. SQLFEST Pre-requisites for setting up Database Mirroring: Setting up database mirroring is easy and simple if you plan ahead and collect all the required information before you start setting up database mirroring in your environment. The new principal database runs without a mirror (that is. Forcing service initiates a smooth transition of the principal role to the mirror database. forcing service requires that the witness is connected to the mirror server. except that forcing failover facilitates re-synchronizing the databases when mirroring is resumed. The mirror server assumes the role of principal server and immediately serves its copy of the database to clients. it runs exposed). In any role-switching scenario.

3. Make sure that both principal and mirror are running on the same edition of Microsoft SQL Server 2005. For best performance. logins. 5.sqlcommunity. Having different collation/code-page can cause problems during database mirroring setup. disk partitions. If the file layouts must differ. SSIS packages. you must include the move option in the RESTORE statement.com) SQLFEST Was latest SQL Server Service pack applied? Location of the scripts for database mirroring? Did you copy all jobs. Make sure Microsoft SQL Server 2005 (any edition) is installed on the witness server. they can either be standard edition or enterprise edition. Make sure that all the databases participating in Database Mirroring are set to FULL recovery model. Page | 18 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. The witness server can run on any reliable computer system that can support SQL Server 2005. use a dedicated network interface card (NIC) for database mirroring. server configuration from Principal server to the mirror server? Fully qualified server name for Principal Fully qualified server name for Mirror Fully qualified server name for Witness Have you performed full and log database backups of the principal server? Once you have the above checklist fully covered you are almost ready for setting up database mirroring: Keep the following points in mind before you start setting up database mirroring: 1. SSIS packages.Microsoft SQL Server Community (http://sqlcommunity. All of the server instances in a mirroring session should use the same master code page and collation. 7. logins. 6. If possible.com . disk space. Make sure that the mirror server has the exact same jobs. for example if the principal database is on drive ‗F:‘ but the mirror system lacks an F: drive. 2. server configuration. etc (This is very important) 4. the path (including the drive letter) of the mirror database should be identical to the path of the principal database.

Just to get an idea of what we are going to do. mirror and witness server instances. You may do this by running and comparing the output of ―Exec SP_Configure‖ system stored procedure on both principal and mirror servers. let me help you understand the mirror setup process and steps. Step2: Perform a full and log backup of the principal database and restore it on the mirror server instance using NORECOVERY option Step3: Start the mirroring session on principal. Configure the mirror server with the server settings exactly as the principal server was configured.Microsoft SQL Server Community (http://sqlcommunity.com) 8. With the steps below you will find how easy it is to setup database mirroring in your environment. Once you follow the above setup process you will be able to setup database mirroring in your environment in not much time.sqlcommunity. You can use these steps at any time to setup database mirroring on any server). I have provided the below setup process steps for you to follow in order to setup database mirroring in your environment.com . Step1: Create mirroring endpoints on principal. mirror and witness server instances. SQLFEST Database mirroring setup flow: Setting up database mirroring is a very easy process if you know exactly what steps you need to perform and just to make your life easy. If you keep in mind that database mirroring is very tough then yes it is very tough and you can‘t do it but take my word it is the most simplest H/A technology that can be configured very easily and is very simple to understand. Page | 19 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www.

com) SQLFEST Database Mirroring Setup Flow Create Endpoint on Principal Server Create Endpoint on Mirror Server Create Endpoint on Witness Server n Pri ci p al Mi rro r P Perform FULL database backup of Principal database and restore it on Mirror server M Enable Mirroring Sessions on all the servers W Principal Server Witness Server Mirror Server P M Easy to understand Database Mirroring Setup Flow Setting up Database Mirroring using T-SQL Once you have met the all the pre-requisites as mentioned in the earlier topic and have understood the setup flow you are now ready to proceed with setting up database mirroring in your environment. example: Server names.sqlcommunity.com . Port Numbers.Microsoft SQL Server Community (http://sqlcommunity. Make sure that you have confirmed and checked all the items from the checklist provided in the earlier topic before you configure database mirroring. Page | 20 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. security accounts. location where databases would reside (especially mirror). Once you have all the information ready you are not very far from configuring Database Mirroring.

T-SQL statement for creating an endpoint on ServerB (mirror server): Use Master. T-SQL Statement for configuring the database to use FULL recovery model: -. ServerB. Page | 21 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. 2 Create an endpoint on ServerA. Alter Database DBM_Demo Set Recovery FULL. Step 1 Action Alter the principal database to use FULL recovery model if it is not already set to use FULL recovery model. & ServerC servers.Please run the below command on the ServerA (principal server) Use Master.com) SQLFEST Now let‘s take a look at how easy it is to setup database mirroring and just for the sake of simplicity we will take an example of 3 easy to remember server names: Role Principal Mirror Witness Server Name ServerA ServerB ServerC Database Name DBM_Demo DBM_Demo Not applicable I recommend that you configure Database Mirroring during off-peak hours because configuration can sometimes impact performance as it has to copy the pending transaction log from principal server to mirror server depending upon the volume of log. Create Endpoint Mirroring_Endpoint State= Started as TCP (Listener_Port=5001) For Database_Mirroring (Role=Partner).com . Database Mirroring will not work on any other recovery model as it has to copy the transaction log from principal to mirror database server.sqlcommunity.Microsoft SQL Server Community (http://sqlcommunity. T-SQL statement for creating an endpoint on ServerA (principal server): Use Master. (For more information about endpoint read the topic ―Communication Mechanism for Database Mirroring (ENDPOINTS)‖ mentioned in previous topic.

Please note: When restoring both Full backup and the Log backup of DBM_Demo database you will need to restore them using ―NORECOVERY‖ option as mentioned in the pre-requisite section earlier. else it may not be required. you may have to perform Log backup of the database.bak‟. T-SQL statement to perform a FULL database backup of DBM_Demo database from ServerA: Use Master. 3 This is the time when you will perform a full database backup followed by a log backup of DBM_Demo database (principal database) from ServerA server.bak‟.sqlcommunity. Create Endpoint Mirroring_Endpoint State=Started as TCP (Listener_Port=5001) For Database_Mirroring (Role=Witness).Microsoft SQL Server Community (http://sqlcommunity.com .com) SQLFEST Create Endpoint Mirroring_Endpoint State=Started as TCP (Listener_Port=5001) For Database_Mirroring (Role=Partner). If there are any changes to the database since you performed the FULL database backup. Once you have all the backups performed move the backup files to ServerB (mirror server) or to a shared location so that you can restore these backups on ServerB Page | 22 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. T-SQL statement to perform LOG backup of DBM_Demo database from ServerA: Use Master. T-SQL statement for creating an endpoint on ServerC (witness server): Use Master. Backup Database DBM_Demo to DISK=‟E:\MSSQL\Bak\DBM_Demo_FULL. Backup Log DBM_Demo to Disk=‟E:\MSSQL\Bak\DBM_Demo_Log.

You must follow the recommendations for restoring the databases on ServerB server: (Using NORECOVERY option assures that the mirror database will be in the ―Restoring‖ state so that the transaction logs can be applied) T-SQL statement to restore the full backup on ServerB server using NORECOVERY option: Use Master.sqlcommunity. Restore Database DBM_Demo from Disk=‟E:\MSSQL\Bak\DBM_Demo_FULL.com .Microsoft SQL Server Community (http://sqlcommunity. Once you have restored the full backup on ServerB server you should now restore any T-Log backups that you had taken since the last FULL database backup from ServerA server: T-SQL statement to restore the Log backup on the mirror server using NORECOVERY option: Use Master. Go 5 Once you have restored all the backups you are now ready to perform the final step and that is to enable your database mirroring session on all the servers participating in database mirroring. The syntax for a server network address is as follows: TCP://<System-address>:<port> <System-address>: is a fully qualified domain name or an IP address: you can get Page | 23 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www.bak‟ with NORECOVERY. 4 Restore the backups that you had taken in the previous step on ServerB server. Restore Log DBM_Demo from Disk=‟E:\MSSQL\Bak\DBM_Demo_Log.com) SQLFEST server.bak‟ with NORECOVERY. The server network address of a server instance must identify the instance by providing a system address and the port number on which the instance is listening. Setting up a database mirroring session requires a server network address for each of the server instances.

Tcp_EndPoints.Microsoft SQL Server Community (http://sqlcommunity. Any database objects that have been added or modified on DBM_Demo database will be transferred to the ServerB copy. You can use the following T-SQL statement to identify the port number from the configured TCP endpoints: Use Master. Alter Database DBM_Demo Set Partner= „TCP://ServerA. a failover can occur.com) SQLFEST this information by executing IPCONFIG on the local machine from DOS prompt. Page | 24 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. Once you have started the mirroring session on both ServerA and ServerB servers you now have to enable mirroring session on ServerC (witness) server: T-SQL for starting database mirroring session on ServerC (witness) server: Alter Database DBM_Demo Set Partner=‟TCP://ServerC. changing the mirrored database‘s role to the principal role. Now run the following T-SQL for starting the database mirroring session on the ServerA server: Use Master. You can use both IPv4 and IPv6. If ServerA database becomes unavailable. T-SQL for starting database mirroring session on the ServerB server: Use Master.com:5001‟.com . Select Type_Desc.com:5001‟. Alter Database DBM_Demo Set Partner=‟TCP://ServerB.com:5001‟.sqlcommunity. You may also use the IP address for partner instead of the system address. <Port> : is the one that you created in step two when creating endpoints. Go Database Mirroring is now ready in your environment. Port from Sys.

database_mirroring which is explained in next topic. please visit MSPress website for a live demo. Once you have setup database mirroring successfully in your environment you can view the state of partners by querying the system catalog called sys. Go Select * from sys. For setting up database mirroring using SQL Server management studio. In case if the domain account for any of the server is different for example the domain account for ServerB (mirror) server is different than the domain account of the ServerA (principal) or ServerC (witness) server then you can use the following statement to grant permissions on the endpoint to that domain account: (You will need to run the below statement on all the three servers participating in mirroring session) Use Master. SQLFEST Viewing the database mirroring state: Once Database mirroring is setup.Microsoft SQL Server Community (http://sqlcommunity. you can view the state of database mirroring by querying Database_Mirroring system table in master database Use Master.com) The above example is assuming that all the three servers are connected to the same domain and are using the same domain account. Grant Connect on EndPoint ::Mirroring_Endpoint to [Domain\Domain_user_account]. this should show you the current state of your database. Create Login [Domain\Domain_user_account] From Windows.com . Paused Page | 25 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. Following table states what each database mirroring state means: States <blank> Explanation No database mirroring session exists and there is no activity to report on the Mirroring page.sqlcommunity. Go Now look at the state column in the result state. The mirror copy of the database is not available.Database_Mirroring. The principal database is running but is not sending any logs to the mirror server.

You must be a member of dbm_monitor database role in MSDB of all the servers if you want to monitor both Principal and Mirror databases. it caches the following information about the database that is being mirrored:    Database Name Names of both Principal and Mirror servers The last known roles of each partner (Principal or Mirror) Also. At the start of a database mirroring session. When you register a database in Database Mirroring monitor. which is applying the changes to the mirror database to roll it forward. Failover On the principal server instance. a manual failover (role swap) has begun but has not yet accepted by the mirror.sqlcommunity. the mirror and principal databases are in the synchronizing state.Microsoft SQL Server Community (http://sqlcommunity. Microsoft introduced Database Mirroring monitor to help monitor how well the data is flowing in the database mirroring session and it also can be very useful for troubleshooting the cause of reduced data flow from principal to mirror. The principal server instance is sending log records to the mirror server instance. The mirror database contains the same data as the principal database.com . Note: sysadmin server role has full permissions to everything in SQL Server. Page | 26 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www.com) SQLFEST No connection The principal server instance cannot connect to its partner or to the witness server instance (if any) The contents of the mirror database are lagging behind the contents of the principal database. Database Mirroring Monitor is available only with SQL Server 2005 Standard and SQL Server 2005 Enterprise editions. Manual and automatic failover are possible only in the synchronized state. with SP1 a new database role is introduced in MSDB database called “dbm_monitor” which can be used to grant access to users/operators/DBA‘s to access Database Mirroring Monitor for the local server and not the other partners. You can register any of your mirrored databases for monitoring each of the failover partners individually. Synchronizing Synchronized Monitoring database mirroring With the release of SQL Server 2005 SP1.

How to launch database mirroring monitor: 1) After connecting to the principal server instance.com . click the server name to expand the server tree. Page | 27 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. alternatively you can click on the refresh button to refresh the screen. 4) In the Database Mirroring Monitor dialog box. and then click Launch Database Mirroring Monitor. Once the database is registered you should see a screen similar to the below: Note: You just have to register either Principal or the Mirror server and database mirroring monitor will automatically register the associated partner. Database Mirroring Monitor will now be launched and you can click on ―Register Mirrored database‖ option from the right pane to register the database to monitor. click Register Mirrored Database to register one or more mirrored database. 3) Right-click the database. and select the database to be monitored. in Object Explorer. Database Mirroring Monitor refreshes automatically @ every 30 seconds. select Tasks. The new dbm_monitor role will not have any users unless you (sysadmin) assigns users to this role. 2) Expand Databases.Microsoft SQL Server Community (http://sqlcommunity.com) SQLFEST Important: The dbm_monitor fixed database role is created in the MSDB database only when the first database is registered in database mirroring monitor.sqlcommunity.

Microsoft SQL Server Community (http://sqlcommunity. the main database mirroring monitor page shows the below information: Feature Mirror Commit Overhead Description Number of milliseconds of average delay per transaction tolerated before a warning is generated on the principal server. This value is relevant only in high-safety mode.sqlcommunity. etc. The amount of log waiting in the send queue (in kilobytes). 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.com . Unsent Log from Principal Server Page | 28 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. Also.com) SQLFEST Some of the features you might like about database mirroring monitor are:  You can monitor the current status of each server  You can monitor the latency  You can view the warnings and the history of each transaction  You can configure performance thresholds.

when setting up a threshold you must set it up both on the principal and on the mirror server to make sure that the warnings and thresholds persists if the database fails over. High Protection (Synchronous). Also. Rate at which incoming transactions are being entered into the principal's log in KB per second. To determine whether mirroring is falling behind. Suspended.Microsoft SQL Server Community (http://sqlcommunity.sqlcommunity. Rate at which transactions are being sent from Principal and restored to the mirror server instance in kilobytes (KB) per second. Disconnected) Will contain the current operating mode of the Database Mirroring session (Ex: High Availability (Synchronous).com . staying up. Will contain the current state of Database Mirroring session (ex: Unknown. compare this value to the Estimated time to send log value.com) SQLFEST Un-restored log from Mirror Server Current send rate and restore rate of the log Current rate of new transactions The amount of log waiting in the redo queue (in KB). Synchronized. synchronizing. There are 3 ways you can setup warning thresholds for database mirroring: 1) Using Database Mirroring Monitor 2) Using System Stored Procedure & 3) Using SQL Server Performance Monitor Page | 29 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. or catching up. High Performance (Asynchronous) History of each transactions occurred since the last 2 days (this can be very helpful when troubleshooting) You can view any warnings that have been generated for Database Mirroring session State of the database Operating Mode Transaction History Warnings Setting up database mirroring thresholds It is recommended that you setup threshold in the production environment for key performance metrics.

sqlcommunity.com) SQLFEST Setup thresholds using Database Mirroring Monitor: 1) From the Database mirroring monitor select warnings tab from the right pane after you register the server 2) Click on ―Set Thresholds‖ button on the ―Warnings‖ page.Microsoft SQL Server Community (http://sqlcommunity. Page | 30 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. (You will see the threshold page similar to the one below) 3) You can now check the boxes for which you want to setup warning threshold (Please do not forget to check the same thresholds for the mirror server as well so that you continue to receive performance related alerts even if the principal fails and mirror takes over. Setup thresholds using system stored procedures: You can setup thresholds for monitoring database mirroring using the following system stored procedure. an event is logged in the NT application log.com . This can come handy when you are writing a process which can consume heavy resources and you want to execute that process based on the performance of database mirroring: 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. Note: When a threshold exceeds its limit.

1 . --Unsent log EXEC sp_dbmmonitorchangealert DBM_Demo. 30. EXEC sp_dbmmonitorchangealert DBM_Demo.000 KB 1.sqlcommunity. Example for sp_dbmmonitorchangealert: Syntax: Exec sp_dbmmonitorchangealert <database_name>. 8. 1 . --Oldest unsent transaction EXEC sp_dbmmonitorchangealert DBM_Demo. sp_dbmmonitorhelpalert (Transact-SQL) Returns information about warning thresholds on one or several key database mirroring monitor performance metrics.Microsoft SQL Server Community (http://sqlcommunity.enabled The following example sets thresholds for each of the performance metrics and the retention period for DBM_Demo database.alert_id . --Retention Period Note: When a threshold exceeds an event is logged in the application event log. 1000. 1. 1 . 10000.000 milliseconds 8 hours Is the warning enabled? Yes Yes Yes No Yes Use Master. 10000. --Unrestored log EXEC sp_dbmmonitorchangealert DBM_Demo.com . 2. .000 KB 10. 1 . sp_dbmmonitordropalert (Transact-SQL) Drops the warning for a specified performance metric. Page | 31 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www.com) SQLFEST System Stored Procedure Description sp_dbmmonitorchangealert (Transact-SQL) Adds or changes warning threshold for a specific mirroring performance metric. 3. 0 . Following table shows values used in the below examples: Alert_id Performance metric 1 Oldest unsent transaction 2 3 4 5 Unsent log Unrestored log Mirror commit overhead Retention period Warning threshold 30 minutes 10. 5.alert_threshold . 4. --Mirror commit overhead EXEC sp_dbmmonitorchangealert DBM_Demo.

Rows to return can be: Rows to return – code 0 1 2 3 4 5 6 7 8 9 Update status value can be: Update Status Value 0 Description Does not update the status for the database.com . or the user is not a member of the sysadmin fixed server role. if the status table has been updated within the previous 15 seconds. The results are computed using just the last two rows. the age of which depends on when the status table was refreshed.000 rows 1 Page | 32 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. Returns Last Row Rows from last two hours Rows from last four hours Rows from last eight hours Rows from Last day Rows from last two days Last 100 rows Last 500 rows Last 1000 rows Last 1. sp_dbmmonitorresults runs without updating the status.000.com) SQLFEST Querying the status of performance metrics: You may use sp_dbmmonitorresults to get a status for monitored database from the status table in which mirroring monitoring history is stored and allows you to choose whether the procedure obtains the latest status beforehand.Microsoft SQL Server Community (http://sqlcommunity. However.sqlcommunity. This procedure accepts three parameters: 1) 2) 3) Database Name (Specify the database to query the mirroring status for) Rows to return (Specify the quantity of rows to return) Update Status (Specify to update the values before returning the result set. Updates the status for the database by calling sp_dbbmonitorupdate before computing the results.

You can change the operating mode of a mirror session by using the ALTER DATABASE statement with the SET PARTNER SAFETY clause on either partner server. and if the principal Page | 33 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. and automatic failover and manual failover is not supported.sqlcommunity. they have quorum). However. When Safety is set to OFF: (High Performance) The session runs in asynchronous mode.com) Example: This example shows the rows recorded since the last 2 days for DBM_Demo database and it also updates the status of the database before the result set is displayed: Use MSDB. 1. When safety is set to FULL and the witness is set to OFF: (High Protection) The session runs in synchronous mode without automatic failover. 5. When the principal server is lost. Changing Modes and Transaction Safety using T-SQL By default.Microsoft SQL Server Community (http://sqlcommunity. SAFETY is set to FULL and is operating in High-Availability mode). Let‘s see what happens when the safety mode or the operating mode is changed. The behavior of high-safety mode depends partly on the witness as follows: When safety is set to FULL and a witness is configured: (High Availability) The session runs in synchronous mode with automatic failover. the principal server instance is unaffected but if the principal server instance goes down. If the mirror server instance goes down. Exec sp_dbmmonitorresults DBM_Demo. problems on the mirror do not affect the principal. the session automatically fails over to the mirror server if the database is synchronized and the mirror server instance and witness are still connected to each other (that is.com . the previous setup example we have seen operates in synchronous mode (i. There are also other procedures that can help you query other pieces of information for database mirroring monitor: System Stored Procedure sp_dbmmonitorhelpalert Sp_dbmmonitordropalert Purpose Returns information about warning thresholds Drops the warning for a specific performance metric SQLFEST Database Mirroring Maintenance and Operations In this topic we will see the different mirroring operations/maintenance tasks you may have to perform with the database mirroring sessions.e. you can do a manual failover to the mirror server instance.

Go To set the safety back to synchronous (i. If for any reason the principal database becomes unavailable. the normal load on each of the failover partners should use less than 50 percent of the CPU. However. Now. a failover partner might not be able to ping the other server instances in the mirroring session. force service (with possible data loss) to the mirror server instance.sqlcommunity. we recommend using either high-safety mode without automatic failover or high performance mode.com . we strongly recommend that you ensure that WITNESS is set to OFF. (Note: You will also need to turn off witness when turning off HIGH-SAFETY. If you are unable to keep the CPU usage below 50 percent. (i. Turning off transaction safety shifts the session in to asynchronous operating mode. SAFETY=FULL) execute the following statement from Principal database: Use Master. If your work load overloads the CPU. you can. Important: Asynchronous (high-performance) operating mode is not intended to use a witness server. use the following T-SQL statement from principal database instance. the mirror stops but is available as a warm standby (Failover requires forcing service with possible data loss). Use Master. Also. to use SAFETY=OFF) To set the safety off that is to change the operating mode from synchronous (high availability) to asynchronous (high performance) mode. Alter Database <Database_Name> Set Partner SAFETY OFF. Alter Database <Database_Name> Set Partner SAFETY FULL. which maximizes performance but minimizes availability. resulting in a unnecessary failover. if you plan to use high-safety mode with automatic failover. if necessary. let‘s look at how we can make changes to the operating mode using T-SQL: Assume you would like to set the database mirroring to be asynchronous instead of synchronous.com) server instance goes down.e.e. Go SQLFEST Page | 34 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. whenever you set SAFETY to OFF.Microsoft SQL Server Community (http://sqlcommunity.

So let‘s see how we can do this: Step1: Always perform the maintenance on your mirror server instance first.com) SQLFEST To remove the witness use the following T-SQL statement from Principal database: Use Master.com . you can switch to the mirror server instance and make it available to the clients while you perform hardware or software maintenance on the principal server instance. install service packs. etc and yet would like to continue providing availability to your servers.sqlcommunity. reboots. applying hot fixes or service packs There may be times when you may have to perform maintenance on your principal SQL Server instance due to Service pack installation. To add a witness to support automatic failover. Alter Database <Database_Name> Set WITNESS OFF. perform an manual failover from the principal server instance to Page | 35 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. so let‘s see how you can achieve high availability and yet perform all the required maintenance tasks for a short period of time.Microsoft SQL Server Community (http://sqlcommunity. You may perform reboots. ALTER DATABASE <Database_Name> SET WITNESS = 'TCP://<Server_Network_Name>:<Port_number>' Steps to take when rebooting. etc even without touching the principal server instance and once you are done performing maintenance on the mirror server instance you should make sure that the mirroring state on the principal server instance becomes ―SYNCHRONIZED‖ Step2: Once you confirm that the mirroring state has become ―SYNCHRONIZED‖ on the principal server instance. Following example assumes you have an endpoint called ‗Database_Mirroring‖ created on the witness server ―ServerC‖: Use Master. use the below statement from Principal database: If you have to add a witness back you must make sure that the database mirroring endpoint exists on the witness server instance and if it doesn‘t exists than you must create the endpoint before adding the witness to database mirroring partners. If you have configured database mirroring in synchronous with or without automatic failover mode.

sqlcommunity. You can now perform the hardware and software changes on the old principal server. As soon as you are done with the change and the database becomes available.Databases object from the master database to view the status of the database. you will need to point your application to the new principal database server.com) mirror server instance by running the Alter Database Failover statement from the Principal server instance: Use Master. mirror & a witness is 10 seconds. Alter Database <Database_Name> SET PARTNER FAILOVER.Microsoft SQL Server Community (http://sqlcommunity. It is recommended that you stop the application for a brief moment of manual failover and restart after the failover succeeds. Page | 36 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. it automatically re-establishes the mirroring session and assumes the role of the mirror. SQLFEST Q) How do you check if the database is a principal database or not? A) You can query Sys.com . In this case. Meaning if any of the partners are not ping-able for 10 seconds it can throw a timeout message and the database can failover. Select Name. Use Master.Databases where Name-„DBName‟. during this failover all the users connected to the principal server instance will be disconnected and any new users connecting to the database will be auto-redirected to the mirror server. the value of Mirroring_Role_Desc column will be ―Principal‖ else it will be ―Mirror‖ Step3: If you have a witness configured you can now perform the same maintenance on the witness server without affecting the database mirroring session. Changing the default auto-failover timeout value The default timeout for communication between principal. Above statement will perform a failover from your principal server instance to the mirror server instance. Mirroring_Role_Desc from Sys. If the server instance is the principal.

On receiving a ping. You can make changes to the default timeout setting by configuring the partner timeout value as shown in the following T-SQL statement: Use Master. Performing Manual Failover When the mirrored database is synchronized (that is. the principal and mirror server roles are swapped for the database on which the failover occurs. when the database is in the SYNCHRONIZED state). Note: To keep a connection open. Server ServerA ServerB Before failover PRINCIPAL MIRROR After failover MIRROR PRINCIPAL Note that the server roles for other database mirroring sessions are not affected Page | 37 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. ALTER DATABASE <Database_Name> Set Partner TIMEOUT <number of seconds>. In synchronous sessions. plus the time required to send one more ping. a server instance must receive a ping on that connection within the time-out period defined by the mirroring time-out value.sqlcommunity. We recommend that you keep the time-out value at 10 seconds or greater. the database owner can initiate manual failover to the mirror server. you can control the time-out period. In asynchronous sessions. During a manual failover. to avoid false failures. however.com . etc. the default time-out value of 10 seconds cannot be changed. a server instance resets its time-out counter on that connection. Receiving a ping during the time-out period indicates that the connection is still open and that the server instances are communicating over it.Microsoft SQL Server Community (http://sqlcommunity. The mirror database becomes the principal database and the principal database becomes the mirror.com) SQLFEST Note: There are several other errors @ the O/S level that can cause failures and some of them are:    Network errors I/O errors Process errors.

SQLFEST Performing forced failover When the database mirroring is set asynchronous (high-performance) mode (Safety=OFF. you can use the following T-SQL statement to perform a manual failover of your database: (Below statement must be used from the Principal server) Use Master. 3) From the buttons on the right side Click on “Failover” it will than prompt you for a confirmation and once confirmed database mirroring has failed over.sqlcommunity. Go <Database_Name> is the database name of the mirrored database. Once the database is successfully failed over to mirror server instance. Witness=OFF) and if the principal server instance goes down you will need to perform a forced failover to the mirror server instance using the below statement. Where <Database_Name> is the name of the database being mirrored The above statement initiates an immediate transition of the principal database to the mirror server. Alternatively. From the object explorer in SQL Server Management studio: 1) Expand Databases and select the database that you would like to failover to mirror. You will need to execute the below statement from the mirror server instance: Use Master.Microsoft SQL Server Community (http://sqlcommunity.com . it will now become the principal for all the clients and the clients connected to the old principal server are disconnected and the in-flight transactions are rolled back.com) Performing manual failover using SQL Server Management Studio: Steps for manually failing over database mirroring from SQL Server management studio. Alter Database <Database_Name> SET PARTNER FAILOVER. 2) Right click on the database and select All Tasks and select Mirror from within “All Tasks”. Go ALTER DATABASE <Database_Name> SET PARTNER FORCE_SERVICE_ALLOW_DATA_LOSS. Page | 38 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www.

Microsoft SQL Server Community (http://sqlcommunity.com)

Once the above statement is issued, the mirror server immediately transitions to principal server, and mirroring is suspended because the principal server is not available but if the old principal server (the one that had crashed) becomes available will act as a mirror server after being recovered and will establish connection with the current principal server but the mirroring session will be suspended. You can use the following statement on the mirror server to resume database mirroring session: Use Master; Go ALTER DATABASE <Database_Name> SET PARTNER RESUME; Go 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.

SQLFEST

Setting up database mirroring on low-bandwidth networks / modems
Rule of thumb: You must configure database mirroring in high-bandwidth network only. For low bandwidth networks meaning lesser then the 10 mega-bits per second or by using modem (56 kbps or 33 kbps), throughput and response time degrades drastically. But if you have no other option other than to set it up on low bandwidth networks than you must not use synchronizing / high availability mode as it may just be too slow or may just freeze up your connection and this completely depends upon your business requirements and resources & budgets allocated for the project.

Page | 39

Author: Saleem Hakani | SQL Server Community
Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

The network bandwidth recommendation is completely based on the log generation rate of your application as setting up database mirroring in lower bandwidth networks can adversely impact the performance of database mirroring. Therefore, we highly recommend that you test your environment and the log generation rate and based on that make the decision. Our recommendation is to use high network bandwidth for database mirroring. You must always make sure both in high and low bandwidth network that your network bandwidth is significantly more than the log generation rate of your application. Otherwise, Database Mirroring performance will be a major bottleneck for your application environment.

SQLFEST

Setting up database mirroring on a local area network
Since it‘s local area network and the network latency is low you may setup database mirroring in high-availability (synchronous) mode with a witness for automatic failover. Within a reliable LAN, synchronous mirroring with a witness is recommended if availability is of higher importance than performance. However, if performance is of high importance, asynchronous mirroring is preferred. You need to make this design tradeoff based on the performance and availability requirements of your application and the performance impact of synchronous mirroring on your application.

Geo-redundancy with Database mirroring
You can setup database mirroring in Metropolitan Area Network or Wide Area Network primarily as a disaster-recovery solution. Several companies have lost their precious data during Katrina and Tsunamis, therefore it‘s always a good idea to think ahead and setup your database mirroring environment with geo-redundancy. You must also decide what‘s important for you, is it the data or the availability if it‘s the availability than you will need to have powerful network backbone to be able to communicate with all the mirroring participants. Generally, in MAN and WAN environments roundtrip times ranges between 2 to 300 millisecond (based on your internet bandwidth)

Cloud Cloud

2 – 300 milliseconds roundtrip

Skyscraper

New York Seattle

Page | 40

Author: Saleem Hakani | SQL Server Community
Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity.com)

SQLFEST
Environment Local area network Metropolitan area network Wide area network Typical roundtrip times (RTT) in milliseconds (ms) 0 to 2 2 to 20 20 to 300 If the network latency between the principal and mirror server is >=2 milliseconds you must evaluate the performance with respect to the performance goals of your application and business requirements and only then you can determine if synchronous mirroring is the right choice for your environment. Also, with high network latency, the log send queue on the principal server can build up significantly under heavy workload, which may result in longer failover time and increased transaction loss in the event of a failover.

Keep the following points in mind:
If roundtrip <=2 then you can setup synchronous database mirroring If roundtrip >=3 then you can setup asynchronous database mirroring

Preparing the Mirror Server for Failover
You must perform failover tests in your test environment or in the production environment before going live with your application or before setting expectations for your production environment. In the event of a failover, you must make sure that the mirror database is ready to take up the full workload of the principal database. Therefore, you must use identical servers (in terms of CPU, memory, storage, and network capacity) as principal and mirror partners.

Best practices recommendations are to use:
  Identical partner servers (in terms of CPU, memory, storage, network capacity). The same service pack and patch levels for the operating system and SQL Server on both partners. When performing rolling upgrades, the service pack and patch levels can be temporarily different on the principal and the mirror. However, for steady state operations, they should be identical. The same edition of SQL Server on both partners. An identical directory structure for the SQL Server install and database files on both partners.

 

Page | 41

Author: Saleem Hakani | SQL Server Community
Copyright 2007 by www.sqlcommunity.com

Microsoft SQL Server Community (http://sqlcommunity. If you add a disk volume on the principal partner on which you plan to put data or log files for the database that is being mirrored. database mirroring tries to add the same file on the mirror database server and will fail because the new drive doesn‘t exist on the mirror server. Have a process in place so that when you make any changes (such as changes to hardware.com . Several considerations apply to the mirror server: SQLFEST  Make sure that applications can connect and execute all necessary actions. see SQL Server 2005 Books Online. Test server failover and make sure that all objects. database mail profiles. only user databases can be mirrored. Otherwise. from the principal server to the mirror server. MSDB. SSIS packages. You cannot mirror the Master. logins. work on the mirror the same as on the principal. and the same version and service pack level of SQL Server and the operating system on both the partners minimizes the risks of encountering SQL Server or operating system issues. The jobs on the mirror server are typically disabled. consider failover clustering. SQL Server settings.com)  The same SQL Server configuration (trace flags. Therefore. You can use the Transfer Logins task of SQL Server 2005 Integration Services to accomplish this. TempDB. you need to perform some administrative tasks to prepare the mirror server to take over the role of principal in the event of a failover. you repeat or transfer the changes on the mirror server. Ensuring that both servers have the same directory structure. or any database support objects) to the principal. or Model databases.) Copy the SQL Agent jobs. etc. Each database in an instance of SQL Server is mirrored independently. Make sure to enable them in the event of a failover. permissions. you might experience undesirable performance when you fail over.) for the principal and mirror instances. maintenance plans. and SQL Server configuration eliminates the need for changes to these during or after the failover to the mirror partner. alerts. Using the same edition of SQL Server. when you add a data file on the new drive on the principal server.sqlcommunity. The granularity of database mirroring is a single database. add a disk volume with the same drive letter on the mirror server as well. backup devices. startup options. same disk partitioning scheme. storage. Moreover. software. (For details on the Transfer Logins task. etc. For full instance failover capabilities (not database level). memory settings. and that all active SQL Server logins (and their permissions) on the principal server are also present on the mirror server. memory.     Page | 42 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. linked server definitions. support databases. and network capacity. If the principal and mirror servers are not identical in terms of CPU. etc. The entire instance is not mirrored.

your environment would look like this: Server Name ServerA ServerA ServerB ServerB ServerC Role Principal Principal Mirror Mirror Witness Database Name DBM_Demo DBM_Demo_Automation DBM_Demo DBM_Demo_Automation N/A Endpoint Name Mirroring_Endpoint Uses same endpoint Mirroring_Endpoint Uses same endpoint Mirroring_Endpoint Port Number 5001 Same port 5001 Same port 5001 So now you have two databases that are being mirrored and if only DBM_Demo database fails-over to the mirror server instance than what happens to your application? if both the databases belong to the same application your application will be not function properly as one of the database is on a separate principal server instance and the other one is on a separate. lets add one more database to the principal server called “DBM_Demo_Automation”. Therefore.sqlcommunity. It is recommended that if you have multiple databases and multiple applications connecting to them than it‘s a good practice to have a separate mirror server instance for each of the database.com . it is recommended that you think carefully before implementing mirroring on multiple databases. Although it is possible to choose a different mirror server for each database.com) SQLFEST Mirroring Multiple Databases If you have more than one database that needs to be mirrored.Microsoft SQL Server Community (http://sqlcommunity. (This again depends upon the resources available on the system) One of the problem that you might experience with multiple databases is that if in case if just one database fails over and the others don‘t then what happens? Let‘s take an example of the same environment we used for setting up database mirroring using SQL Server Management Studio. you need to mirror each database individually. it is a best practice recommendation that you make the decision based on your application and environment. Note: Mirroring can occur on 10 or so databases per server. Tip: If you have one Application with multiple databases then choose one mirror server for all the databases that belong to the same application. Page | 43 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www.

For as long as the mirroring state stays DISCONNECTED. it is not available to the clients. In such a situation. or break the database mirroring session. except that automatic failover is not possible. Real-Life Scenarios: What happens when you lose the mirror server? If the mirror server instance is lost. The recommended limit of 10 is only approximate and not an exact number. the principal continues functioning. Once the witness becomes operational. Even though the principal database is running. one database might fail over. you must manually fail over the other databases.sqlcommunity. it automatically joins the database mirroring session.Microsoft SQL Server Community (http://sqlcommunity. database mirroring continues functioning without interruption. What happens when you lose both mirror and witness servers? Assume you have configured database mirroring session with a witness. if your application consists of multiple databases. but not the others. it is a best practices recommendation to mirror not more than 10 databases in one instance. then you can choose different mirror servers for them. the principal server instance becomes isolated and can‘t service the clients. Based on the resource (memory and threads) utilization by database mirroring. the transaction log space on the principal cannot be reused. To prevent this you have two options—either plan for enough disk space for the transaction log to grow and bring back the mirror database before the space fills up. the complete database comes to a halt. if the network is experiencing sporadic issues and the mirroring session of one database times out. it automatically assumes the role of the mirror and starts synchronizing with the principal. However. Therefore.com) SQLFEST If you have multiple databases for different applications. you get the message ―Database <dbname> is enabled for database Page | 44 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. Or. if the witness is also lost. What happens when you lose the witness server? If the witness server instance is lost. the principal runs exposed. Once the mirror database becomes operational. but the mirroring state is DISCONNECTED and the principal is running exposed. but the other databases do not. When the mirror is unavailable. In the event of the failure of the SQL Server service or the server or network. If the log file grows and reaches its maximum size limit or runs out of disk space. but doing so adds complexity & maintenance to the configuration. If you attempt to connect to the database.com . even if you back up the transaction log. The limit can vary depending upon your application and workload. both databases will fail over in approximately the same time. what happens if one database experiences a disk failure? In that case. develop an alert mechanism to detect if one database fails over while others don‘t. only that database fails over. While the mirror is unavailable.

you can do that by using Database Mirroring Monitor.sqlcommunity.com .‖ SQLFEST Viewing Database Mirroring Information using T-SQL SQL Server 2005 provides several system catalogs that can help you view the database mirroring information using T-SQL. Alternatively. endpoint names. It provide the following information in the result set:           Mirror Database Name Current State of the database Current role of the database Current transaction safety level Endpoint string for Mirror server Name of the mirror server Endpoint string for witness server State of the witness server Connection timeout value Redo Queue and type Create Procedure usp_DBMStatus as Set NOCOUNT on --Author: Saleem Hakani (Microsoft Corporation) --Purpose: This procedure helps you query the current state of --database mirroring environment. Alternatively. Select db_name(database_id) as 'Mirror DB_Name'. Just so that it eases up the life of a DBA the below stored procedure can be run on either partners to obtain database mirroring related information. you can use Database Mirroring monitor.Microsoft SQL Server Community (http://sqlcommunity. etc.com) mirroring. who‘s playing what role and --their safety levels. case mirroring_state When 0 then 'Suspended' When 1 then 'Disconnected from other partner' When 2 then 'Synchronizing' When 3 then 'Pending Failover' When 4 then 'Synchronized' When null then 'Database is inaccesible or is not mirrored' end as 'Mirroring_State'. Page | 45 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. but neither the partner nor witness server instances are available: the database cannot be opened.database_mirroring object. Below provided script can be used to query sys.

sys.database_mirroring_witnesses.sqlcommunity. Mirroring_Redo_Queue_Type from sys.database_mirroring_endpoints.com) case mirroring_role When 1 then 'Principal' When 2 then 'Mirror' When null then 'Database is not mirrored or is inaccessible' end as 'Mirroring_Role'. (Needs to be run on the witness server) Use Master. Select * from sys.       Below query can provide you with the following information: Endpoint Name Type of protocol being used Port number on which it communicates Current role Encryption status Page | 46 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. Mirroring_Connection_Timeout as 'Failover Timeout in seconds'.tcp_endpoints.endpoints. Querying Endpoint Information You can find detailed information about the endpoints you created earlier by querying sys. case mirroring_safety_level When 0 then 'Unknown state' When 1 then 'OFF (Asynchronous)' When 2 then 'FULL (Synchronous)' When null then 'Database is not mirrored or is inaccessible' end as 'Mirror_Safety_Level'. Mirroring_Redo_Queue. Mirroring_Witness_Name as 'Witness_Endpoint'.Microsoft SQL Server Community (http://sqlcommunity.Database_mirroring where mirroring_role is not null SQLFEST Querying Witness Server You can also query the witness server by using the following T-SQL statement.com . etc. Mirroring_Partner_Name as 'Mirror_Endpoint'. Mirroring_Partner_Instance as 'Mirror_ServerName'. sys. Case Mirroring_Witness_State When 0 then 'Unknown' When 1 then 'Connected' When 2 then 'Disconnected' When null then 'Database is not mirrored or is inaccessible' End as 'Witness_State'.

sqlcommunity. Querying Mirroring Connections Sometimes you may have to look into current mirroring connections for either troubleshooting purpose or to make sure things are working fine and one of the best way you can query SQL Mirroring connections and their state is by querying sys. Convert(Varchar(24). just in case if you have to re-setup or troubleshoot some part of it. Case state When 1 then 'NEW' When 2 then 'CONNECTING' When 3 then 'CONNECTED' When 4 then 'LOGGED_IN' When 5 then 'CLOSED' End as 'Connection_State'.State_Desc as 'Mirroring State'. Page | 47 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www.Connection_Auth_Desc as 'Type of Connection'.Name as 'Endpoint Name'. a. a.port as 'Port'.endpoint_id=b. You can use the below query to query the current state of database mirroring connections: Use Master. a. Select Connection_id.tcp_endpoints b on a.Protocol_Desc as 'Protocol'.endpoint_id It is always a good practice to store mirroring related information in a document. Select a.com . a.Microsoft SQL Server Community (http://sqlcommunity.database_mirroring_endpoints a join sys. b.Role_Desc as 'Current_Role'.Is_Encryption_Enabled When 1 then 'Yes' When 0 then 'No' End as 'Is_Encryption_Enabled'.com)   Type of connection Type of encryption SQLFEST Use Master. Case a.Encryption_Algorithm_Desc as 'Encryption_Type' From sys. a.dm_db_mirroring_connections DMV. Convert(Varchar(24).Login_Time) as 'Login_Time'.Type_Desc as 'Endpoint Payload Type'. a.Connect_Time) as 'Connection_Time'.

you may sometimes want to look at the performance of database mirroring by using PerfMON tool. To monitor the performance of database mirroring. The Databases performance object provides some important information as well. Ltrim(str(Total_bytes_Received)) as 'Total_Bytes_Received'. Log Send Queue KB Transaction Delay Total kilobytes of log that hasn‘t been sent to mirror Delay in waiting for acknowledgement from mirror.Microsoft SQL Server Community (http://sqlcommunity. Principal_Name. Remote_User_Name. SQL Server provides a System Monitor performance object (SQLServer:Database Mirroring) on each partner (principal and mirror). Login_state_Desc as 'Login_State'. Ltrim(str(Total_Fragments_sent)) as 'Total_Message_Fragment_Sent'. Ltrim(str(Total_sends)) as 'Total_Network_Requests_Sent'. Case Is_Send_flow_Controlled When 0 then 'Network is not busy' When 1 then 'Network is busy' end as 'Is_Network_Busy'. such as throughput information (Transactions/sec counter).com . Convert(Varchar(24). It reports total delay for all the transactions in process at that time.sqlcommunity.Last_Activity_Time) as 'Last_Activity_Time'. Ltrim(str(Total_receives)) as 'Total_Network_Requests_Received' from sys. Ltrim(str(Total_Fragments_Received)) as 'Total_Message_Fragment_Received'.com) Authentication_Method. You may want to keep and eye on the following counters when troubleshooting any database mirroring performance related issues: What counters to use on the Principal server: Performance counter Purpose Log Bytes Sent / Sec Number of bytes sent to mirror database transaction log every second. You can divide this counter by Transactions/Sec counter to determine the average delay per transaction. Ltrim(str(Total_bytes_sent)) as 'Total_Bytes_Sent'. Page | 48 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. Encryption_Algorithm_Desc as 'Encryption_Algorithm'.dm_db_mirroring_connections. SQLFEST Monitoring database mirroring performance You have already seen queries in the previous topics that can be used to look for several database mirroring related information including performance.

Here is a list of performance impacts of database mirroring sessions:  If repeated messages reporting that the database mirroring session is switching from active to inactive in the SQL Server error log file exist then it is likely that network problems exist.Microsoft SQL Server Community (http://sqlcommunity. This counter is in the logical disk performance object. It is suggested that the mode be changed to High Performance (Async) during such maintenance windows to minimize the effect on concurrent OLTP operation.com) SQLFEST Transactions/Sec Log bytes flushed/sec Disk Write Bytes/Sec Transactions per second for database The rate at which log records are written to the disk The rate at which the disk is being written. Production performance problems while in Synchronous modes High Availability or High Protection can be attributed to mirror log IO completions if performance increases after changing to asynchronous mode (high performance). Disk Write Bytes/Sec The rate at which the disk is being written. For a complete list see the latest SQL Server 2005 Books Online: o o Logins Linked Servers Page | 49 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. Index maintenance can generate extreme amounts of transaction log. This counter can be found in Logical Disk performance object.com . Mirror redo increases and transaction delay (when using synchronous modes) decreases during the time when a transaction log backup is being created on the principal database. What counters to use on the Mirror Server: Performance Counter Purpose Redo Bytes/Sec Number of bytes of T-Log applied on the mirror database per second. Redo Queue KB Total kilobytes of hardened log that remain to be applied to the mirror database to roll it forward.    The following short list of objects will not failover to the new principal as it is stored outside of the database which is the unit of failover.sqlcommunity.

due to the fact that the database is unavailable on the mirror server instance. The database owner can pause and later resume the mirroring session which preserves the session state while in a suspended state. You will have to restart the job from where it stopped. its transaction log is truncated to that checkpoint after the next log backup. Note: If any of the SQL Jobs were running when the failover occurred. It is recommended that you resume a paused/suspended session quickly. This can be helpful for improving performance on the principal server during bottlenecks. Note: Whenever an automatic checkpoint is performed on a database. Keep the following points in mind before you suspend database mirroring session:    Log records accumulate during the suspended mode T-Logs on the principal server cannot be truncated (even backing up T-Log doesn‘t help) If you keep the mirroring session suspended for an extended period of time.Microsoft SQL Server Community (http://sqlcommunity. scheduled jobs will not failover. 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 to the mirror server. While a database mirroring session remains paused. To set this up on the mirror server instance where the database is unavailable.sqlcommunity. all of the current log records remain active because the principal server is waiting to send them to the mirror server. either failover temporarily to create the job or create a job that runs on all user databases and it will perform the action when the database is serving as the principal.  Page | 50 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www.com) o o Scheduled Jobs (via SQL Agent) Database snapshots SQLFEST Although. the job execution will not failover to the mirror server instance. jobs will succeed performing no action so the best solution is to create the same job on both principal and mirror servers for the mirrored database so that it will run regardless of which server is holding the principal copy.com . Suspending and resuming a mirroring session There may come a time when you might consider suspending mirroring session and then later may consider resuming the mirroring session just to gain some performance (example: when performing index maintenance). you may fill up the log space and the principal database may come to a halt.

checkpoint by checkpoint.com . If the safety level is FULL. The mirror server truncates the redo queue at the same log record. when the original principal server reconnects. Alternatively.sqlcommunity. After the mirror server confirms that it has queued the log record corresponding to the oldest automatic checkpoint. At this point. the log is truncated in stages. ALTER DATABASE <DB_Name> SET PARTNER RESUME. you can use SQL Server Management studio to suspend database mirroring by following below steps: Step1: In the object explorer of the principal server expand databases Step2: Right click on the mirror database and select “Tasks” and then click on “Mirror” option which opens up Mirroring page of the “Database Properties” Step3: Click on the “Pause” button to pause the session. principal server immediately begins sending the accumulated log records to the mirror server. Resuming mirroring in this situation could possibly cause some data loss to the original principal server.com) Once the session is resumed. failover becomes Page | 51 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. You will be asked for a confirmation click on “Yes” and the session is paused and the button caption changes to “Resume” How to resume a suspended database mirroring session? Once you are ready to resume the suspended/paused database mirroring session you can use the below statements to resume the session: Use Master.Microsoft SQL Server Community (http://sqlcommunity. Important: Following a forced service. the principal server truncates the log of the principal database to that checkpoint. mirroring is suspended. Also. resuming database mirroring session places the mirror database in the SYNCHRONIZING state. SQLFEST How to pause/suspend a database mirroring session? You can pause/suspend a database mirroring sessions using the following T-SQL statement: Use Master. As this process is repeated for each successive checkpoint. the mirror catches up with the principal and the mirror database enters the SYNCHRONIZED state. ALTER DATABASE <DB_Name> SET PARTNER SUSPEND.

Following T-SQL statement will stop database mirroring session: Use Master. the database owner can manually stop a database mirroring session by removing mirroring from the database.sqlcommunity. Alternatively.com . any log backups taken on the principal database after mirroring was removed must all be applied to the mirror database. You will be asked for a confirmation click on “Yes” and the session is stopped. How to remove database mirroring session from a server? You can remove database mirroring using the following T-SQL statement: Use Master. automatic failover is possible. ALTER DATABASE <DB_Name> SET PARTNER OFF. Alternate to the T-SQL resume. you can also use SQL Server Management studio to resume database mirroring session using the following steps: Step1: In the object explorer of the principal server expand databases Step2: Right click on the mirror database and select “Tasks” and then click on “Mirror” option which opens up Mirroring page of the “Database Properties” Step3: Click on the “Resume” button to resume the session. manual failover is possible.Microsoft SQL Server Community (http://sqlcommunity. If the witness is present and ON. You will be asked for a confirmation click on “Yes” and the session is resumed and the button caption changes to “Pause” SQLFEST How to stop database mirroring session? At any time. Important: Before mirroring can be restated. you can use SQL Server Management studio to stop database mirroring session using the following steps: Step1: In the object explorer of the principal server instance expand databases Step2: Right click on the mirror database and select “Tasks” and then click on “Mirror” option which opens up Mirroring page of the “Database Properties” Step3: Click on the “Stop Mirroring” button to stop the session. In the absence of a witness. Page | 52 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www.com) possible.

Page | 53 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. you can remove database mirroring using SQL Server Management studio by following the below steps: Step1: In the object explorer of the principal server expand databases Step2: Right click on the mirror database and select “Tasks” and then click on “Mirror” option which opens up Mirroring page of the “Database Properties” Step3: Click on the “Remove Mirroring” button to remove database mirroring. You can now recover the former mirror database from the mirror server using the following statement: Use Master.sqlcommunity. Both Publisher and Distributor must be using SQL Server 2005. which provides greater fault tolerance if the publisher has an unplanned failover.com) ALTER DATABASE <DB_Name> SET PARTNER OFF. Alternatively. Some of the requirements for enabling this feature include: The principal and mirror server instance must use a shared distributor.Microsoft SQL Server Community (http://sqlcommunity. Replication supports mirroring the publication database for merge replication and for transactional replication with read-only subscribers or queued updating subscribers only. You will be asked for a confirmation click on “Yes” and database mirroring is removed. The principal and the mirror databases become independent of each other. We recommend that this be a remote distributor. it is not supported for distribution database or subscription databases. This means that your replication will continue even after the publisher database goes down if the publisher is configured to be mirror-aware. SQLFEST Above statement causes a restart of the principal database by disconnecting all sessions currently using that database.com . Making Replication Mirror-aware This is one of the most powerful features I like about Database mirroring and that is to make your publication database mirror-aware. Replication failover to a mirror is supported for publication databases only. RESTORE DATABASE <DB_Name> WITH RECOVERY. and drops all information about the mirroring session.

Publishers in peer-to-peer topology. asynchronous mode and synchronous without automatic failover are much less affected by network reliability. and republishing are not supported. However. Oracle Publishers.Microsoft SQL Server Community (http://sqlcommunity.com) SQLFEST Immediate updating subscribers. and so on. including Logins. It is important to understand how your network functions in the real world so that you can predict how database mirroring will work there. jobs.sqlcommunity. Metadata and objects that exist outside the database are not copied to the mirror. Before you setup database mirroring in your production environment you must make sure that you have successfully tested all the operating modes and have concluded which operating mode can best suite your production environment. A mirroring session that uses synchronous operation might experience slowed performance when its workload generates large amounts of transaction log data. (If you require the metadata and objects at the mirror. Steps for Configuring Replication with Database Mirroring Configuring replication with database mirroring is very easy if you do it couple of times Following are the five steps for successfully configuring replication with database mirroring: 1) 2) 3) 4) 5) First configure the publisher Second configure database mirroring Configure the mirror to use the same distributor as the principal Configure Replication agents for failover Add the principal and mirror to the replication monitor Implementing database mirroring in production environment It is always better to be safe than be sorry. therefore we recommend that you follow these deployment guidelines: Page | 54 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. Sometimes even the test environment does not give you the right picture because of several barriers. Optimal database mirroring performance is obtained using asynchronous operation. Such a high quality network environment is essential for high-safety mode with automatic failover and is recommended for database mirroring sessions. you must copy them manually). For production environments.com . linked servers. Synchronous mode with automatic failover is designed for a high-service network configuration that minimizes the sources of possible network failures.

Microsoft SQL Server Community (http://sqlcommunity. we recommend that you monitor your sessions for network errors that cause database mirroring to fail) 2) Once you are confident that asynchronous operation is meeting your business needs. having an excessive number of database snapshots on a mirror database might decrease performance on the principal database. This mode is the least sensitive to the network environment and provides the best configuration for exploring how mirroring works. 3) Wait to enable automatic failover until you are confident that high-safety mode without automatic failover is meeting your business needs and that the network errors are not causing failures. you might want to try synchronous operation to improve your data protection. new data is not available. You must create new database snapshots periodically and have applications direct incoming client connections to the newest snapshot. As long as both mirror and principal server are communicating with each other database snapshots can be accessible to clients.com) 1) Begin running in asynchronous. SQLFEST Querying mirrored database using database snapshots In the database mirroring environment Principal interacts with all the users but the mirror server only receives transaction log data from the principal server and other than that mirror database doesn‘t do anything as it‘s in ―RECOVERING‖ state all the time. The primary purpose of this testing is to see how synchronous operation affects your database performance. each database snapshot consumes as much resources as a normal database. Depending on the configurations of the mirror server and principal server. The new database is almost empty. but it grows over time as more and more database pages are updated for the first time.com . With Database Snapshots you can take advantage of the mirror database that you are maintaining for high availability purposes to offload reporting. Because every snapshot on a database grows incrementally in this way. We recommend that first you test high-safety mode without automatic failover. high performance mode. it is recommended that if you can live without touching Page | 55 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. (Throughout testing. You can create a database snapshot on the mirror database and direct client connection requests to the most recent snapshot. We recommend running your system asynchronously until you are confident that your bandwidth supports mirroring and you have developed a solid knowledge of mirroring setup and of the performance of asynchronous mode in your environment. You can create a database snapshot on the mirror database only when the database is fully SYNCHRONIZED. Keep in mind that as database snapshot is static. Therefore.sqlcommunity.

Documenting database mirroring environment: Page | 56 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. this places an additional load on the new principal server.com .snp‟) As SNAPSHOT OF MSNPE_Collect. and drop all of the database snapshots from the former mirror database. How and where to view database snapshots? In the object explorer. you may drop the database snapshots the same way as you would any user databases: Use Master. Users can continue to use the snapshots after the failover. If role switching occurs. great and if not you can keep only a few relatively recent snapshots on your mirror databases. However. the database snapshots remain on the server instance where they were created. Drop Database MSNPE_Collect_SnapSHOT_0400. temporarily disconnecting users. FILENAME= „H:\MSSQL\DATA\MSNPE_Collect_0400. Note: For a dedicated reporting solution that scales out well. connect to the instance of Microsoft SQL Server and expand ―Databases‖ and then expand ―Database Snapshots‖ and select the snapshot you want to view. You are now ready to use database snapshots for querying mirrored databases. make sure you are connected to the mirror database: Use Master. Afterwards. which has become the new principal database. Let‘s create a snapshot on the mirror database. SQLFEST Once you are done working with database snapshots. the database and its snapshots are restarted.sqlcommunity. CREATE DATABASE MSNPE_Collect_SnapSHOT_0400 on (Name=‟MSNPE_Collect_0400_Data‟. consider replication.Microsoft SQL Server Community (http://sqlcommunity.com) the mirror databases/servers. If performance is a concern in your environment than it is recommended that you create a snapshot on the new mirror database when it becomes available and redirect clients to the new snapshot.

accurate documentation addressed to everyone who is involved with the solution.com . because unless proper procedures are followed and change control is in place. It is strongly recommended that you document your database mirroring environment so that you have a record of how it was setup and what change was made by whom and why and when. SQLFEST Page | 57 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www. operated. inaccurate. Out-of-date. concise documentation for the audience‘s level of expertise will ensure the success of the solution. and tested properly. or incomplete documentation is a great risk to the success of any H/A solution. It is critical to produce complete. Feel free to make any changes to the template based on your environment. Below we are providing you with a template that can be used to document your Database Mirroring configuration. it is likely that human errors or misunderstandings will lead to downtime. Every software or infrastructure solution must be documented to ensure that it is implemented.com) Documentation is a very crucial and is a very major part of your H/A solution design. Documentation is the ley to maintaining high availability. Clear. This document may be stored on a shared location so that all the DBA‘s or the service operations people can access it when needed.sqlcommunity.Microsoft SQL Server Community (http://sqlcommunity.

com .sqlcommunity.com) SQLFEST BUSINESS CONTACT INFORMATION Primary DBA: Secondary DBA: Primary DBA Phone #: Secondary DBA Phone # Alternate Ph # Primary DBA: Alternate Ph # Secondary DBA: Manager‘s Name Manager‘s Ph # Alternate Ph # Primary DBA E-mail: Secondary DBA E-mail: SERVER INFORMATION (SOFTWARE / HARDWARE) PRINCIPAL SERVER INFORMATION O/S version Software‘s Installed along with Version number: Service Accounts and Passwords Backup Location SLA: Disaster Recovery Document Location: Other miscellaneous document related to this server: Principal Server Information Principal Server Name: Principal Server IP Address: Page | 58 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www.Microsoft SQL Server Community (http://sqlcommunity.

sqlcommunity.com) SQLFEST Backups Location: Database being mirrored: Description of this database: Endpoint Name: Port # Operating Mode Transaction Safety: List of jobs and other dependencies: Server Network Address (use IPCONFIG /ALL) Mirroring Script Location and Instructions: Mirroring Troubleshooting Guide Location: Other Information: MIRROR SERVER INFORMATION Mirror Server Information Mirror Server Name: Mirror Server IP Address: Page | 59 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www.Microsoft SQL Server Community (http://sqlcommunity.com .

com) SQLFEST Backups Location: Database being mirrored: Description of this database: Endpoint Name: Port # Operating Mode Transaction Safety: List of jobs and other dependencies: Server Network Address (use IPCONFIG /ALL) Mirroring Script Location and Instructions: Mirroring Troubleshooting Guide Location: Other Information: WITNESS SERVER INFORMATION Witness Server Information Endpoint Name: Witness Server Name: Port # Witness Server IP Address: Operating Mode Page | 60 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www.com .Microsoft SQL Server Community (http://sqlcommunity.sqlcommunity.

com Page | 61 Author: Saleem Hakani | SQL Server Community Copyright 2007 by www.com .com) SQLFEST Server Network Address (use IPCONFIG /ALL) Mirroring Script Location and Instructions: Database Mirroring Troubleshooting Guide Location: http://sqlcommunity.sqlcommunity.Microsoft SQL Server Community (http://sqlcommunity.