Fundamentals of SQL Server 2012 Replication
Fundamentals of SQL Server 2012 Replication
Copyright Sebastian Meine 2013 ISBN 978-1-906434-98-4 The right of Sebastian Meine to be identied as the author of this work has been asserted by him in accordance with the Copyright, Designs and Patents Act 1988. All rights reserved. No part of this publication may be reproduced, stored or introduced into a retrieval system, or transmitted, in any form, or by any means (electronic, mechanical, photocopying, recording or otherwise) without the prior written consent of the publisher. Any person who does any unauthorized act in relation to this publication may be liable to criminal prosecution and civil claims for damages. This book is sold subject to the condition that it shall not, by way of trade or otherwise, be lent, re-sold, hired out, or otherwise circulated without the publisher's prior consent in any form other than which it is published and without a similar condition including this condition being imposed on the subsequent publisher. Technical Review: Kalen Delaney and Robert Sheldon Editor: Robert Sheldon Cover Image: Sebastian Meine Typeset: Peter Woodhouse and Gower Associates
Table of Contents
Chapter 1: Overview of SQL Server Replication_________________ 20
Putting SQL Server Replication to Work___________________________________ 21 Replication Components________________________________________________ 23 Articles____________________________________________________________ 24 Publications________________________________________________________ 24 Publication database_________________________________________________ 25 Publisher__________________________________________________________ 25 Distributor_________________________________________________________26 Distribution databases________________________________________________26 Subscriber_________________________________________________________ 27 Subscriptions_______________________________________________________ 27 Subscription databases_______________________________________________ 27 Replication agents___________________________________________________ 28 Replication maintenance jobs__________________________________________ 30 How Terms Are Used___________________________________________________30 Replication Types______________________________________________________ 31 Snapshot replication_________________________________________________ 31 Transactional replication______________________________________________ 32 Merge replication____________________________________________________ 32 Summary_____________________________________________________________ 33 Setting Up the Distributor_______________________________________________ 35 Setting Up a Publication________________________________________________47 Setting Up a Subscription______________________________________________ 60 Success!______________________________________________________________ 73 Summary_____________________________________________________________74
Distribution Components_______________________________________________ 75 The distribution database_____________________________________________ 75 The snapshot folder__________________________________________________ 77 The replication agents________________________________________________ 77 Best Practices__________________________________________________________78 Setting up Distribution_________________________________________________78 Removing replication_______________________________________________ 80 Setting up the Distributor_____________________________________________84 Setting up distribution on the Publisher________________________________ 90 Implementing multiple distribution databases____________________________ 93 Summary____________________________________________________________ 97
Preparing to Create a Publication________________________________________106 Creating a database_________________________________________________ 107 Enabling a database for replication_____________________________________ 109 Creating a Publication_________________________________________________ 112 Setting up your database_____________________________________________ 112 Setting up your articles______________________________________________ 118 Setting up the initial snapshot________________________________________ 124 Setting up security__________________________________________________ 126 Completing the publication setup _____________________________________ 131 Potential Problems____________________________________________________ 134 Summary____________________________________________________________ 135
Setting Up a Subscription______________________________________________ 136 Conguring the Publication Access List___________________________________ 137 Creating the Subscription______________________________________________ 142 Summary____________________________________________________________ 142 Setting up a Subscription_______________________________________________ 144 Connecting to the Publisher__________________________________________ 144 Selecting the Distribution Agent location_______________________________ 148 Specifying the Subscriber and the subscription database___________________ 150 Conguring security on the Distribution Agent__________________________ 152 Account Permissions__________________________________________________ 155 Finalizing the Subscription_____________________________________________ 156 Conguring Retention_________________________________________________160 Conguring retention on the Distributor_______________________________ 161 Conguring retention on the Publisher_________________________________ 165 Summary____________________________________________________________ 168
Merge Replication Components_________________________________________180 Snapshot Agent____________________________________________________ 183 Triggers, tables, and views____________________________________________ 184 Merge Agent_______________________________________________________ 186 Summary____________________________________________________________ 187
Enabling a Database for Merge Replication________________________________ 191 Creating a Publication_________________________________________________ 194 Adding a publication________________________________________________ 194 Adding articles to your publication_____________________________________ 199 Conguring the Snapshot Agent_____________________________________ 209 Finalizing your publication___________________________________________ 213 Potential Problems____________________________________________________ 216 Summary____________________________________________________________ 216 Setting up a Subscription_______________________________________________ 217 Selecting the Publisher ______________________________________________ 218 Selecting the Merge Agent location____________________________________ 222 Specifying the target database ________________________________________ 224 Conguring security ________________________________________________ 225 Setting up permissions______________________________________________ 229 Setting up the schedule _____________________________________________ 230 Initializing the subscription database___________________________________ 232 Selecting the subscription type________________________________________ 234 Finishing up your subscription________________________________________ 236 Setting Up Your Subscription's Retention_________________________________ 239 Synchronizing Your Subscription Manually_______________________________ 241 Summary___________________________________________________________ 244
Conict Types_______________________________________________________ 246 Conguring the Tracking Level________________________________________ 246 Row-level tracking__________________________________________________ 248 Column-level tracking_______________________________________________249 Conict Resolvers_____________________________________________________250 The default resolver_________________________________________________ 252 Other resolvers____________________________________________________ 255 Custom resolvers___________________________________________________ 255 Business logic handlers______________________________________________ 256 Interactive conict resolution_________________________________________ 256 Reviewing Conicts___________________________________________________ 257 Summary____________________________________________________________ 263
Starting Replication Monitor__________________________________________ 264 Removing a Publisher__________________________________________________267 Connecting to a Publisher_____________________________________________ 269 Viewing Information About a Publisher, Its Publications and Subscriptions____ 275 Viewing information about a Publisher_________________________________ 275 Viewing information about transactional publications_____________________ 281 Viewing information about merge publications___________________________ 287 Viewing information about snapshot publications_______________________ 290 Subscription Information______________________________________________ 291 Alerts_______________________________________________________________ 295 Summary____________________________________________________________297
Troubleshooting the Publication_______________________________________ 299 The Log Reader Agent______________________________________________ 299 The Snapshot Agent________________________________________________ 311 Troubleshooting a Subscription_________________________________________ 325 But what about the PAL?_____________________________________________ 338 Other Tools and Issues_________________________________________________ 339 Tracer tokens______________________________________________________ 339 Always check the details_____________________________________________ 340 Data problems_____________________________________________________ 342 Summary____________________________________________________________ 346
Foreword
Replication is the oldest of the high availability technologies in SQL Server. Introduced in SQL Server 6, replication synchronizes data between SQL Server instances, typically copying data from a Publisher, which is the source of the data, to a Subscriber, which hosts the copied data. If the Publisher fails, the Subscriber can take over data operations. Unlike other high availability technologies, replication gives the DBA full control over how much or how little of the data should be replicated. The DBA can choose which tables to replicate from the Publisher to one or more Subscribers and even decide which columns within those tables to replicate. As a very mature technology, replication is also very robust and, in most cases, very straightforward to set up and manage. This book will get you started with SQL Server replication even if you've never worked with any kind of high availability feature, and if you've already been working with replication, the discussions about troubleshooting could still prove invaluable. Replication lends itself very nicely to a step-by-step tutorial of the sort presented in this book. Sebastian guides you through setting up a complete replication scenario. Subsequent chapters then drill into more details about Publishers and Subscribers, as well as publications, subscriptions and articles. Following a set of chapters that discuss transactional replication are several on merge replication. Sebastian Meine has been working with SQL Server for over a decade. I rst met him as a student in a SQL Server Internals class I was teaching for the company he worked for. I noticed immediately that Sebastian was not one to be satised with simple explanations. He wanted to know as much as he could about every detail of the SQL Server engine, including not just what and how, but also why. I was not always able to answer every question he had, and many were about issues I had never thought of before, which inspired me to do more digging on my own.
Since that class, Sebastian and I have kept in touch. I was delighted to oer him the opportunity to write the original Stairway on which this book is based and even more delighted when he accepted. If you've wanted to learn the what, how and why of SQL Server replication, you've come to the right place! I hope you enjoy reading and learning from this book as much as I enjoyed editing it. Kalen Delaney, WWW.SQLSERVERINTERNAls.COM Poulsbo, WA July 2013
Acknowledgements
This is the place where people write that they could not have done this alone. This book is no exception, and a lot of people helped and worked hard on making it possible. I am grateful for all the help I received, especially from the team at Red Gate. Of all the people who helped, there are two who stand out. The rst is my good friend Kalen Delaney, who got me into the SQL Server Central Stairway project in the rst place and then spent numerous hours reviewing and editing the original Stairway to SQL Server Replication. The second is Robert Sheldon. He spent countless hours reviewing and editing to make sure that the book stayed on a consistent technical and linguistic level throughout. Thank you both for working with me on turning this "small project" into the book you are holding in your hands today. Sebastian Meine August 2013
xii
Introduction
Many of my clients need to make data that lives on one server available on another server. There are many reasons for such a requirement. You might want to speed up cross-server queries by providing a local copy of the data. Or you might want to make the data available to resource intensive reporting queries without impacting the OLTP load, maybe even with an intentional delay so you're always reporting against complete days only. Finally, you might be looking to implement high availability. In all these situations, SQL Server Replication is a viable option to look at when planning for the implementation of such a requirement. With this book, I want to introduce you into the vast world of SQL Server Replication and show you its most important strengths and weaknesses. After working through the exercises, you will be able to make an informed decision whether replication is the right feature to use and which type of replication is the most advantageous in your situation. You will also know when to stay away from replication and use other features such as simple log shipping or the new "Always On" feature set.
13
14
15
16
17
System Requirements
This book shows how to set up a real life replication scenario. As those rarely live on a single SQL Server instance, most of the examples and exercises in this book require three separate servers with their own SQL Server instance installed on them. While you can follow many examples using just one instance or multiple instances on a single server, you will get most out of the exercises if you follow them exactly and use three separate machines. Those machines should live in the same domain, but if you don't have access to a domain controller, you can still follow the examples by creating the required user accounts on all three machines instead of just the domain controller.
18
Finally, as this book is about SQL Server 2012 Replication, you need an instance of that SQL Server version on each of your machines. You can use the Standard, BI, Enterprise or Developer edition of SQL Server. (The Subscriber could also be the Web or the Express edition.) The easiest way to get those machines is to open an account with Amazon AWS or Microsoft Azure and create four Windows virtual machines, one as the domain controller and three for the SQL Server instances. You can then install SQL Server as a trial version on each of them. That gives you half a year to work through this book. If you go down this route, make sure to shut down the machines every time you have to step away for an extended time period, as you will be charged for each hour during which the virtual machines are running.
19
20
21
Chapter 1: Overview of SQL Server Replication Replication can also be used for data archival and high availability (HA) purposes. You can, for example, maintain a copy of your complete database on a second server and automatically keep it in sync with the main database. You can even combine your HA standby server and database copy with your reporting server and database, saving on hardware and licensing costs. Before SQL Server 2012, this was the only way to maintain a synchronized copy of your database that was accessible for read requests. However, SQL Server 2012 introduced the Always-On feature, which combines clustering and mirroring into one exible HA solution. Always-On lets you maintain a one-to-one copy of your database (or database group) that is automatically kept in sync with the master copy. This feature utilizes technology that was introduced with the snapshot isolation levels in SQL Server 2005 to provide read-only access to the secondary databases. It also allows the synchronization to be either synchronous, to maximize protection, or asynchronous, to reduce the impact on the primary database. With the Always-On feature, you can also implement more than one secondary server. For example, you might set up your rst secondary server in the same datacenter as the primary server. You can congure the secondary server to be updated synchronously for fast failover. You might then implement another secondary server in a remote location (such as across the ocean) to ensure maximum disaster recoverability. This one you can congure to be updated asynchronously to minimize the impact on the main database. What all this means is that, if your goal is to create an exact copy of the database, replication in SQL Server 2012 is not necessarily the way to go because Always-On oers advantages such as synchronous data transfer and the guarantee that the two databases are identical. On the other hand, if your goal is not to have a one-to-one copy, replication oers a lot more exibility. You can replicate just a subset of tables. You can even lter out rows. You can have two subscriptions of publications in separate databases write to the same database, thereby collecting data from dierent sources into one place. You can also synchronize multiple data sources bi-directionally, allowing for data to change in more
22
Chapter 1: Overview of SQL Server Replication than one place. Finally, you can even do things such as change the replicated data on the y or replicate only data inserts and updates, while ignoring deletes. SQL Server can replicate data from one database to another database on the same server or on another server. That second server can be in the same building or on the other side of the world. SQL Server also allows you to replicate data to and from other database management systems such as Oracle.
Replication Components
Replication requires a number of components to work properly. Figure 1-1 provides a high-level overview of the pieces involved in a replication setup.
Figure 1-1:
23
Chapter 1: Overview of SQL Server Replication The components in the replication setup shown in Figure 1-1 include a Publisher and its publication database. The publication database contains a publication that includes two articles. The setup also includes a Distributor and its distribution database as well as a Subscriber and its subscription database, which contains the subscription. Finally, the setup includes the replication agents necessary to drive these processes. (A replication setup also includes a few maintenance jobs, but they are not displayed in Figure 1-1.) Let's dig deeper into each of these components.
Articles
For each SQL Server object that should be replicated, an article needs to be dened. Each article corresponds to a single SQL Server object. For example, in Figure 1-1, the tables dbo.tbl_3 and dbo.tbl_4 are the articles. The objects that are replicated most often are tables, views, and stored procedures. (For a complete list of objects that can be replicated, check out the topic, Publishing Data and Database Objects in SQL Server Books Online.) An article's properties determine whether that article contains the entire object or a ltered subset of its parts. For example, an article can be congured to contain only some of the columns of a table. With some restrictions, multiple articles can be created on a single object.
Publications
A publication is a collection of articles grouped together as one unit. In Figure 1-1, the dotted circle that surrounds the two articles represents the publication.
24
Chapter 1: Overview of SQL Server Replication Every article is dened to be part of exactly one publication. However, you can dene dierent articles on the same object in separate publications. A publication supports several congurable options that apply to all its articles. Perhaps the most important option is the one that lets you dene which type of replication to use.
Publication database
Any database that contains objects designated as articles is called a publication database. When you set up a publication on a database, SQL Server modies the inner workings of that database and creates several replication-related objects. A publication database is also protected against being dropped. A publication can contain articles from a single publication database only.
Publisher
The Publisher is the SQL Server instance that makes a publication available for replication; however, the Publisher itself doesn't actually have an active role in a replication setup. After the publication is dened, the Distributor and sometimes the Subscriber do all the heavy lifting. The entire left-most column in Figure 1-1 represents the Publisher with its publication database, publication, and two articles.
25
Distributor
Each Publisher is linked to a single Distributor. The Distributor is a SQL Server instance that identies changes to the articles on each of its Publishers. Depending on the replication setup, the Distributor might also be responsible for notifying the Subscribers that have subscribed to a publication that an article has changed. The information about these changes is stored in the distribution database until all Subscribers have been notied or the retention period has expired. The Distributor can be congured on a SQL Server instance separate from the Publisher, but often the same instance takes the role of the Publisher and the Distributor. In Figure 1-1, the top part of the center column is the Distributor. There are no table details shown because you don't usually have to directly access a replication's internal objects.
Distribution databases
Each Distributor has at least one distribution database. The distribution database contains a number of objects that store replication metadata as well as replicated data. A Distributor can hold more than one distribution database; however, all publications dened on a single Publisher must use the same distribution database.
26
Subscriber
Each SQL Server instance that subscribes to a publication is called a Subscriber. The Subscriber receives changes to a published article through that publication. A Subscriber does not necessarily play an active role in the replication process. Depending on the settings selected during replication setup, it might receive the data passively. In Figure 1-1, everything related to the Subscriber is displayed in the right-hand column. Here you can nd the subscription database and the subscription, which is represented by the dotted circle that surrounds the two replicated articles.
Subscriptions
A subscription is the counterpart of the publication. Each subscription creates a link, or contract, between one publication and one Subscriber. There are two types of subscriptions: push subscriptions and pull subscriptions. In a push subscription, the Distributor directly updates the data in the Subscriber database. In a pull subscription, the Subscriber asks the Distributor regularly if any new changes are available, and then updates the data in the subscription database itself.
Subscription databases
A database that is the target of a replication subscription is called a subscription database. As in the case of the publication database, SQL Server modies the subscription database during the rst initialization. The most obvious change is the addition of a few replication-related objects. However, unlike publication databases, SQL Server doesn't prevent a subscription database from being dropped.
27
Replication agents
The replication processes are executed by a set of replication agents. Each agent is an independent Windows executable responsible for one piece of the process of moving the data. In a default installation of replication, each agent is executed by its own SQL Server Agent job. Most of those agents usually run on the Distributor, although some can run on the Subscriber. The Publisher houses replication agents only when the Publisher and Distributor are the same instance. Instead of relying on the SQL Server Agent, you can execute any replication agent manually or by some other scheduling means. However, in most cases, these approaches provide little advantage and often make troubleshooting more complex. The following sections briey introduce each replication agent type. The replication agents are described in more detail in later chapters.
Snapshot Agent
In all replication topologies, the Snapshot Agent provides the data required to perform the initial synchronization of the publication database with the subscription database. Transactional replication and merge replication use other agents to keep the data in sync afterwards. For both topologies, replication will use the Snapshot Agent again (after the initial synchronization) only when you request a fresh resynchronization. Snapshot replication, on the other hand, uses the Snapshot Agent exclusively to replicate data. It works by copying all the data every time from the publication database to the subscription database.
28
Distribution Agent
The Distribution Agent applies the changes recorded in the distribution database to the subscription database. As with the Log Reader Agent, only transactional replication uses the Distribution Agent.
Merge Agent
The Merge Agent synchronizes changes between the publication database and the subscription database. It is able to handle changes in both the publication database and the subscription database and can sync those changes bi-directionally. A set of triggers in both databases support this process. Only merge replication uses the Merge Agent.
29
Replication Types
SQL Server supports three types of replication: snapshot, transactional, and merge replication. There is also peer-to-peer replication, which is transactional replication with a few enhancements that allow for bi-directional updates.
Snapshot replication
Snapshot replication creates an identical copy of the replicated objects and their data each time it runs. There is no synchronization capability available for snapshot replication; subsequent executions always copy the entire dataset again, overwriting any external changes that might have been applied to the target database. Snapshot replication uses SQL Server's bcp utility to write the contents of each table into the snapshot folder. The snapshot folder is a shared folder set up on the Distributor when replication is congured. Each component that participates in snapshot replication needs to have access to the snapshot folder. Every time snapshot replication runs, all articles and their data are again copied from scratch, which can require signicant bandwidth and storage resources. During their initial setup, all other replication types use, by default, a single replication snapshot to sync the Publisher to its Subscribers. Snapshot replication is rarely used by itself and therefore will not be covered further. However, its mechanisms are an integral part in the initialization process of the other replication types, so you will see it being mentioned in several places throughout the book.
31
Transactional replication
Transactional replication copies data uni-directionally from the source database to the target database. This replication type uses the log les associated with the source database to keep data in sync. If a change is made to the source database, that change can be immediately synced to the target database, or the synchronization can be scheduled. Transactional replication, however, is sensitive to external changes to the target database. Any such change can potentially break replication so, for all intents and purposes, the target database should be considered read-only. There are exceptions to this rule, however. For example, you can modify objects in the target database that are not part of the replication setup. Transactional replication works, as the name suggests, on a transaction basis. The Log Reader Agent scans the transaction log of the publication database and examines each committed transaction to determine whether any changes aect the replicated articles. If they do, those changes are logged to the distribution database. The Distribution Agent then replicates those changes to the Subscriber. Transactional replication allows for close to real-time synchronization and leaves only a small footprint on the Publisher. There are several options to allow for bi-directional data movement in transactional replication, as in the case of peer-to-peer replication. However, uni-directional transactional replication is the most commonly used form, and we will not cover the other forms in this book. For transactional replication to work, every table you want to publish must be congured with a primary key.
Merge replication
Merge replication allows two or more databases to be kept in sync. Any change applied to one database will automatically be applied to the other databases and vice versa. 32
Chapter 1: Overview of SQL Server Replication Merge replication was designed to allow for data changes on the Publisher as well as the Subscriber, but merge replication also allows for disconnected scenarios. For example, if a Subscriber is disconnected from a Publisher during part of the day, the Subscriber and Publisher are synchronized when they are reconnected. The Merge Agent is responsible for synchronizing the changes between the Publisher and its Subscribers. It utilizes a set of triggers to identify articles that have changed and to record those changes. Because data can be modied on both the Subscriber and Publisher, it's possible for a row to be updated in two dierent places at the same time, which can result in data being in conict. Merge replication comes with several built-in options to help resolve such conicts. Merge replication identies rows across the dierent servers by using a uniqueidentifier column with the ROWGUIDCOL property set and a unique constraint dened on that column. If you publish a table that does not have such a column already, a properly congured uniqueidentifier column will be added automatically.
Summary
In this chapter, you learned about the basic components that make up SQL Server replication. Objects in a publication database that are marked for replication are called articles. Articles are grouped together into publications. If changes occur to those articles, the changes are propagated to the Subscriber, as dened by a subscription. The data ows through the distribution database, which resides on the Distributor. The Publisher, Distributor, and Subscriber can be on the same SQL Server instance or on separate instances, either on the same or on dierent machines. The source and the target database can be the same (if the Publisher and Subscriber are on the same SQL Server instance), but the distribution database has to be separate from the others.
33
34
Figure 2-1:
35
Chapter 2: Conguring a Basic Replication Setup After clicking Congure Distribution, the rst page of the Congure Distribution Wizard appears (shown in Figure 2-2). The page provides general information about setting up a Distributor.
Figure 2-2:
The Congure Distribution Wizard has two purposes. First, it lets you set up a SQL Server instance to be a Distributor. Second, it lets you select an existing Distributor to be used when setting up a Publisher. When using the local distributor model, these two steps occur with one execution of the wizard. Later chapters will provide more details about these two actions and their implications.
36
Chapter 2: Conguring a Basic Replication Setup 3. You can select the Do not show this starting page again option if you don't want the page to appear when you start the wizard. Or you can ignore the option and simply click Next to go to the next page. 4. On the Distributor page (shown in Figure 2-3), you can choose to set up the current instance to be a Distributor or select another instance that's already been congured as a Distributor.
Figure 2-3:
Because you'll be installing the Distributor on this SQL Server instance, leave the default settings, and click Next.
37
Chapter 2: Conguring a Basic Replication Setup 5. If the SQL Server Agent is not set up to start automatically with the operating system, you'll get an additional page here that lets you change SQL Server Agent's conguration. That page, SQL Server Agent Start, is shown in Figure 2-4.
Figure 2-4:
To be able to select the Yes option, the SQL Server service account needs to have administrative privileges in Windows. However, because this is not a recommended security best practice, you most likely will not be able to select the Yes option so, if this page appears, take it as a warning, then select the No option, and adjust the setting manually. For our exercises to work, it's not necessary that the SQL Server Agent be set to autostart. However, it will need to be running, so this is a good place to start the SQL Server Agent service if needed.
38
Chapter 2: Conguring a Basic Replication Setup After you're nished on the SQL Server Agent Start page, click Next. 6. On the Snapshot Folder page (shown in Figure 2-5), you specify the location for the snapshot folder. The snapshot folder is used during the initial synchronization of transactional replication and needs to be large enough to hold all the replicated data. You can place the snapshot folder in any location on your machine or your network. For performance reasons, it makes sense to create a network share on the Distributor. The example shown in Figure 2-5 uses \ \SQL0\ReplDataS12A.
Figure 2-5:
When you set up the snapshot folder, you must also ensure that the appropriate rights have been granted on that folder. To keep this example simple, simply grant write access to the Authenticated Users group, as shown in Figure 2-6. Note, however, that this approach is not a recommended security best practice, and you should grant this access only for the purposes of these exercises. 39
Figure 2-6:
In addition, you must ensure that le sharing has been enabled on the snapshot folder and that read access to that share has been granted to the Everyone group, as shown in Figure 2-7. In a later chapter, you'll learn more about how to tighten security in this area. (To keep this entire exercise simple, there are a few other places in this chapter where you will select options that are not security best practices. All those will be tightened up in later chapters as well.)
40
Figure 2-7:
If these folder security settings are not set up correctly, you'll have to deal with silent failures, that is, failures that don't generate obvious or even easy-to-nd error messages, so double-check that you got them right. There are no completely silent errors in replication. However, sometimes everything looks ne at rst glance and you have to really dig to see that there is a problem.
41
Chapter 2: Conguring a Basic Replication Setup After you've set up your snapshot folder and its share, click Next on the Snapshot Folder page of the Congure Distribution Wizard. This takes you to the Distribution Database page, shown in Figure 2-8.
Figure 2-8:
7. Specify the name of the distribution database and the folders where the data and log les should be located. The distribution database will be created based on these parameters. Be aware that this step will fail if a database with the selected name already exists. After lling in the three elds, click Next to advance to the Publishers page, shown in Figure 2-9.
42
Figure 2-9:
8. On the Publishers page, you specify the Publishers that should have access to the Distributor. Every SQL Server instance that you want to set up as a Publisher and that is going to use this Distributor needs to be added to this list. Note, however, that being on a Distributor's access list does not make a server a Publisher. It merely grants the server access to that Distributor. You will always nd the local instance preselected in this list. That is due to the fact that a SQL Server instance that is set up to be a Distributor can use only itself as a Distributor for publishing. Therefore the wizard automatically suggests the local instance to be a Publisher on this list. Because we're actually going to use the local instance as our Publisher, you can leave the default setting. Click Next to advance to the Wizard Actions page, shown in Figure 2-10. 43
Figure 2-10:
9. On the Wizard Actions page, you choose whether you want the wizard to execute your selections immediately or whether you want the wizard to create a script that you can execute at a later time. Ensure that the Congure distribution option is selected, and then click Next to move on to the Complete the Wizard page, shown in Figure 2-11.
44
Figure 2-11:
10. Review your conguration options, and then click Finish to create your Distributor. As the wizard is creating the Distributor, it displays the Conguring page, shown in Figure 2-12. Here you'll nd information about the wizard's progress as it works through each step.
45
Figure 2-12:
After the wizard has created the Distributor, the Conguring page should show that the process has been successful. If the process was not successful, that information will be displayed instead.
46
Setting Up a Publication
Once you've set up your Distributor, you can create a publication; however, before you do that, you need a database containing a table to publish. So, before you start the next exercise, execute the Transact-SQL script in Listing 2-1 to create a test database and table for the publication.
USE MASTER; GO EXECUTE AS LOGIN = 'SA'; GO CREATE DATABASE ReplA; GO USE ReplA; GO IF OBJECT_ID('dbo.Test') IS NOT NULL DROP TABLE dbo.Test; GO CREATE TABLE dbo.Test( Id INT IDENTITY(1,1) PRIMARY KEY, Data INT CONSTRAINT Test_Data_Dflt DEFAULT CHECKSUM(NEWID()) ); GO INSERT INTO dbo.Test DEFAULT VALUES; GO 1000 USE MASTER; GO REVERT; GO
Listing 2-1:
47
Chapter 2: Conguring a Basic Replication Setup Now you're ready to set up your publication. The following steps walk you through that process: 1. In Object Explorer, expand the Replication folder, right-click Local Publication, and then click New Publication, as shown in Figure 2-13.
Figure 2-13:
The welcome page of the New Publication Wizard appears and provides information about creating a new publication, as shown in Figure 2-14.
48
Figure 2-14:
You can select the Do not show this starting page again option if you don't want the page to appear when you start the wizard. Alternatively, you can ignore the option and simply click Next.
49
Chapter 2: Conguring a Basic Replication Setup 2. When the Publication Database page appears (shown in Figure 2-15), select the ReplA database (the one you just created), and click Next.
Figure 2-15:
50
Chapter 2: Conguring a Basic Replication Setup 3. On the Publication Type page (shown in Figure 2-16), you select the publication type, which corresponds to the type of replication you're implementing. For this exercise, select Transactional publication, and click Next.
Figure 2-16:
51
Chapter 2: Conguring a Basic Replication Setup 4. On the Articles page (shown in Figure 2-17), you choose which articles should be part of this publication. Notice that the Articles page includes the Objects to publish pane. The pane lists the database objects hierarchically, similar to the way Object Explorer in SSMS displays database objects. Also, notice that the dbo.Test table you created earlier is included in that hierarchy. Select that table, and click Next.
Figure 2-17:
52
Chapter 2: Conguring a Basic Replication Setup 5. The next page in the wizard is Filter Table Rows (shown in Figure 2-18). Here you dene any lters that should be applied to your articles. You'll learn about lters in a later chapter, so for now, skip this page by clicking Next.
Figure 2-18:
53
Chapter 2: Conguring a Basic Replication Setup 6. On the Snapshot Agent page (shown in Figure 2-19), you specify when to run the Snapshot Agent. The Snapshot Agent creates that initial snapshot that is used to start the synchronization process. For this exercise, select the option Create a snapshot immediately and keep the snapshot available to initialize subscriptions, and then click Next.
Figure 2-19:
54
Chapter 2: Conguring a Basic Replication Setup 7. On the Agent Security page (shown in Figure 2-20), you specify the account to use to run the Snapshot Agent. For this exercise, you can use the SQL Server Agent account. Click the Security Settings button to select that account.
55
Chapter 2: Conguring a Basic Replication Setup 8. When the Snapshot Agent Security dialog box appears, select the option Run under the SQL Server Agent service account, as shown in Figure 2-21.
Figure 2-21: Selecting the security account for the Snapshot Agent.
56
Chapter 2: Conguring a Basic Replication Setup 9. Click OK to close the Snapshot Agent Security dialog box. You'll be returned to the Agent Security page of the New Publication Wizard. Click Next to continue to the Wizard Actions page, shown in Figure 2-22.
Figure 2-22:
57
Chapter 2: Conguring a Basic Replication Setup 10. On the Wizard Actions page, you choose whether you want the wizard to create the publication immediately or to create a script you can execute at a later time. For this exercise, ensure that the Create the publication option is selected, and then click Next to move on to the Complete the Wizard page, shown in Figure 2-23.
Figure 2-23:
58
Chapter 2: Conguring a Basic Replication Setup 11. In the Publication name text box, type MyFirstPublication, review your conguration options, and then click Finish to create the publication. As the wizard is creating the publication, it displays the Creating Publication page, shown in Figure 2-24. Here you'll nd information about the wizard's progress as it works through each step of the process.
Figure 2-24:
After the wizard has created the publication, the Creating Publication page should show that the process has been successful. If the process was not successful, that information will be displayed instead.
59
Setting Up a Subscription
The nal step in setting up replication is to create the subscription. In most cases, the subscription will be on a dierent machine from the Publisher, but there are scenarios in which you want it to be on the same instance. To keep this exercise simple, you'll be creating your subscription on the same instance as well. But rst, you must create your subscription database. To do so, use the Transact-SQL code in Listing 2-2 to create the ReplB database.
USE MASTER; GO EXECUTE AS LOGIN = 'SA'; GO CREATE DATABASE ReplB; GO REVERT; GO
Listing 2-2:
After you've created the database, you're ready to create your subscription. The following steps walk you through that process.
60
Chapter 2: Conguring a Basic Replication Setup 1. In Object Explorer, expand the Replication folder if necessary, right-click Local Subscriptions, and then click New Subscriptions, as shown in Figure 2-25.
61
Chapter 2: Conguring a Basic Replication Setup 2. The Welcome page of the New Subscription Wizard appears (shown in Figure 2-26) and provides information about the wizard.
You can select the Do not show this starting page again option if you don't want the page to appear when you start the wizard. Or you can ignore the option and click Next.
62
Chapter 2: Conguring a Basic Replication Setup 3. On the Publication page (shown in Figure 2-27), you select a publication you want to associate with your subscription. The publications are listed hierarchically in the Databases and publications pane. Select the publication you created in the previous section, and then click Next.
63
Chapter 2: Conguring a Basic Replication Setup 4. On the Distribution Agent Location page (shown in Figure 2-28), you specify whether this is a push or a pull subscription. In this exercise, you'll create a push subscription, which is the default setting. So all you need to do is to click Next.
64
Chapter 2: Conguring a Basic Replication Setup 5. On the Subscribers page (shown in Figure 2-29), you choose one or more Subscribers and the subscription database associated with each one. For this exercise, select your server and the ReplB database from the Subscription Database drop-down list, and then click Next.
65
Chapter 2: Conguring a Basic Replication Setup 6. The next screen is the Distribution Agent Security page (shown in Figure 2-30). The Distribution Agent is responsible for moving the data from the distribution database to the subscription database. To do so, it has to connect to the Distributor and the Subscriber. On the Distribution Agent Security page, you specify a security account for the Distribution Agent as well as connection details for the two required connections.
Click the ellipsis button on the right side of the rst row in the Subscription properties grid. This launches the Distribution Agent Security dialog box, shown in Figure 2-31.
66
7. Select the option Run under the SQL Server Agent service account, and then click OK . You're returned to the Distribution Agent Security page of the New Subscription Wizard.
67
Chapter 2: Conguring a Basic Replication Setup 8. Click Next to continue to the Synchronization Schedule page, shown in Figure 2-32.
68
Chapter 2: Conguring a Basic Replication Setup 9. In the rst row of the Agent schedule grid, select Run continuously from the Agent Schedule drop-down list, and then click Next to move on to the Initialize Subscriptions page, shown in Figure 2-33.
69
Chapter 2: Conguring a Basic Replication Setup 10. For this exercise, you want to initialize your subscription immediately, so use the default settings, and then click Next to continue to the Wizard Actions page, shown in Figure 2-34.
70
Chapter 2: Conguring a Basic Replication Setup 11. Ensure that the Create the subscription(s) option is selected, and then click Next. The Complete the Wizard page appears, as shown in Figure 2-35.
71
Chapter 2: Conguring a Basic Replication Setup 12. Review the conguration options, and click Finish to create the subscription. As the wizard is creating the subscription, it displays the Creating Subscription(s) page, shown in Figure 2-36. Here you'll nd information about the wizard's progress as it creates the subscription.
After the wizard has created the subscription, the Creating Subscription(s) page should show that the process has been successful. If the process was not successful, information to that eect will be displayed instead.
72
Success!
When you created the Test table in the ReplA database, you inserted 1,000 rows into it. After the initial snapshot is transferred over to the subscription database, the Test table in the ReplB database will also contain the same 1,000 rows. A couple of minutes after you set up the Subscriber, you can run the script in Listing 2-3 to verify that replication pushed all the data to the Subscriber as expected. This script joins the ReplA.dbo.Test and ReplB.dbo.Test tables to show which rows were replicated correctly.
SELECT TOP ( 20 ) A.Id AS [ReplA.Id], A.Data AS [ReplA.Data], B.Id AS [ReplB.Id], B.Data AS [ReplB.Data] FROM ReplA.dbo.Test A FULL OUTER JOIN ReplB.dbo.Test B ON A.Id = B.Id ORDER BY A.Id DESC;
Listing 2-3:
You can also run further tests of your own, such as inserting and updating rows in ReplA.dbo.Test in order to watch the changes magically appear in ReplB.dbo.Test.
73
Summary
In this chapter, we worked through several exercises that stepped you through the process of conguring a simple replication setup. In this case, our setup was a transactional replication conguration. To keep the exercises simple, we congured our Distributor, Publisher, and Subscriber on the same instance of SQL Server 2012. Chances are, in a real-world scenario, you'll want to set up at least some of those components on dierent instances and dierent servers. As we progress through the book, you'll see how to do just that. In the meantime, you should now have a sense of how a basic replication setup works.
74
Distribution Components
A number of specic components are important to the Distributor and replication in general. They include the distribution database, snapshot folder, and replication agents. Although Chapter 1 covers these components, this chapter provides more details about how they apply to the Distributor and the distribution process.
Chapter 3: The Role of the Distributor The distribution database contains metadata about a Publisher's publications and their articles. In addition, the database contains metadata about the progress and state of the replication process. In the case of transactional replication, the database also contains any Transact-SQL commands that were executed on the Publisher and that need to be replicated. For each command, all the data necessary to re-execute that command is also stored in this database. Because of the amount of data that the distribution database must store, it can become quite large, so make sure you have enough room on your hard drive to accommodate its projected growth. The size required for the distribution database is dependent on many factors. For example, assume that our database includes the dbo.MyProc stored procedure, which inserts data into seven tables published in a transactional replication setup. If the procedure itself is published, the data needed to re-execute it on the Subscriber will be stored in the distribution database. If, on the other hand, the procedure itself is not published, or if the seven inserts get executed ad hoc by the application, each INSERT statement with all the column values will be stored. Not surprisingly, this approach requires a lot more space in the distribution database than the stored procedure, although both approaches accomplish the same thing. That means the distribution database size is aected by the number of statements, their frequency, and the type of statements that are executed by your application to insert or update data. Other factors aecting the size of the distribution database are the time it takes to get the data to the Subscribers (latency) as well as the dierent retention times, as we'll see later in the book.
76
Chapter 3: The Role of the Distributor If you follow the standard setup for replication, as described in this book, SQL Server will create SQL Server Agent jobs that execute and control the replication agents. However, you do not have to follow that pattern; the agents are independent executables, so you can also execute them from the command line. With the exception of a pull-subscription setup, all agents reside on the Distributor. For pull subscriptions, the Subscriber executes its own Distribution Agent in order to pull the data from the distributor. Chapter 7 explains pull subscriptions in more detail. Chapters 4 and 8 cover the roles of all the agents in more detail.
Best Practices
A replication setup often follows the local distributor model, in which all parts of the Distributor live and run on the Publisher. This model is easier to implement than other models; however, it takes a measurable toll on the Publisher's performance. If the impact becomes too great, you should move distribution to its own server. With the Distributor and all its processes on a separate machine, the impact on the Publisher is minimal. If you have a lot of Publishers using the same Distributor, the distribution database might become a bottleneck. To alleviate this, you should install one distribution database per publishing SQL Server instance. This also signicantly simplies backup and recovery planning.
Setting up Distribution
The exercises in this and the following chapters attempt to show security best practices and point out the requirements for a full-scale installation of replication. To that end, the exercises assume that the Publisher, Distributor, and Subscriber are three distinct machines. If you plan to try out these exercises and I encourage you to do so you 78
Chapter 3: The Role of the Distributor need to identify the three servers now. Although the exercises in this chapter are concerned primarily with setting up the Distributor, some of the steps require actions on the other machines. Again, I encourage you to use three separate machines for these exercises. There are several pages in the wizards that won't show if you're on a single machine. Also, to see the dierence between push and pull subscriptions, the Distributor and Subscriber must be dierent machines. Finally, combining two or more machines can hide mistakes that don't show up unless you set up replication on separate machines. To make sure you get the most out of this and the following chapters, using three machines is indispensable. Because most enterprise networks are set up with a Windows domain, we'll assume that the three machines are part of a Windows domain. While it's possible to set up replication outside of a domain, it is not recommended. This book will therefore not go into any details on how that works. However, if you're forced to work outside of a domain, you must ensure that each user account used for replication exists on every machine and is congured with the same password, instead of existing just on the domain controller. The rest of this chapter walks through how to set up a Distributor. We will go through this setup in more detail than we did in Chapter 2. When you have completed the exercises, you'll have prepared a SQL Server instance to act as a Distributor in a full-scale replication setup. You will know what the dierent settings mean and how to set them based on your requirements. As you work through these exercises, you might notice that some of the screenshots seem to be repeated from Chapter 2. Although we use some of the same interface components, such as the Congure Distribution Wizard, we won't be using those components in exactly the same way, so be aware that there are dierences.
79
Removing replication
To be able to follow along with the exercises in the next sections, you need to start with SQL Servers on which replication is not yet installed. If replication has been set up on any of your servers maybe because you followed the steps in Chapter 2 you need to remove it now. However, before you continue, make sure that the existing replication setup is not needed. It can be very time consuming to recongure a replication setup if you've accidentally dropped it. The easiest way to remove replication is to connect to the SQL Server instance in Object Explorer and generate a script to delete replication, as described in the following steps: 1. Right-click the Replication folder and then click Generate Scripts, as shown in Figure 3-1.
Figure 3-1:
80
Chapter 3: The Role of the Distributor This launches the Generate SQL Script dialog box (shown in Figure 3-2). Using this dialog box, you can generate scripts that either create or delete replication components.
Figure 3-2:
2. In the Script the commands section, select the option To drop or disable the components.
81
Chapter 3: The Role of the Distributor 3. Select all available components that are listed. That means the Distributor, all publications, and all subscriptions that are not grayed out. 4. At the bottom of the screen, click Generate Script, and then click Open in New Query Window. A script is then generated that you can use to drop all the selected replication components. 5. Run the script to delete the specied components. If the setup you're trying to remove involves more than one SQL Server instance, you have to repeat these steps for each instance. Start with the Subscribers, followed by the Publishers, and nally the Distributor. If any of the steps generate an error, make sure you're removing the instances in the correct order, and then regenerate and run the new scripts. You'll need to regenerate them because the previous run probably made changes to the setup. In some cases, you might run into a particularly stubborn case in which you continue to receive errors even if you've tried to regenerate the script. In such cases, try stopping all the replication agents before running your scripts. (In a default replication setup, that means stopping the SQL Server Agent jobs that run the replication agents.) 6. If you have a single server setup, such as the one described in Chapter 2, you might have to manually delete any remaining orphaned subscription entries. In such cases, right-click the subscription, and then click Delete, as shown in Figure 3-3. When prompted to conrm your deletions, conrm that you're deleting the correct object, and accept the changes accordingly.
82
Figure 3-3:
83
Figure 3-4:
84
Chapter 3: The Role of the Distributor 3. This launches the Congure Distribution Wizard. If the rst page to appear is the Welcome screen, click Next to go to the Distributor page (shown in Figure 3-5).
Figure 3-5:
Because we're setting up the Distributor on the current SQL Server instance, select the rst option on the Distributor page, and then click Next. 4. The Snapshot Folder page appears and asks for the snapshot folder location, as shown in Figure 3-6.
85
Figure 3-6:
Most processes that access the snapshot folder run on the Distributor. For this reason, it's considered a best practice to create a network share on the Distributor itself. That gives direct and therefore fast access to the local processes while also allowing for scenarios such as pull subscriptions that require remote access. (Pull subscriptions are covered in Chapter 7.) Wherever you place the snapshot folder, make sure that the drive has enough room to hold a bcp copy of all replicated tables. The details on who needs to have which type of access to the snapshot folder are discussed in later chapters. Enter the full path to the network share you want to use, and then click Next.
86
Chapter 3: The Role of the Distributor 5. The next page of the wizard is the Distribution Database page. Here, you provide details about the distribution database, as shown in Figure 3-7.
Figure 3-7:
Depending on the number of Publishers using this Distributor, the number of articles published and, most importantly, how often those articles change, the distribution database can become quite large and busy. Follow the standard best practices for placing and sizing busy databases when picking a location for the distribution database les. While it's often a good idea to do so, the Congure Distribution Wizard does not allow you to create multiple distribution databases. The section, Implementing multiple distribution databases, later in the chapter, provides detailed information on why it might be a good idea to have multiple distribution databases, and on how to set them up.
87
Chapter 3: The Role of the Distributor Provide a name for the database and the folder locations for the data and log les, and then click Next. 6. On the next page of the wizard, Publishers, you specify which servers can use the Distributor when they become Publishers. Figure 3-8 shows the Publishers page.
Figure 3-8:
Every Publisher needs to be registered with the Distributor. This page shows a list of all registered Publishers. Because we're just setting up this Distributor, the list will contain only the Distributor itself when the page rst appears. To enable the instance you selected as Publisher to use this Distributor, click the Add button, and then select SQL Server Publisher in the drop-down list that appears. A standard SQL Server Connect to Server dialog box appears and lets you pick your publishing server instance. After you've connected to that instance, it will appear in the list, as shown in Figure 3-8. 88
Chapter 3: The Role of the Distributor For the Distribution Database option associated with the new Publisher, youll nd that the distribution database is automatically selected and you can't change it. You can nd more information about how to use multiple distribution databases later in this chapter. There are a few other settings that are automatically selected as well. You can get to them by clicking the ellipsis button at the end of the row that lists your Publisher. Chapter 5 provides more information about those settings. 7. After adding your Publisher, uncheck the Distributor itself, as this server will not be used as a Publisher in this example. Once you've added the Publisher and deselected the Distributor, click Next. 8. When you add a SQL Server instance that is not the Distributor, as you've just done, the next page to appear in the Congure Distribution Wizard is the Distributor Password page (shown in Figure 3-9).
Figure 3-9:
89
Chapter 3: The Role of the Distributor On this page, you specify the password that remote Publishers must use to access the Distributor. Every time you set up a Publisher and connect it to the Distributor, you must provide this password. Be sure to pick a secure password and store it somewhere safe. Enter the password (twice), and then click Next. 9. The next few pages of the Congure Distribution Wizard are the nalizing pages that you saw in Chapter 2. Be sure to select the Congure distribution option (on the Wizard Actions page), review the conguration steps, and let the wizard do its magic.
90
Chapter 3: The Role of the Distributor 5. When you're returned to Congure Distribution Wizard, the Distributor page should look similar to what is shown in Figure 3-10. After you review the information, click Next.
6. The next page in the Congure Distribution Wizard is the Administrative Password page (shown in Figure 3-11).
91
Figure 3-11:
The password asked for here is the same password that we picked for the Distributor in the previous exercise on the Distributor Password page. Enter the password (twice), and then click Next. 7. The remaining pages let you pick whether the wizard should create a script or should run the setup immediately. For this exercise, you should run the setup immediately. You'll be able to review the steps that the wizard will take when performing that setup. Once the wizard has completed running, the distribution setup is complete.
92
Figure 3-12:
93
Chapter 3: The Role of the Distributor This will open the Distributor Properties dialog box. On the General page, you'll see a list of the installed distribution databases. 3. Click the New button beneath the list of distribution databases. This opens the New Distribution Database dialog box, shown in Figure 3-13.
Figure 3-13:
Here you specify the name and folder locations for the new distribution database. You can also specify retention values, which are covered in Chapter 7. For now, leave these retention options at their default values.
94
Chapter 3: The Role of the Distributor 4. Click OK to create the new distribution database, and then close the New Distribution Database dialog box. You'll be returned to the Distribution Properties dialog box, which will now list both distribution databases. 5. Switch to the Publishers page of the Distribution Properties dialog box. 6. Click the Add button, and then click Add SQL Server Publisher. A Connect to Server dialog box appears (shown in Figure 3-14). This lets you register additional Publishers with this Distributor.
95
Chapter 3: The Role of the Distributor 7. Select the SQL Server instance that you want to add as a Publisher. Then select an authentication type and, if applicable, a login and password. Next, click Connect. The Publisher will be added to the list of registered Publishers on the Publishers page of the Distributor Properties dialog box. 8. In the row for the new Publisher, select the distribution database you want to use for that Publisher from the Distribution Database drop-down list (next to the Publisher's name), as shown in Figure 3-15.
Figure 3-15:
96
Chapter 3: The Role of the Distributor Make sure you select the correct database, because once you click OK, this selection cannot be changed. The only way to change the distribution database for an existing Publisher is to drop all publications on that Publisher and then delete the Publisher from the list of registered Publishers on the Distributor. Youll then need to set everything up again. So make sure you select the right distribution database in the rst place. 9. Click OK to close the Distributor Properties dialog box. For more details on how to handle multiple distribution databases, check out the SQL Server Central article, Scaling out the distribution database at http://www.sqlservercentral.com/articles/Replication/69663/.1
Summary
In this chapter, we prepared a SQL Server instance to be a Distributor for replication. We also prepared another SQL Server instance to use that Distributor. We will set up the Publisher for transactional replication in Chapter 5, followed by a Subscriber in Chapter 7. At this point, there is not much to see on the Distributor. None of the agents are running yet, and nothing else will show any activity. Although there are now distribution databases on the server, they're well hidden amongst the system databases. The only visible change is to the context menu of the Replication folder in Object Explorer. The menu now includes the Distributor Properties option, instead of Congure Distribution. This might feel a little disappointing spending so much eort and having nothing to show for it. Keep in mind, however, that the Distributor is the most important piece of a transactional replication installation. Without it, no data would move anywhere. The reward for this work will come soon, so let's get started setting up the Publisher.
1
97
Replication Agents
The SQL Server Database Engine does not carry out the tasks associated with executing transactional replication. Instead, the replication process is driven by several external services known as replication agents. Replication agents are Windows programs that connect to the replication servers and facilitate data movement. At rst glance, there seems to be an overwhelming amount of moving parts required to make transactional replication work. However, when you look more closely, you'll nd that there are really only three main players: the Snapshot Agent, the Log Reader Agent, and the Distribution Agent. Figure 4-1 provides an overview of the three primary replication agents. (Bi-directional transactional replication also utilizes the Queue Reader Agent, which applies changes made on a Subscriber to the Publisher. For more information about the Queue Reader Agent, check out SQL Server Books Online.)
98
Figure 4-1:
The arrows in the gure show how the replication agents work with the data. The arrows indicate the direction of the data ow; the green arrows indicate read access, whereas the red arrows indicate write access. For example, the Log Reader Agent reads data from the publication database and writes data to the distribution database. The Snapshot Agent and the Log Reader Agent reside on the Distributor. The Distribution Agent, however, can live either on the Distributor or the Subscriber, depending on whether the subscription has been set up to follow the push or the pull model. Let's take a closer look at each of these agents to get a better sense of how they work. 99
Snapshot Agent
The Snapshot Agent is the main player in snapshot replication. However, in transactional replication as well as all other replication types, the Snapshot Agent performs the initial synchronization of the replicated objects. Although this is not the only way to execute the initial synchronization, it is certainly the most convenient way. Generating a snapshot involves two steps. First, the Snapshot Agent generates the scripts necessary to drop and create the replicated objects on the Subscriber. After that, the agent uses the bcp utility to generate les that contain copies of the data from all the published tables. The Snapshot Agent places the les in the snapshot folder and maintains a record of each le in the distribution database. If, after creating the snapshot, you run the SELECT statement shown in Listing 4-1 against the distribution database, you'll see that the MSRepl_commands table contains one record for each le that was generated. (The table also contains records for other replication-related activity, such as changes to the data, so don't be surprised to see a lot of other records in there.)
SELECT publisher_database_id, xact_seqno, type, article_id, originator_id, command_id, partial_command, CAST(command AS NVARCHAR(MAX)) AS command_text, command, hashkey, originator_lsn dbo.MSrepl_commands;
FROM
Listing 4-1:
Retrieving information from the MSRepl_commands table about the data les.
100
Chapter 4: Transactional Replication the Replication Agents During snapshot replication, SQL Server places a shared lock on the published tables while the bcp utility generates the data les. This allows the Snapshot Agent to guarantee transactional consistency of the data; however, it blocks other requests trying to write to those tables while the locks are in place. Depending on the size of the tables, the time it takes to create the snapshot can be substantial, but this is the only way to guarantee transactional consistency in snapshot replication. In transactional replication, the shared table locks are not required. Starting with SQL Server 2005, if you set up transactional replication through SQL Server Management Studio (SSMS), SQL Server uses a dierent method to generate snapshots. This method allows changes to the published tables during the snapshot generation process. When the process starts, SQL Server places a table lock on all tables involved in the publication and then writes a marker to the log le associated with the publication database. The marker indicates the beginning of the snapshot process. Right after the marker is written, SQL Server releases the locks. The Snapshot Agent then generates the bcp les without taking further table locks, but be aware that SQL Server maintains ne-grained, short-lived locks at the page and row levels. After the Snapshot Agent creates the bcp les, SQL Server writes another marker to the log le of the publication database, recording the end of the snapshot process. These markers are then used by the Log Reader Agent to copy any changes committed to the published objects (as recorded in the log le between those two markers) to the distribution database. When it is time to apply the snapshot, the Distribution Agent uses the scripts generated by the Snapshot Agent during the rst step to drop and re-create the tables in the subscription database. It then bulk-loads the data from the bcp les in the snapshot folder into those tables. During the load process, SQL Server maintains table locks on all subscription tables aected. With the table locks still in place, as the last step, the Distribution Agent uses the log data that captured the activity during the snapshot generation to bring all tables into a transactionally consistent state.
101
102
Chapter 4: Transactional Replication the Replication Agents One reason for this has to do with Virtual Log Files (VLFs). A log le is split into VLFs, and as long as one is required, that VLF and the ones that logically follow cannot be reused. For example, a VLF might be required for a lengthy period of time for long-running transactions or outstanding log backups. Only after SQL Server does not need a VLF to warrant transactional consistency will it be reused. SQL Server manages this process automatically. With replication, however, there is an additional reason that can prevent VLFs from being reused. Because the Log Reader Agent has to process every log record in the publication database, reuse cannot occur until the Log Reader Agent processes all records in the VLF. Several situations can prevent the agent from processing log records in a timely manner. The most obvious ones are the Distributor being down or the Log Reader Agent not running. An overloaded Distributor can also cause a delay in log record processing. When the VLFs cannot be reused, the log le must grow to continue to function, and the le lls up. Depending on the log le's autogrow setting, this operation can take a signicant amount of resources. If the log le has reached its congured maximum size or the drive is full, SQL Server will prevent any further write access to that database until the issue is resolved. After you've set up replication, keep an eye out for the size of the log le associated with your publication database. You can use the query in Listing 4-2 to verify whether replication is preventing log record reuse. If the log_reuse_wait_desc column contains the value REPLICATION over an extended period of time, replication is the reason for unexpected log growth.
SELECT FROM log_reuse_wait_desc, Name sys.databases
Listing 4-2:
103
Distribution Agent
The Distribution Agent moves data from the distribution database to the subscription database. The Distribution Agent connects to the Distributor and reads the recorded changes. Then it connects to the Subscriber and applies those changes in the order they occurred. That order is guaranteed within a single subscription and single publication, but not across publications. In some cases, this can lead to logical inconsistencies. For example, if you have two tables that have a foreign key relationship on the Publisher and those two tables are published in separate publications, two inserts into the two tables could get executed in the wrong order on the Subscriber, leading to a temporarily orphaned record in the child table. However, replication by default does not copy foreign key constraints to the Subscriber, so you will not receive an error if a logical inconsistency should occur. To be safe, tables that have a foreign key relationship should always be published in the same publication. If the subscription is a push subscription, the Distribution Agent runs on the Distributor. That means that the Distributor is in control of when the distribution to each Subscriber occurs. For a pull subscription the agent is located on the Subscriber, in which case the Subscriber controls the synchronization schedule. In most cases, you'll want to use the push subscription model, but if you have several Subscribers and you need to start and stop the data ow to each of them at dierent times (such as having to wait for a nightly reporting process), you're better o using the pull subscription model.
Summary
In this chapter, we discussed the internals of the replication agents. We looked at the purpose of each replication agent in detail and discovered what steps each is taking to make replication work. We also recognized that a replication process that is running slow can have a signicant impact on the size of the publication database's log le.
104
Chapter 4: Transactional Replication the Replication Agents After all this theory, let's now move on to actually setting up transactional replication. In Chapter 5, we'll create a publication, in Chapter 6 we'll set up the permissions necessary to set up a subscription, and in Chapter 7 we'll subscribe to that publication. Chapter 8 will close out the section on transactional replication with an in-depth look at the dierent SQL Server Agent jobs involved in transactional replication.
105
Chapter 5: Transactional Replication the Publication If you have not done so yet, please visit Chapter 3 for details about setting up distribution on both the Distributor and the Publisher. Once you've set up your Distributor and your Publisher, you need to identify a database on the Publisher that you want to congure for replication, and then you must enable that database to support replication.
Creating a database
For the exercises in this chapter, we'll build our own database rather than use an existing one. Listing 5-1 shows the T-SQL script that you can run to create the ReplA database on your system.
USE MASTER; GO EXECUTE AS LOGIN = 'SA'; GO CREATE DATABASE ReplA; GO USE ReplA; GO IF OBJECT_ID('dbo.Test') IS NOT NULL DROP TABLE dbo.Test; GO CREATE TABLE dbo.Test( Id INT IDENTITY(1,1) PRIMARY KEY, Data INT CONSTRAINT Test_Data_Dflt DEFAULT CHECKSUM(NEWID()), Data2 INT CONSTRAINT Test_Data2_Dflt DEFAULT CHECKSUM(NEWID()), Data3 INT CONSTRAINT Test_Data3_Dflt DEFAULT CHECKSUM(NEWID()) );
107
Listing 5-1:
Notice that the script, in addition to the database itself, creates several objects: a table, a stored procedure, a view, an indexed view, and a function. We can replicate any of these objects from our Publisher to our Subscriber.
108
109
Figure 5-1:
This launches the Publisher Properties dialog box, which has two pages: The General page allows you to specify a new administrative password for the connection to the Distributor in the event it was changed there. The Publication Databases page (shown in Figure 5-2) lets you enable databases for publishing. For each database, you can select whether transactional replication, merge replication, or both are allowed.
110
Figure 5-2:
On the Publication Databases page, select the Transactional option associated with the ReplA database. 3. Click OK to conrm your change and close the Publisher Properties dialog box. That's all there is to enabling transactional replication on the ReplA database. You're now ready to create your publication. 111
Creating a Publication
The easiest way to create a publication is to use the New Publication Wizard. Except for conguring the security accounts themselves, you can use the wizard for the entire setup process. However, to make the process more manageable, we've broken down the exercise into several tasks: conguring the database for replication, selecting which articles to replicate, setting up the initial snapshot, and conguring security.
112
Figure 5-3:
2. When the New Publication Wizard appears, advance to the Publication Database page, shown in Figure 5-4.
113
Figure 5-4:
If you started the wizard as a member of the db_owner xed database role instead of as a sysadmin, the page will list only the databases that you own and that have been enabled for publishing. There will also be a note advising you that not all databases might be included in the list, as shown in Figure 5-5.
114
Figure 5-5:
If, instead, you get the message box shown in Figure 5-6, refer back to the previous section about enabling a database for replication.
Figure 5-6:
115
Chapter 5: Transactional Replication the Publication 3. From the list of databases shown in the Publication Database page, select the database that you want to publish (in this case, ReplA), and then click Next to advance to the Publication Type page, shown in Figure 5-7.
Figure 5-7:
4. From the list of publication types, select Transactional publication. If you are only a member of the db_owner role, you might now see the error shown in Figure 5-8. It informs you that the selected database is not enabled for the type of replication selected, and it prevents you from continuing. Again, check back to the previous section for information about enabling a database for transactional replication.
116
Figure 5-8:
5. After selecting the publication type, click Next. This will take you to the Articles page, which we'll review in the next section.
117
Figure 5-9:
118
Chapter 5: Transactional Replication the Publication You congure the articles by using the Article Properties dialog box (described in the next step). The options available for conguring an article depend on the associated object type: By default, a table article replicates the data in the table as well as any schema changes to the table. However, you have the option to replicate only the data and ignore changes to the table schema. For a stored procedure, you can choose to replicate the procedure denition or the denition and each execution. Replicating an execution in this context means that each time the procedure runs on the Publisher, it will be called with the same parameters on each Subscriber. Data changes to underlying tables that happen during the execution of the procedure will not be replicated separately. This can be a great performance benet because potentially a lot less data has to be moved. Views and functions always replicate the schema only. Indexed views are schema only by default. However, they can get replicated as tables; that means on the Subscriber side a table is created instead of a view. All schema changes to the indexed view as well as changes to the underlying data will be applied to that table. For a complete list of articles and their restrictions, check out the topic, Publish Data and Database Objects,1 in SQL Server Books Online. 2. Associated with each article is a set of properties that you can view or recongure. To access the properties associated with the Test table, select the table in the Objects to publish list, and then click the Article Properties button. This opens a drop-down list that lets you choose between showing the Article Properties dialog box for the highlighted article only, or showing the dialog box for all table articles in the
119
Chapter 5: Transactional Replication the Publication publication. The second option allows you to change the properties of all articles of a single type (the type of the highlighted object) in one shot. For this exercise, select the rst option to open the Article Properties dialog box for the Test table only, as shown in Figure 5-10.
The list of properties changes depending on the type of article you have selected. For example, depending on the article, you can specify the name of the target object, what to do if the target object already exists, whether to replicate each stored procedure execution along with the denition, etc. For a detailed list of the available options and their explanations, refer to the topic, Publish Data and Database Objects,2 in SQL Server Books Online.
2
120
Chapter 5: Transactional Replication the Publication 3. For now, we'll stick with the Test table's default property settings, so click Cancel to close the Article Properties dialog box. 4. For table articles, there is one more option to be aware of. You can choose to publish the entire table or a subset of columns within that table. If you refer back to Figure 5-9, you'll notice a plus sign next to the Test table in the Objects to publish list. By clicking the plus sign, you can expand the table node to display the table's columns, as shown in Figure 5-11. Here, you can select individual columns to be replicated or to be excluded.
Figure 5-11:
When selecting columns to be replicated, you must always include the primary key. All other columns can be omitted. In such cases, when you select individual columns, you're creating a vertical lter. 121
Chapter 5: Transactional Replication the Publication For the rest of this chapter, we'll assume you did not choose to exclude any columns. So make sure all columns are selected, and click Next to advance to the Filter Table Rows page. This page appears only if you selected at least one table article on the previous page, as we have done in the example. 5. Click Add to open the Add Filter dialog box, which is shown in Figure 5-12.
Figure 5-12:
122
Chapter 5: Transactional Replication the Publication The Add Filter dialog box lets you create a lter that species which rows to replicate in your selected table article. This type of lter is known as a horizontal lter and looks like a SELECT statement that includes a WHERE clause. The part of the SELECT statement before the WHERE keyword is automatically supplied and cannot be changed. After the WHERE keyword, however, you can specify the clause's condition. For example, if you dene the WHERE clause as WHERE Data > 42, only rows with a Data column value greater than 42 will be replicated. Be aware that a horizontal lter uses signicant additional resources because every row that was changed on a ltered article has to be inspected to see whether or not it matches the lter. For more details on horizontal lters, check out SQL Server Books Online. 6. Click Cancel on the Add Filter page to return to the Filter Table Rows page without creating a lter, and then click Next to advance to the next page of the New Publication Wizard. 7. At this point, depending on the type of articles you selected, you might see the Article Issues page. The page warns you of potential issues that could arise from your selection. Figure 5-13 shows an example of the page with a couple of issues listed.
123
Figure 5-13:
This page does not mean that there is a problem. It only points out areas that often cause problems later. If it appears, make sure you look thoroughly through each point listed and then make the necessary changes, if any. Usually you can just advance to the next page by clicking Next. This will get you to the Snapshot Agent page, which we cover in the next section.
Chapter 5: Transactional Replication the Publication The Snapshot Agent creates the snapshot and stores it in the snapshot folder on the Distributor. The following steps describe how to congure the Snapshot Agent: 1. On the Snapshot Agent page of the New Publication Wizard, you can choose to have the Snapshot Agent create the snapshot immediately after the publication has been created, or you can schedule the agent to run at a later time, as you can see in Figure 5-14. If you choose to schedule the agent to run at a later time, you're presented with the SQL Server Agent New Job Schedule dialog box, which lets you create a schedule for running the Snapshot Agent.
If you're setting up a publication that will have only one Subscriber, you should probably create the snapshot immediately. On the other hand, if you'll need to resynchronize multiple Subscribers often, you should consider setting up the agent to refresh the 125
Chapter 5: Transactional Replication the Publication snapshot regularly so you're always working with fresh data. Remember, however, that a snapshot is needed only when adding a new Subscriber to a publication or when an existing Subscriber needs to be resynchronized, such as when it has been disconnected for too long. Also keep in mind that creating a snapshot particularly if large tables are involved can be quite resource intensive. Depending on the size of the tables and the network speed, generating a snapshot can take several hours. With all this in mind, you usually do not want to schedule the Snapshot Agent to run at regular intervals. However, because of the impact that taking a snapshot can have, it might be a good idea to schedule it to run during o-hours instead of right away. 2. For this exercise, select the "immediate" option, as shown in Figure 5-14, and then click Next to advance to the Agent Security page, which is covered in the next section.
Setting up security
The next step on our way to a working publication is to set up replication agent security. Remember that replication agents are independent Windows programs responsible for actually moving the data. Transactional replication uses a Snapshot Agent, a Log Reader Agent and Distribution Agents. This section shows how to select the accounts that the rst two agents execute under. You will also see how to specify the connection credentials for the agents to use to connect to the Publisher and the Distributor. Distribution Agents will be covered in Chapter 7 when we look at setting up a subscription. It is a general security best practice to have each Windows service or service-like executable run under its own Windows account. That way, you can grant just the minimal set of required permissions to each account. That practice greatly reduces the surface for a potential malicious attack. It also reduces the amount of damage that can be done should an attack be successful. 126
Chapter 5: Transactional Replication the Publication The replication agents run automatically and unattended, which puts them into this category. Therefore, each one should be given its own account to run under. In this exercise, we follow this best practice and show you how to set up separate accounts. You'll also learn what permissions are required for each account. The following steps walk you through the process of setting up agent security: 1. If you haven't already advanced to the Agent Security page of the New Publication Wizard, do so now. On this page, you assign security accounts to the two agents used to process a transactional publication: the Snapshot Agent and the Log Reader Agent, as shown in Figure 5-15.
Figure 5-15:
127
Chapter 5: Transactional Replication the Publication 2. To set the security conguration for the Snapshot Agent, click the Security Settings button associated with that agent. This opens the Snapshot Agent Security dialog box, shown in Figure 5-16. Here you can provide a Windows login, or you can use the SQL Server Agent service account. Microsoft documentation, however, warns that the latter is not a recommended security best practice, so you should provide a Windows login.
The Connect to the Publisher section of the Snapshot Agent Security page lets you to specify how the agent should connect to the publisher. You can either use Windows authentication (by selecting the option By impersonating the process account), or you can provide a SQL Server login for the connection to the Publisher.
128
Chapter 5: Transactional Replication the Publication For the connection to the distribution database, the agent always uses Windows authentication. Click OK when you are done conguring the security settings for the Snapshot Agent. 3. For the Log Reader Agent, you have the same security options to choose from if you click the agent's associated Security Settings button. However, instead of taking this approach, you can use the same settings that you provided for the Snapshot Agent. To do so, select the Use the security settings from the Snapshot Agent check box on the Agent Security page but, as mentioned earlier, it's not recommended to do this. Although replication provides a Snapshot Agent per publication, there is only one Log Reader Agent for each publication database. That means that if you already have a publication dened in your database, you cannot change the Log Reader Agent account here. However, you can still specify a dierent SQL Server login for the Log Reader Agent to use to connect to the publication database for the new publication. 4. After you select the account and connection settings for both agents, the next step is to grant the appropriate permissions to each applicable Windows account and SQL Server login. The Snapshot Agent is responsible for moving data from the publication database to the snapshot folder as well as to the distribution database. As a result, you must make the Windows account assigned to the Snapshot Agent a member of the db_owner xed database role in both the publication database and in the distribution database. The account also needs to have write permission on the snapshot folder. If you set up the Snapshot Agent to not use integrated security to connect to the publication database, but instead use SQL Server authentication, the provided SQL Server login also needs to be a member of the db_owner xed database role in the publication database. In that case the Snapshot Agent Windows account itself does not need to have access to the publication database.
129
Chapter 5: Transactional Replication the Publication For this exercise, we're using the domain\SQL2_S12A_Snapshot Windows account for the Snapshot Agent. To ensure the necessary access rights, we must congure our accounts as follows: A SQL Server login must be associated with this Windows account on both the Distributor and the Publisher. The distribution and publication databases must each include a user that is associated with the login. Each user must be member of the db_owner xed database role in that user's database. The domain\SQL2_S12A_Snapshot Windows account must also be granted write access to the snapshot folder, in this case \ \SQL1\ReplDataS12A. You should consult SQL Server and Windows documentation as necessary for details about how to set up these accounts. 5. The Log Reader Agent also copies data from the publication database to the distribution database, but it does not make use of the snapshot folder. The Windows account assigned to the Log Reader Agent needs to be a member of the db_owner xed database role in the distribution database. In addition, the Windows account (or the SQL Server login, if you're using SQL Server authentication to connect to the publication database) needs to be a member of the db_owner xed database role in the publication database. For this exercise, we're using the domain\SQL2_S12A_LogReader Windows account for the Log Reader Agent. To ensure the necessary access rights, we must congure our accounts as follows: A SQL Server login must be associated with this Log Reader Agent account on both the Distributor and the Publisher.
130
Chapter 5: Transactional Replication the Publication The distribution and publication databases must each include a user that is associated with the login. Each user must be a member of the db_owner xed database role in that user's database. Once again, you should consult SQL Server and Windows documentation as necessary for details about how to set up these accounts. 6. After you have congured the security settings for both agents and made sure the appropriate rights have been granted to these accounts, click Next to proceed to the Wizard Actions page, where we'll nish the setting up of the publication.
131
Figure 5-17:
If you create two publications on dierent databases, you can use the same name for both of them. However, if you have multiple publications, I strongly recommend that you use meaningful and distinguishable names. A replication setup has a lot of moving parts. There is no need to cause additional confusion by choosing the same or similar names for multiple publications. 3. Type MySecondPublication into the Publication name text box, review the summary on the Complete the Wizard page, and then click Finish. The wizard will create the publication while displaying progress information on the Creating publication page. Once this step is complete, click Close.
132
Chapter 5: Transactional Replication the Publication These are all the steps necessary to create a publication. To see if everything worked correctly, we need to rst create a subscription. The next two chapters will cover the steps for doing just that. In the meantime, you can check that the publication was actually created, by returning to Object Explorer, expanding the Replication folder and then expanding Local Publications folder, as shown in Figure 5-18.
Your new publication should now be listed under the Local Publications folder, which means you can now create a subscription. But rst, let's look at several issues that could arise when setting up your publication.
133
Potential Problems
Because there are so many steps to take and decisions to make when conguring replication, you might run into issues during the setup. The most common problem is an account that does not have the appropriate rights. If something does not seem to work as expected, review all applicable accounts and make sure that they're congured with the correct permissions. Another issue that might complicate matters is that error messages do not always point you in the right direction. For example, the message, The remote server "SQL1\S12A" does not exist, or has not been designated as a valid Publisher really means that the Snapshot Agent does not have the necessary permissions to access the distribution database. It has nothing to do with the Publisher. What makes matters even more difficult is that nding the error messages is not always a straightforward process. You should also take into account several other considerations when implementing replication. (Chapter 14 will provide more details about how to troubleshoot replication.) If you're using a snapshot share that is located on the Distributor, you might have to grant write access to the Snapshot Agent account on both the share and the underlying folder. If you've assigned Windows domain accounts to the replication agents and use impersonation to connect to the other servers in your replication setup, you might have to grant the Windows account that is executing the SQL Server service read access to Active Directory. This is a best practice anyway. Check out SQL Server Books Online and Windows documentation for details on why and how to do this. In general, you should use a SQL Server login (such as SA) to execute the replication wizards, instead of a Windows account. A full discussion of why you should do this is beyond the scope of this book. However, you'll usually run into fewer issues not only with replication, but with other functionality as well if the objects you're dealing with are owned by a user associated with a SQL Server login and not a Windows account. 134
Summary
In this chapter, you learned how to create a publication for transactional replication. The chapter explained who is allowed to create a publication and what permissions the replication agents involved in a publication require to do their jobs successfully. In addition, the chapter described how to add articles to the publication and what object types you can select as articles. You also learned how to schedule the Snapshot Agent in order to generate the initial snapshot. Finally, the chapter pointed out potential problems you might run into when implementing replication. Using this information, you should now be able to set up your own publication. Once you do, any modications to the publication articles are recorded in the distribution database. However, because Subscribers have yet to be set up, no one is collecting that data from there, which means the distribution database will steadily grow, potentially a lot. The next step is to set up a Subscriber, which we'll cover in the following chapters.
135
Setting Up a Subscription
As you learned in Chapter 5, to create a publication in a database, two requirements must be in place: The login used to execute the setup needs to have at least db_owner level permissions in the publication database. The database itself needs to be enabled for publishing. Enabling a database for publishing requires sysadmin privileges. However, it needs to be done only once per database. The requirements for a new subscription are a little more complex. During setup, information needs to be gathered from the distribution database and changes need to be applied to that database, the publication database, and the subscription database. Additionally, you must provide an account to run the Distribution Agent. As a result, all three locations require a substantial list of permissions. SQL Server supports two subscription models: pull subscriptions and push subscriptions. Chapter 7 provides information about both models and explains the dierences between them. For now, however, know that in a pull subscription the Subscriber is responsible to 136
Chapter 6: The Publication Access List collect data changes from the publication, whereas in a push subscription the Distributor actively pushes the data to the Subscribers. A push subscription requires the complex permission set mentioned above, but a pull subscription requires a signicantly reduced set of permissions. A discussion of the permissions required to set up a push subscription is beyond the scope of this book (although you can use an account with sysadmin privileges to simplify matters). For more details about the required permissions, see SQL Server Books Online. The easier case of the pull subscription is, however, worth spending time on. To be able to set up a pull subscription, your account needs to fulll only two requirements: Be a member of the db_owner database role in the subscription database. Be added to the Publication Access List (PAL) of the publication. Before we continue, make sure that your login is mapped to a user in the subscription database that is a member of the db_owner role. Check SQL Server Books Online for details on how to do this.
137
Chapter 6: The Publication Access List Only logins that meet the following three requirements can be added to the PAL for a specic publication: the login must exist on the Distributor the login must exist on the Publisher a user associated with that login must exist in the publication database. You do not need to grant any permission to the user in the publication database. The user in the publication database is required only because the PAL information is stored in that database. Login information, on the other hand, is stored in the master database, so that information might not be accessible in all situations. However, database user information is readily available within each database, as it is stored at the database level. The following steps walk through adding an account (in this case, DOMAIN\SQL3_PAL) to the PAL: 1. The PAL is maintained on the Publisher. Therefore the rst step is to connect to it in SSMS. 2. In Object Explorer, expand the Replication folder and then the Local Publications subfolder. 3. Right-click your publication and then click Properties, as shown in Figure 6-1.
138
Figure 6-1:
4. When the Publication Properties dialog box appears, go to the Publication Access List page, as shown in Figure 6-2. The page contains a list of the logins that are already members of the PAL.
139
Figure 6-2:
5. Click the Add button on the right-hand side to add a new login to the PAL. This opens the Add Publication Access dialog box, as shown in Figure 6-3.
140
Figure 6-3:
The dialog box contains all logins that are eligible to be a member of the PAL, but that are not yet on that list. If your login is not included here, make sure that it meets the three requirements that are listed at the beginning of this section. 6. Select the login that you want to add (DOMAIN\SQL3_Pal in this example), and click OK to close the Add Publication Access dialog box. Then click OK to close the Publication Properties dialog box. This is all you need to do to add a login to the PAL.
141
Summary
In this chapter, we learned about the minimal security requirements for an account used to create a pull subscription. We also discovered how to congure the PAL. We'll encounter the PAL a few more times during the rest of the book, as it is a requirement for the accounts running the Distribution Agents or Merge Agents.
142
143
Setting up a Subscription
The easiest way to create and congure the actual subscription is to use the New Subscription Wizard. The wizard walks you through each step necessary to set up the subscription. However, this process can be a bit overwhelming, so we've broken it down into several tasks: connecting to the Publisher, selecting the subscription type, specifying the Subscriber and subscription database, and conguring security on that database.
144
Figure 7-1:
3. If a Welcome page appears, advance to the Publication page, shown in Figure 7-2. Here we identify the Publisher, the publication database, and the publication itself.
145
Figure 7-2:
First, we need to select the Publisher using the Publisher drop-down list. If as previously suggested you are using a separate instance for your Subscriber, your Publisher won't be listed here. Click the Find SQL Server Publisher option to open a standard SQL Server connection dialog box, where you can connect to the SQL Server instance that is your Publisher. 4. After you connect to your Publisher, it will be automatically selected in the Publisher drop-down list. Additionally any publication databases and publications dened on that Publisher are listed in the Databases and publications window, as shown in Figure 7-3.
146
Figure 7-3:
If you performed the exercises in Chapter 5, the publication MySecondPublication will be listed beneath the ReplA publication database. 5. Select the MySecondPublication publication, and then click Next to advance to the Distribution Agent Location page, which we cover in the following section.
147
148
Chapter 7: Transactional Replication the Subscription This page lists two options. Run all agents at the Distributor will congure the subscription as a push subscription. Run each agent at its Subscriber will congure the subscription as a pull subscription.
Figure 7-4:
2. Select the rst option (as shown in Figure 7-4), and then click OK to continue to the Subscribers page, which we cover in the next section. Note that, if you set up your subscription as a pull subscription instead of push, you'll see dierences from what we show here when you get to the Distribution Agent Security page later in the wizard. However, the dierences are minor, so you should still be able to follow along if you go with a pull subscription.
149
Figure 7-5:
150
Chapter 7: Transactional Replication the Subscription 2. The Subscribers and subscription databases grid already shows the Subscriber you connected to in the beginning SQL3\S12A, in the example. However, you need to make sure the check box associated with the Subscriber is selected. 3. In the Subscription Database column of the row associated with your Subscriber, select the applicable subscription database. Or you can instead select the New Database option, which launches the New Database Wizard and lets you create a subscription database on the y. If you select an existing database, be careful to pick the correct one. The subscription initialization step drops and re-creates all objects in the subscription database that are part of the subscription.
Note
If you pick the wrong database and that database has objects with the same name as objects being replicated, those objects will be dropped. You will receive no warning messages to let you know that this is happening.
The Subscribers page of the New Subscription Wizard also lets you to associate more than one Subscriber with your publication. For this, you can click the Add Subscriber button to add as many Subscribers as necessary. However there are some limitations. For example, all Subscribers that are set up together in this way have to use the same subscription model (push or pull). Also, while it is possible to have a single Subscriber subscribe to a single publication more than once using distinct subscription databases, the wizard allows for each Subscriber to be included only once. It's generally advised that you run the wizard again for each new subscription. Therefore we won't be discussing this option further. 4. To complete this step, make sure that you've selected the correct subscription database and veried that the check box associated with your Subscriber is selected, and then click Next to advance to the security section of the wizard, which we cover in the following section. 151
152
Figure 7-6:
2. For each Subscriber, you have to select the necessary accounts by using the Distribution Agent Security dialog box. To launch the dialog box, click the ellipsis button at the end of the row associated with the specic Subscriber. Figure 7-7 shows the Distribution Agent Security dialog box for our Subscriber (SQL3\S12A). The one shown here is specic to a push subscription. However, the dialog box that appears for a pull subscription is very similar. It diers only in the fact that it allows for a SQL Server login to be selected to connect to the Distributor, rather than the Subscriber.
153
Figure 7-7:
The number of connections and accounts needed to set up replication can seem overwhelming at rst. Refer back to Chapter 4 for more details about the replication agents. In addition, Chapter 8 will provide information about the SQL Server Agent jobs that drive the replication agents. 154
Chapter 7: Transactional Replication the Subscription 3. At the top of the Distribution Agent Security dialog box, provide a Windows account for the Distribution Agent to run under and the password associated with the account. For this you should create a new domain account without special access privileges and provide it together with its password here. This example uses the DOMAIN\SQL3_S12A_DistPush account. You can instead choose to use the SQL Server Agent account, but as mentioned before, this is not a good idea from a security perspective. 4. For the connection to the Distributor and the connection to the Subscriber, select the option By impersonating the process account. Assuming your servers belong to the same domain and you are using a new domain account, there is no reason to specify a SQL login here. 5. Click OK to close the Distribution Agent Security dialog box. This brings you back to the Distribution Agent Security page of the New Subscription Wizard.
Account Permissions
Before we continue any further with the New Subscription Wizard, we should rst grant the necessary permissions to the account(s) used to run the Distribution Agent, as described in the following guidelines: The account running the Distribution Agent must have read access to the snapshot folder. The account used by the Distribution Agent to connect to the subscription database must be a member of the db_owner xed database role in that database. The account used by the Distribution Agent to connect to the distribution database must be a member of the PAL and also a member of the db_owner xed database role in the distribution database.
155
Chapter 7: Transactional Replication the Subscription For these exercises, we're using the DOMAIN\SQL3_S12A_DistPush Windows account to run the Distribution Agent, and we're using impersonation to connect to the Distributor and the Subscriber. Therefore this is the only account we need to be concerned with for now. Providing the account with read access to the snapshot folder and making the account a member of the db_owner xed database role should be straightforward. If you have any questions about how to do either, refer to the Windows and SQL Server documentation. And if you need help with adding the account to the PAL, refer back to Chapter 6.
Figure 7-8:
2. Ensure that Run continuously is selected, and then click Next to advance to the Initialize Subscriptions page, shown in Figure 7-9.
157
Figure 7-9:
Here you can select when the subscription should be initialized. You have two options: Immediately and At rst synchronization. The latter holds o with the initialization until the rst synchronization is started. If you had selected anything but the default on the previous page and if the rst scheduled synchronization is far in the future, you should delay the initialization here too. The default is Immediately and in most cases this is the appropriate choice. You can also choose not to initialize the subscription by deselecting the Initialize check box. However, in that case you won't be able to use the subscription until it is initialized by some other means. 158
Chapter 7: Transactional Replication the Subscription For the initialization, a current snapshot must exist. If a long time (more than 24 hours) has passed since you created the snapshot, as outlined in Chapter 5, rerun the Snapshot Agent job manually now. You can nd the Snapshot Agent job by looking in the Job Activity Monitor on the Distributor for a job in the REPL-Snapshot category that has your publication name as part of its name, as shown in Figure 7-10.
Figure 7-10:
3. On the Initialize Subscriptions page of the New Subscription Wizard, make sure both the Initialize check box and the Immediately option are selected, and then click Next.
159
Chapter 7: Transactional Replication the Subscription 4. On the next page that appears, the Wizard Actions page, you can choose whether the subscription is created upon completion of the wizard or whether a script is generated that you can run later to create the subscription. For this exercise, we'll go with the rst option, so select Create the subscription(s), and then click Next. 5. On the nal page of the wizard, review your selections. If everything is to your liking, click Finish to create the subscription.
Conguring Retention
Once you've created your subscription, you should congure the settings that dene replication's retention. Retention refers to the length of time vital publication data is kept before being deleted and how long a Subscriber can be offline before becoming invalid. SQL Server replication supports four retention settings. Three are dened on the Distributor and one on the Publisher. The rst three distribution retention settings are properties dened in the distribution database. Therefore, they are global for all Publishers using the same distribution database. All three are covered in the next section, Conguring retention on the Distributor. The fourth retention setting is publication-specic and is covered in the later section, Conguring retention on the Publisher, which follows the section on conguring the Distributor. Although none of the retention settings are subscription-specic, they are mentioned here because they can have a signicant impact on your Subscribers. A Subscriber that does not request an update within the retention period will be deactivated or dropped. If that happens, a complete resynchronization of the Subscriber is required, making the data on the Subscriber unavailable during that time.
160
Chapter 7: Transactional Replication the Subscription On the other hand, retention settings directly aect how much space you need to provide for the distribution database because data that has not yet been delivered to all Subscribers is held in that database for the specied time. When selecting the replication retention settings, you need to provide your Subscribers with enough time to load the data from the Distributor. For this, you need to plan in time for accidental or scheduled outages. But you also need to keep the time short enough so that the distribution database does not run out of space.
161
Chapter 7: Transactional Replication the Subscription The following steps explain how to set the retention times on the distribution database: 1. In SSMS, connect to the SQL Server instance that you've congured as the Distributor. 2. In Object Explorer, right-click the Replication folder for that instance, and then click Distributor Properties, as shown in Figure 7-11.
Figure 7-11:
When the Distributor Properties dialog box appears, it opens to the General page, as shown in Figure 7-12. The page displays a list of congured distribution databases and their retention values. 162
Figure 7-12: The General page of the Distributor Properties dialog box.
3. Click the browse (ellipsis) button at the end of the row that contains the distribution database whose settings you want to change. This launches the Distribution Database Properties dialog box, shown in Figure 7-13.
163
In the Transaction retention section, you can specify the minimum and maximum retention times, and you can specify whether those values are measured in hours or days. 4. Set the times, click OK to close the Distribution Database Properties dialog box, and then click OK again to close the Distributor Properties dialog box. As mentioned before, if there is transactional data in the distribution database that has not been synchronized with a Subscriber for more than the maximum retention time, the data will be purged, and the Subscriber will automatically be marked as inactive. To reactivate an inactive Subscriber, the subscription has to be reinitialized from a fresh snapshot.
164
Chapter 7: Transactional Replication the Subscription If you have a Subscriber that becomes incapable of synchronizing from time to time, as can occur as the result of scheduled or unscheduled connection interruptions, you need to set the maximum retention time value high enough to guarantee that the Subscriber can reconnect before it is deactivated. On the other hand, the longer the maximum retention time, the more data needs to be stored and kept in the distribution database. So the higher this value, the more storage you need for the distribution database. In addition to the distribution database taking up more hard-drive space, the replication throughput will also decrease. So you need to nd a happy medium between Subscriber availability and storage and performance requirements when setting this value. The default values for transaction retention are 0 hours for the minimum and 72 hours for the maximum. Figure 7-13 also shows a History retention setting. This is the third setting referred to at the beginning of the discussion on retention. This setting denes how long information about the health of the replication setup is kept in the distribution database. The setting does not aect the Subscribers. However, the history data can be helpful in troubleshooting issues that might arise. The default of 48 hours is usually a good choice. The Queue Reader Agent security section at the bottom of the Distribution Database Properties dialog box is not used in a standard transactional replication installation and will not be covered in this book.
165
Chapter 7: Transactional Replication the Subscription For a push subscription, if a subscription lapses past the publication retention period, the subscription is removed completely from the Distributor and nothing remains. For a pull subscription, an orphan is left on the Subscriber that must be cleaned up manually. In either case, if you want to continue to use the instance as the Subscriber, you need to set it up again from scratch. The default value for the publication retention period setting is two weeks (336 hours). The following steps explain how to modify the publication retention period: 1. In SSMS, connect to the SQL Server instance congured as the Publisher. 2. In Object Explorer, expand the Replication folder for that instance, and then expand the Local Publications subfolder. 3. Right-click the publication you want to change, and then click Properties. 4. When the Publication Properties dialog box appears, it opens to the General page, as shown in Figure 7-14. Here you can change the description of the publication as well as congure the retention period, which you do in the Subscription Expiration section. You can either specify a value (in hours) or set the retention period never to expire.
166
Figure 7-14:
5. Congure the retention setting, and then click OK to close the Publication Properties dialog box. All your retention settings should now be congured and your subscription is ready to go.
167
Summary
In this chapter, we worked through the nal piece of a replication setup, the subscription. We discussed how to connect a subscription to a publication, as well as how to select the subscription type and the subscription database. We reviewed the dierences between push and pull subscriptions and the importance of the retention periods. We also learned about the security requirements for a subscription. By the time you get to this point, the rst synchronization should be complete. If you connect to the subscription database, you should see that all the replicated objects have been created. However, if the database does not contain these objects yet, wait a little longer. It can take several minutes for the rst synchronization to nish, even on a very small table. After the rst synchronization is completed, you can insert or update a row in the publication database. After your change has been replicated to the Subscriber, you'll be able to see it applied in the subscription database. Transactional replication consists of many parts, including replication agents, SQL Server Agent jobs and special databases. We have already touched upon most of the parts. What we haven't yet discussed in detail are the SQL Server Agent jobs that process the replication agents and keep transactional replication running. Those, we dive into in Chapter 8.
168
169
Chapter 8: SQL Server Agent Jobs for Transactional Replication If you need to generate a new snapshot for a publication, you can manually run the Snapshot Agent job associated with that publication, or you can schedule the job to run at a later time.
170
Chapter 8: SQL Server Agent Jobs for Transactional Replication The pull subscription distribution jobs follow a slightly dierent naming pattern: <Publisher>-<Publication Database>-<Publication>-<Subscriber><Subscription Database>-<GUID>
171
Figure 8-1:
The default SQL Server jobs on the Distributor, Publisher, and Subscriber.
Local distribution
When you congure a SQL Server instance to be a Distributor, replication setup creates several SQL Server Agent jobs, as shown in Figure 8-2.
172
Figure 8-2:
As you can see, six SQL Server Agent jobs have been created on the Distributor: Agent history clean up: <distribution database name> Removes from the distribution database all history records that keep track of the agents' performance. The job uses the history retention setting of the distribution database to determine which records to delete. SQL Server creates one job of this type for each distribution database on the Distributor. Distribution clean up: <distribution database name> Removes old transaction information from the distribution database. The job also checks whether all Subscribers received each record. Based on the result of that check and the replication retention settings, the job then determines which records to delete from the distribution database. In addition, the job disables subscriptions that failed to read the transaction information in time. The job also regularly refreshes the statistics on the tables in the distribution database. SQL Server creates one job of this type for each distribution database on the Distributor.
173
Chapter 8: SQL Server Agent Jobs for Transactional Replication Expired subscription clean up Removes subscriptions that fail to connect to the Subscriber within the publication retention period. This job runs on the Distributor as well as on the Publisher. SQL Server creates one instance of this job on each server. Reinitialize subscriptions having data validation failures Identies subscriptions with data validation errors and sets them up for re-initialization. You can use data validation to verify data consistency between the Publisher and Subscriber. For more information, see the topic, Validating Replicated Data in SQL Server Books Online. Replication agents checkup Monitors the replication agents and creates an entry in the Windows Event Log if any replication agent fails to report its status in the distribution database. Replication monitoring refresher for <distribution database name> Used by the replication monitor to refresh cached queries.
Remote distribution
When you congure remote distribution on a Publisher, replication setup creates one additional SQL Server Agent job to the Publisher, as shown in Figure 8-3.
Figure 8-3:
174
Chapter 8: SQL Server Agent Jobs for Transactional Replication The Expired subscription clean up job is responsible for removing the Publisher's metadata of expired subscriptions.
Publication
When you create a publication, SQL Server creates two jobs on the Distributor, but none on the Publisher, as you can see in Figure 8-4. Remember that SQL1\S12A is the Distributor and SQL2\S12A the Publisher.
Figure 8-4:
175
Chapter 8: SQL Server Agent Jobs for Transactional Replication The two publication-related jobs are SQL2\S12A-ReplA-2 and SQL2\S12A-ReplAMySecondPublication-2. They run the Log Reader Agent and the Snapshot Agent, respectively. You can tell which SQL Server Agent job runs which replication agent by referring to the Category column in the Job Activity Monitor. Remember, the Snapshot Agent is used to prepare the rst synchronization for each Subscriber. It copies all the schema information and all the data of the published objects into the snapshot folder. The Log Reader Agent is responsible to read the log le of the published database and copy all the data necessary to reproduce the object or data changes in the subscription database. It stores that information in the distribution database.
Push subscription
When you congure a push subscription, SQL Server creates a single SQL Server Agent job on the Distributor. The job runs the Distribution Agent. If you refer to Figure 8-5, you'll see that a new job, SQL2\S12A-ReplA-MyFirstPublication-SQL3\S12A-5, has been created on SQL1\S12A, which is our Distributor.
Figure 8-5:
176
Chapter 8: SQL Server Agent Jobs for Transactional Replication Figure 8-6 reveals that there are no additional jobs on either the Publisher or the Subscriber.
Figure 8-6:
As you can see, in the push subscription model all three replication agents live on the Distributor.
177
Pull subscription
When you congure a pull subscription, SQL Server again creates only a single SQL Server Agent job to run the Distribution Agent, but this time it's located on the Subscriber. Figure 8-7 shows the Job Activity Monitor for the Distributor (SQL1\S12A) and the Subscriber (SQL3\S12A). In this case, the name of the job is rather long: SQL2\S12A-ReplA-MySecondPublication-SQL3\ S12A-ReplB-CCEFBC29-C803-4A32-B743-FF86A59071BF.
Figure 8-7:
178
Chapter 8: SQL Server Agent Jobs for Transactional Replication Again, if you want to identify which SQL Server Agent job is associated with which replication agent, check the Category column.
Summary
In this chapter we discussed all the dierent SQL Server Agent jobs that are responsible for executing the replication agents as well as performing other maintenance tasks. We discovered when each job is created during the replication setup process and how to tell what each job's purpose is. This chapter closes the section on transactional replication. The next few chapters will walk you through everything you need to know about merge replication.
179
180
Chapter 9: Merge Replication the Replication Agents A merge replication setup looks a little dierent. It includes the following components: Snapshot Agent Triggers, tables, and views Merge Agent. The Snapshot Agent used in merge replication plays the same role as in transactional replication: it creates a snapshot of the data in the publication database, which is required to initialize or reinitialize a Subscriber. In merge replication, the role that the Log Reader Agent lls in transactional replication is taken by a set of triggers, tables, and views. These objects are added to each subscription database as well as to the publication database. The Merge Agent is comparable to the Distribution Agent in transactional replication. It applies the collected changes to the Subscriber. Because merge replication is bi-directional, the Merge Agent also applies changes to the Publisher as required. Figure 9-1 provides an overview of how these components work together.
181
Figure 9-1:
The arrows in Figure 9-1 show how the replication agents work with the data. The arrows reect the direction of the data ow; the green arrows indicate read access, whereas the red arrows indicate write access. The Merge Agent lives on either the Distributor or the Subscriber, depending on the subscription model. Let's look a little closer at each of these components to better understand how they work.
182
Snapshot Agent
As in transactional replication, merge replication uses the Snapshot Agent to generate a snapshot of the data in the publication database. Merge replication then uses the snapshot to initialize the subscription database. As in transactional replication, there are other ways to execute the initial synchronization. However, using the Snapshot Agent is certainly the most convenient way. Compared to transactional replication, there is one important dierence in how merge replication uses the Snapshot Agent. In transactional replication, the Snapshot Agent uses concurrent processing, which means it doesn't take any extended locks on the published articles. This technique relies on markers written to the database log during the snapshot generation. The Log Reader Agent picks up these markers, and the Distribution Agent then uses the markers to gure out which changes still need to be applied to the Subscriber and which changes were already picked up by the Snapshot Agent. (See Chapter 4 for more details about how this technique works.) Because merge replication does not use the Log Reader Agent, it cannot use these markers and concurrent snapshot processing is therefore not an option. As a result, the Snapshot Agent takes a lock on all published tables during a portion of the time it takes to generate the snapshot. This ensures transactional consistency between the publication and subscription databases. This description is a stark oversimplication of what is actually going on during snapshot creation. Most of the locks are not actually taken on the published tables. Instead, they're taken on the metadata tables created by merge replication to hold the information about data changes. Even so, the locks still block other transactions trying to write to the published tables because those transactions would re the merge replication triggers that write to the metadata tables. However, those locks do not interact with other reading transactions.
183
Chapter 9: Merge Replication the Replication Agents In addition, the length that each lock is taken has nothing to do with the amount of data in the published tables. Instead, it depends on the amount of data in the metadata tables, which is directly related to the amount of changes in the published tables since the last synchronization. Because of this, the Snapshot Agent is able to hold on to the locks for a shorter time in most cases. SQL Server Books Online gives a little more insight into this process, although it's not too detailed about it either. The important point to take away is that the published tables cannot be updated during the time those locks are held. Processes attempting to update any of the published tables (or to change non-table articles) are therefore going to be blocked. Because of this locking behavior, you should try to schedule the snapshot generation to run during o-peak hours. Chapter 10 explains how to do this. For each publication, SQL Server creates a SQL Server Agent job to execute the Snapshot Agent. Replication names these jobs based on the following pattern: <Server>-<Publication Database>-<Publication>-<number> If you need to generate a new snapshot, you can manually start the Snapshot Agent job for the publication, or you can schedule the job to run at a later time.
184
Chapter 9: Merge Replication the Replication Agents Replication denes three triggers on every published table. The triggers conform to the following naming convention: MSmerge_???_FA62745126C846858453EEF185F94618 The long hexadecimal number at the end of the name is the internal article identier. The question marks (???) serve as a placeholder for one of the following three values: del (for delete trigger) ins (for insert trigger) upd (for update trigger). These triggers are responsible for recording every change that is applied to the data in the published tables. Replication also creates the following database triggers to capture any schema changes to the published articles: MSmerge_tr_alterschemaonly MSmerge_tr_altertable MSmerge_tr_altertrigger MSmerge_tr_alterview The changes recorded by the triggers are not applied to the Subscribers right away. Instead, data that can be used to identify which records and columns changed is stored in replication metadata tables in the database in which the change happened. The names of all these tables begin with MSmerge_. Replication also creates several system views that follow the same naming pattern. These views are used by the internal merge replication processes. For more information about the triggers, tables, and views specic to merge replication, refer to SQL Server Books Online. 185
Merge Agent
The Merge Agent uses the information recorded by the database triggers to synchronize the changes between the Publisher and all its Subscribers. The Merge Agent, like the other replication agents, is an autonomous program separate from the SQL Server service. By default, SQL Server creates a SQL Server Agent job for each subscription to execute the Merge Agent. The job runs either on the Distributor (for push subscriptions) or on the Subscriber (for pull subscriptions). The push subscription jobs conform to the following naming convention: <Publisher>-<Publication Database>-<Publication>-<Subscriber><number> The naming convention for pull subscription jobs looks a little dierent: <Publisher>-<Publication Database>-<Publication>-<Subscriber><Subscription Database>-<number> In both cases, the <number> placeholder represents a number, usually a small one, used to prevent name collisions.
186
Summary
This chapter introduced the dierent components that support the merge replication process and showed how those components interact to make merge replication work. We talked about the Snapshot Agent and how it must take table locks to prevent changes to the underlying data while it generates the snapshot. As you've seen, there is a significant dierence between the initialization of a merge replication setup and a transactional replication setup. We also talked about the Merge Agent and the dierent triggers that it relies on to record changes to the data in the replicated tables or changes to the replicated objects themselves. In the chapters to follow, you'll learn how to set up merge replication so you can see for yourself the merge components in action.
187
188
Chapter 10: Merge Replication the Publication because there needs to be a way to identify records that changed between synchronizations. Chapter 9 explains how this process works. In this chapter, you'll learn how to set up a merge publication and how to add articles to that publication. We'll also cover where you select the conict resolver for each article and how to decide if that article is going to be synchronized bi-directionally or one way only. To perform the exercises in this chapter, you need a database that contains objects you can replicate. We'll be using the ReplM database, which you can create by running the script in Listing 10-1.
USE MASTER; GO EXECUTE AS LOGIN = 'SA'; GO CREATE DATABASE ReplM; GO USE ReplM; GO CREATE TABLE dbo.Tbl1( Id INT IDENTITY(1,1) PRIMARY KEY, Data INT CONSTRAINT Tbl1_Data_Dflt DEFAULT CHECKSUM(NEWID()), Data2 INT CONSTRAINT Tbl1_Data2_Dflt DEFAULT CHECKSUM(NEWID()), Data3 INT CONSTRAINT Tbl1_Data3_Dflt DEFAULT CHECKSUM(NEWID()) ); GO INSERT INTO dbo.Tbl1 DEFAULT VALUES; GO 1000 GO CREATE TABLE dbo.Tbl2( Id INT IDENTITY(1,1) PRIMARY KEY, Data INT CONSTRAINT Tbl2_Data_Dflt DEFAULT CHECKSUM(NEWID()), Data2 INT CONSTRAINT Tbl2_Data2_Dflt DEFAULT CHECKSUM(NEWID()), Data3 INT CONSTRAINT Tbl2_Data3_Dflt DEFAULT CHECKSUM(NEWID()) );
189
190
191
Figure 10-1:
3. In the Publisher Properties dialog box, go to the Publication Databases page, and select the Merge check box in the row associated with your database. Figure 10-2 shows the Merge check box selected for the ReplM database, the database we created at the beginning of this chapter.
192
Figure 10-2:
4. After you have made your selection, click OK to close the Publisher Properties dialog box. Now that you've enabled the database for merge replication, any member of the db_owner role associated with that database can dene a publication on it.
193
Creating a Publication
You're now ready to create a merge publication. The rest of the chapter walks you through the steps necessary to add a publication to the ReplM database. For all these steps, we'll use the New Publication Wizard. The wizard is the simplest way to create a publication, although there are still a number of steps that must be performed. For that reason, we've grouped the steps into the following exercises: adding a publication to the publication database, adding articles to that publication, conguring the Snapshot Agent and its security, and nalizing your publication. After performing these exercises, you'll have a working publication that is ready to be subscribed to.
Adding a publication
After launching the New Publication Wizard, your rst steps will be to create the initial publication in your publication database and then to select Merge Replication as its type. The following steps walk you through that process: 1. In Object Explorer, expand the Replication folder of the SQL Server instance that holds the database you want to publish. (This is the same database you enabled in the previous task.) 2. Right-click the Local Publications subfolder, and click New Publication, as shown in Figure 10-3.
194
Figure 10-3:
3. If the rst page of the New Publication Wizard is the Welcome page, click Next to advance to the Publication Database page, shown in Figure 10-4. If you want, you can also select the option to disable the Welcome page so it doesn't appear when you use the wizard in the future.
195
4. On the Publication Database page, select the database in which you want to dene your publication. For the exercises in this chapter, we're using the ReplM database, the same database we enabled for merge replication in the previous task.
196
Chapter 10: Merge Replication the Publication 5. Click Next to advance to the Publication Type page, shown in Figure 10-5. This is where we select the publication type.
Figure 10-5:
Up to this point, the steps for creating a merge publication have been very similar to those used to create a transactional publication. That, however, will change as we continue working through the wizard.
197
Chapter 10: Merge Replication the Publication 6. Select the Merge publication option on the Publication Type page, and then click Next to advance to the Subscriber Types page, shown in Figure 10-6.
Figure 10-6: Selecting the Subscriber types that can use your publication.
On the Subscriber Types page, you select one or more SQL Server versions that the publication will support. Any Subscriber that connects to this publication must be running one of these versions. Note, however, that any selection other than SQL Server 2008 will cause the publication to run with reduced functionality. (SQL Server 2012 did not introduce any new functionality.) For details about these restrictions, refer to SQL Server Books Online. 7. Select one or more Subscriber types. For these exercises, we've selected only the SQL Server 2008 or later option. If possible, you should try to follow the same strategy so you can benet from all the functionality now available to merge replication. 198
Chapter 10: Merge Replication the Publication Note that, if your publication database already contains a merge publication, the Subscriber Types page might show a reduced number of options. That's because, with few exceptions, all merge publications in the same database need to use the same Subscriber types, and if a merge publication has already been dened, that publication's conguration settings will determine which options are available here. 8. Click Next to advance to the Articles page, which is covered in the next section.
Chapter 10: Merge Replication the Publication To add articles to your publication, take the following steps: 1. If you have not already done so, advance to the Articles page in the New Publication Wizard. The Articles page should look similar to the one shown in Figure 10-7.
On the Articles page, you can select tables, stored procedures, views, indexed views, and user-dened functions to be replicated to your Subscribers. For now, select only the dbo.Tbl1 table. 2. As with transactional replication, you can replicate a table in its entirety or you can select individual columns to be replicated (vertical lter). For this exercise, we'll include a couple of columns from the dbo.Tbl2 table, so expand the column list for that table by clicking the plus sign next to the table name. Then select columns Id and Data2. Figure 10-8 shows the selected columns on the Articles page. 200
When you highlight a table that is selected as an article, the Highlighted table is download-only option appears beneath the Article Properties button. If you select this option, changes to the table's data are not permitted on the Subscriber. You should select this option for any table that contains data that should not be changed on the Subscriber(s). This selection causes signicantly less data to be collected on the Publisher because there is no need to maintain data to help resolve conicts. (A conict occurs when a row is changed in more than one place at a time. If the Publisher is the only place where data changes can be made, conicts cannot happen. See Chapter 12 for details on conicts.) Not permitting changes to the replication data on the Subscriber side can therefore have a dramatic impact on performance and space requirements on the Publisher.
201
Chapter 10: Merge Replication the Publication You can also set this option in the article's properties. To access the properties, ensure that the table article is selected in the Objects to publish list, click the Article Properties button, and then click Set Properties of Highlighted Table Article. This launches the Article Properties dialog box, shown in Figure 10-9.
202
Chapter 10: Merge Replication the Publication The article property that corresponds to the Highlighted table is download-only option is Synchronization direction. The property supports the following three settings: Bi-directional Download-only to Subscriber, allow Subscriber changes Download-only to Subscriber, prohibit Subscriber changes. The Highlighted table is download-only option essentially lets you toggle between the rst and the last setting. If you were to manually select the second setting, changes on the Subscriber would be allowed, but would not be transferred back to the Publisher and might be overwritten. The fact that this option has a single check box alternative on the Articles page of the wizard shows the importance of selecting the appropriate setting for your articles. Of course, there are other important properties you can also congure on an article. As you can see in Figure 10-9, the Article Properties dialog box includes numerous settings for an article in a merge publication, just as it does for an article in a transactional publication. (For a complete list of the available options for each object type, refer to SQL Server Books Online.) But notice that, for a merge article, the dialog box also includes the Resolver tab, which is not available for transactional publications. Here, you can specify how conicts should be handled for each article by selecting a resolver, as shown in Figure 10-10. (Resolvers are covered in Chapter 12.)
203
3. Click the Cancel button to close the Article Properties dialog box and return to the Articles page of the New Publication Wizard. On the Articles page make sure that the Highlighted table is download-only option is checked for dbo.Tbl2, as shown in Figure 10-8, and then click Next. 4. The next page to appear in the New Publication Wizard is the Article Issues page, which provides you with any warnings that might apply to your publication. While there are several possible warnings that can be displayed here, you're most likely to see the one shown in Figure 10-11 when you're setting up a merge publication.
204
The warning tells you that merge replication requires each replicated table to include a uniqueidentifier column congured with the ROWGUIDCOL property and a unique index. If such a column does not exist, SQL Server will automatically add it when the rst snapshot is generated. That change can potentially break existing code accessing those tables. It will also increase the size of the table by at least 16 bytes per row.
205
5. For this exercise, we'll accept the default behavior and let SQL Server add the necessary columns. Click Next to advance to the Filter Table Rows page. 6. On the Filter Table Rows page (shown in Figure 10-12), you can add row level lters to your table articles. The page appears only if you've added at least one table article to the publication.
Figure 10-12: The Filter Table Rows page of the New Publication Wizard.
7. Click the Add button, and then click Add Filter to open the Add Filter dialog box. 206
Chapter 10: Merge Replication the Publication 8. In the Add Filter dialog box, select Tbl2 (dbo) from the Select the table to lter drop-down list. You can then add a row lter, in the Filter statement windows. A row lter, or horizontal lter, looks like a SELECT statement that includes a WHERE clause, as shown in Figure 10-13. However, you can edit only the code after the WHERE keyword.
9. The purpose of the column list on the left side of the Add Filter dialog box is to help you with remembering (and typing) the column names of the current article. The selected column does not aect the functionality of the lter. 10. Complete the query so it matches what is shown in Figure 10-13, and then click OK . This lter will cause only rows that have an even number value in the Id column to get replicated. 207
Chapter 10: Merge Replication the Publication 11. When you're returned to the Filter Table Rows page, it should now show that there is a lter dened for the table dbo.Tbl2, as shown in Figure 10-14.
12. Click Next to advance to the Snapshot Agent section of the wizard, which we cover in the next section.
208
209
Chapter 10: Merge Replication the Publication The following steps explain how to congure the Snapshot Agent: 1. If necessary, advance to the Snapshot Agent page of the New Publication Wizard. As you can see in Figure 10-15, you can select whether a snapshot should be created immediately, and you can schedule future snapshots. By default, both options are selected.
2. Leave the default schedule settings (immediate, and every 14 days), and click Next to advance to the Agent Security page, shown in Figure 10-16.
210
3. Click the Security Settings button to open the Snapshot Agent Security dialog box, shown in Figure 10-17.
211
4. Type the Windows account that the snapshot should run under. For these exercises, we're using the domain\SQL2_S12A_Snapshot account. 5. In the Connect to the Publisher section, select the option By impersonating the process account. Note that, as with transactional replication, instead of using impersonation you might have to specify a SQL Server login in some cases, such as when the Publisher and Distributor are in dierent domains. 6. Click OK to close the Snapshot Agent Security dialog box. You're returned to the Agent Security page of the New Publication Wizard. 7. Click Next to continue to the nal section of the New Publication Wizard, which we cover in the following few paragraphs.
212
Figure 10-18: Choosing the action to be taken at the end of the wizard.
213
Chapter 10: Merge Replication the Publication 2. On the Complete the Wizard page, type a name for your publication. In this case, we've used MyFirstMergePublication, as shown in Figure 10-19.
3. Review the actions listed on the Complete the Wizard page, and then click Finish. The Creating Publication page appears and provides details about the publication creation process, as shown in Figure 10-20.
214
4. Before long, the Creating Publication page should show the steps executed and whether they were successful. If everything succeeded, click Close to close the wizard. 5. At this point, you have successfully created a merge publication. The next step is to create a subscription for this publication, which is the topic of Chapter 11.
215
Potential Problems
As with transactional replication, there are a lot of things that can go wrong when setting up merge replication. The most common problem to occur in merge replication, as well as in transactional replication, is that one of the specied accounts or logins does not have the appropriate permissions. (If you followed the example, you have specied only one account so far, the one used for the Snapshot Agent.) If you run into problems, make sure all accounts used have the appropriate rights granted. For details on how to troubleshoot problems, review the Potential Problems section in Chapter 5, which covers problems you might run into when setting up a transactional publication. Most of the suggestions there can be helpful for merge replication as well. For more in-depth troubleshooting help, check out Chapter 14.
Summary
This chapter demonstrated how to create a publication for merge replication and how to add articles to that publication. The chapter listed the dierent types of articles and discussed their synchronization options. It also pointed out the dierences from setting up a publication for transactional replication. As with transactional replication, after doing all the work to set up a merge publication, there's not a lot to show for your eorts. To see something happening, you also need at least one subscription. In the next chapter, you'll learn how to set up a subscription to support merge replication.
216
Setting up a Subscription
To set up a subscription to support merge replication, we must perform a number of steps, such as selecting the Publisher, choosing the subscription type and subscription database, and conguring security. For most of these steps, we'll use the New Subscription Wizard, which walks us through the process of setting up the subscription. In addition to running the wizard, we'll need to take a few other steps to set up our subscription, such as setting up the Publication Access List (PAL) and conguring retention. After we've completed all these steps, we'll have a working merge replication setup with a single Subscriber and a single subscription. The permissions you need to set up a merge subscription are very similar to the ones needed for a transactional subscription. In this chapter, we're going to create a pull subscription, as that is the more common scenario for merge replication. Therefore, we assume for the rest of the chapter that you have at least db_owner level permissions in the subscription database and that you are a member of the PAL for the publication we created in the previous chapter. For more details on how to add your account to the PAL, refer back to Chapter 6. For the permissions required to set up a push merge subscription, refer to SQL Server Books Online. 217
Figure 11-1:
218
Chapter 11: Merge Replication the Subscription 3. When the New Subscription Wizard appears, advance to the Publication page, shown in Figure 11-2. This page is where you identify the Publisher, the publication database, and the publication.
Figure 11-2:
4. At the top of the Publication page is the Publisher drop-down list, where you select the Publisher. The list contains the name of the SQL Server instance you're currently connected to (the Subscriber), along with an option for nding a SQL Server Publisher and an option for nding an Oracle Publisher. 5. Note that the SQL Server instance shown in Figure 11-2, SQL3\S12A, is the instance that I've designated on my system as the Subscriber. You should see the instance you've set up as your Subscriber listed in the drop-down list.
219
Chapter 11: Merge Replication the Subscription 6. From the Publisher drop-down list, click the Find SQL Server Publisher option. This opens a standard Connect to Server dialog box, where you can select your Publisher, as shown in Figure 11-3.
Figure 11-3:
7. Select your Publisher, provide the necessary authentication information, and then click Connect. You're returned to the Publication page of the New Subscription Wizard. The Publisher's publication database and any congured publications associated with that database now appear in the Databases and publications window, as shown in Figure 11-4.
220
Figure 11-4:
As you can see in Figure 11-4, the SQL Server instance that I've congured as my Publisher is SQL2\S12A. The publication database associated with that Publisher is ReplM, and the publication associated with that database is MyFirstMergePublication. 8. Expand the folder associated with your publication database, and then select the merge publication you created in Chapter 10. Click Next to advance to the Merge Agent Location page of the wizard, which we cover in the next section.
221
222
Figure 11-5:
2. Select the option, Run each agent at its Subscriber (pull subscriptions). 3. Note that the subscription type you select here will result in minor dierences in some of the wizard pages that follow the Merge Agent Location page. However, because the dierences are so minor, we won't be covering them here. 4. Click Next to advance to the Subscribers page of the wizard, which we cover in the following section.
223
Figure 11-6:
224
Chapter 11: Merge Replication the Subscription 2. When the Subscribers page appears, the SQL Server instance from which you launched the New Subscription Wizard is listed in the Subscribers and subscription databases grid. On my system this is the SQL3\S12A instance. Ensure that the check box next to the Subscriber name is selected. 3. The Subscription Database drop-down list associated with the Subscriber lists all databases on the selected instance and allows you to select your subscription database. If you need to create a new database, you can do so by selecting the New database option. That option launches the New Database Wizard, which walks you through the process of creating the database. 4. When you pick an existing database, be careful to pick the correct one. Replication's initialization step drops and re-creates all objects that are part of the publication in the subscription database. If you pick the wrong database and that database contains objects with the same names as replicated objects, the objects in the target database are dropped. There is no warning about this anywhere in the process. 5. After selecting your subscription database, click Next to advance to the Merge Agent Security page. We cover security in the next section.
Conguring security
The next step in setting up our subscription is to congure Merge Agent security, which involves selecting the accounts and logins that replication will use to connect to the various databases participating in our replication setup. As always, it's a best practice to use dierent accounts for each Merge Agent and grant only the required permissions to each account. To congure Merge Agent security, we'll use the Merge Agent Security page of the New Subscription Wizard. Each Subscriber that you selected in the previous step is listed on this page. For each Subscriber, you must select the accounts that the Merge Agent should use. In this case, because we selected only one Subscriber, we need to congure security for that one only. 225
Chapter 11: Merge Replication the Subscription The following steps walk you through the process of setting up Merge Agent security for your Subscriber: 1. If you haven't already done so, advance to the Merge Agent Security page of the New Subscription Wizard, shown in Figure 11-7. The page lets you to specify the account used to run the Merge Agent associated with each Subscriber and the accounts used by that agent to connect to the Publisher, Distributor, and Subscriber.
Figure 11-7:
2. In the Subscription properties grid you'll nd the Subscriber you selected on the previous pages. (Again, my Subscriber is SQL3\S12A.) 3. Initially, no accounts are associated with the Subscriber's Merge Agent. To add the accounts, click the ellipsis button at the end of the row to launch the Merge Agent Security dialog box. 226
Chapter 11: Merge Replication the Subscription 4. The Merge Agent Security dialog box lets you specify the accounts used to run the Merge Agent and connect to the various SQL Server instances, as shown in Figure 11-8. Note that the gure shows the dialog box as it appears for a pull subscription. The dialog box is slightly dierent for a push subscription. However, because the dierences are minor, we'll stick with only the version shown here.
Figure 11-8:
227
Chapter 11: Merge Replication the Subscription 5. Similar to transactional replication, there's an overwhelming amount of connection information needed to set up merge replication. Chapter 9 provides more details about the inner workings of merge replication and sheds light on the various connections. You can refer back to that chapter for more information. 6. Near the top of the Merge Agent Security dialog box, provide a Windows account for the Merge Agent to run under. Remember, in pull subscriptions the Merge Agent runs on the Subscriber, so this same Windows account will also be used to connect to the SQL Server instance designated as the Subscriber. 7. In the Connect to the Publisher and Distributor section, select the option By impersonating the process account. This is the default and usually the best choice. Using a SQL Server login here is appropriate only in rare circumstances. 8. In the Connect to the Subscriber section, only the option By impersonating the process account is available because we're setting up a pull subscription. 9. Click OK to return the New Subscription Wizard. The Merge Agent Security page should now display account information next to your Subscriber, as shown in Figure 11-9. 10. For now, we won't go any further with the New Subscription Wizard. But don't close or cancel it. We'll return to it as soon as we set up the necessary permissions on our accounts.
228
Figure 11-9:
Setting up permissions
The account you select to run the Merge Agent must be congured as follows: be a member of the db_owner xed database role in the subscription database be a member of the PAL for the publication have read permissions to the snapshot share. If you selected a SQL login to connect to the Publisher and Distributor during the previous step, that login must be added to the PAL instead of the Merge Agent account. 229
Chapter 11: Merge Replication the Subscription Remember, to be able to add an account to the PAL, the account must be congured as follows: be a login on the Publisher be a login on the Distributor have access to the publication database. You access and congure the PAL through the publication's properties. Chapter 6 describes in more detail how to work with the PAL. Once a login is added to the PAL, the user associated with it automatically becomes a member of several additional database roles in the publication database. Do not manually remove the user from those roles. If you selected the push subscription topology, the account used to connect to the Distributor must additionally be a member of the db_owner xed database role in the distribution database.
Chapter 11: Merge Replication the Subscription For this exercise, we'll stick with on-demand synchronization. The following steps describe how to set up your subscription's synchronization to run on demand only: 1. If you haven't already done so, advance to the Synchronization Schedule page of the New Subscription Wizard, as shown in Figure 11-10.
2. Select the Run on demand only option from the Agent Schedule drop-down list associated with your Subscriber. 3. Note that, if you want to schedule the synchronization, you should select the Dene schedule option instead. This opens a standard SQL Server Agent New Job Schedule dialog box in which you can set up a schedule. We won't be going into this option any further. 4. Click Next to advance to the Initialize Subscriptions page of the New Subscription Wizard, which we cover in the next section. 231
232
3. For this exercise, we'll synchronize our subscription immediately. In the Initialize When column of the Subscription properties grid, select Immediately from the drop-down list associated with your Subscriber. 4. Click Next to advance to the Subscription Type page of the New Subscription Wizard. We cover subscription types in the next section.
233
234
Chapter 11: Merge Replication the Subscription For our example, we'll set up the subscription as a client because we won't be creating a hierarchy of Subscribers. The following steps walk you through the process of specifying the subscription type: 1. If you haven't already done so, advance to the Subscription Type page of the New Subscription Wizard, as shown in Figure 11-12.
2. Select Client from the Subscription Type drop-down list associated with your Subscriber. Because you cannot specify a priority for a client, the Priority for Conict Resolution text box is read only. If you had selected Server, you would be able to specify the priority for this subscription here. 3. Click Next to advance to the Wizard Actions page of the New Subscription Wizard.
235
Figure 11-13: Choosing what happens when you nish running the wizard.
2. Select the Create the subscription(s) option, and then click Next.
236
Chapter 11: Merge Replication the Subscription 3. On the Complete the Wizard page you get a chance to review all your settings, as shown in Figure 11-14.
4. Once you're satised that the settings look correct, click Finish. 5. The Creating Subscription(s) page, shown in Figure 11-15, appears and informs us of the wizard's progress as it creates the subscription.
237
6. If everything succeeds, click Close to close the New Subscription Wizard. Your subscription should now be created and about ready to go. However, before you start synchronizing your subscription, there's one more step you need to take: conguring the subscription's retention settings.
238
239
Chapter 11: Merge Replication the Subscription The following steps describe how to set up the retention period on your subscription: 1. In SSMS, connect to the SQL Server instance that you've set up as your Publisher. 2. In Object Explorer, expand the Replication folder for that instance and then expand the Local Publications subfolder. 3. Right-click your publication and select Properties. This launches the Publication Properties dialog box. The dialog box opens to the General page, as shown in Figure 11-16. The page contains the Subscription expiration section, which is where you can select the length of the retention period. You can also select a unit of time, such as minutes, hours, or days. The default is 14 days. 4. For this exercise, we'll stick with the default setting, so click Cancel to close the Publication Properties dialog box.
240
241
3. When you click the View Synchronization Status option, the View Synchronization Status dialog box appears. The dialog box should appear similar to the one in Figure 11-18, except that it will show the SQL Server instances and databases you've congured in your own replication setup.
242
The View Synchronization Status dialog box includes several options related to synchronizations: Start: run the Merge Agent job that performs the synchronization. Stop: stop a Merge Agent job that's currently synchronizing a subscription. View Job History: view the history of the most recent Merge Agent job executions. Close: close the View Synchronization Status dialog box. 4. Click Start to execute the synchronization of your subscription. The dialog box will show progress information. 5. You can click Close at any time to close the dialog box. You don't have to wait for the synchronization to nish, as it will continue in the background.
243
Summary
In this chapter, you learned how to set up a subscription on a merge replication Subscriber. First, you connected to the Publisher and selected the publication that the subscription would connect to. Next, you selected the Merge Agent location and specied the subscription database. You then congured the Merge Agent security. Finally, you learned how to set up the synchronization schedule, initialize the subscription database, and select the subscription type. The chapter also included information about push and pull subscriptions. Plus, you learned how to congure your subscription's retention and how to synchronize the subscription manually. If you followed the steps in this chapter's exercises, you should have a working merge replication setup. You can test that setup by changing data on the Publisher as well as the Subscriber and see how those changes are replicated with each synchronization. Keep in mind that you need to synchronize manually before you can see the data changes on the other side of your replication setup because we did not create a schedule on the Synchronization Schedule page. In Chapter 12 you'll be introduced to conict resolvers and you'll learn how they automatically handle conicts in merge replication.
244
245
Conict Types
The most common cause for a conict is that a row is changed on one node (Publisher or Subscriber) and then changed on another node, as in the example above. This type of conict is called an update-update conict. However, if a row is updated on one node, but deleted on another node, the resulting conict is called an update-delete conict. A conict can also occur if a change that is applied to one node cannot be applied to another node. For example, a successful update on one Subscriber might result in a constraint violation on another Subscriber. This type of conict is called a failed-change conict. Failed-change conicts can occur due to a number of reasons, such as mismatched constraint denitions or mismatched triggers or identity columns being used without automated identity management. For a complete list of reasons why failed-change conicts can occur, refer to SQL Server Books Online. Now let's look at how to congure merge replication to handle various types of conicts.
246
Chapter 12: Merge Replication Conicts The two options are available through the Tracking level property associated with each table article. You can access the property through the Article Properties dialog box for that article, as shown in Figure 12-1.
Figure 12-1:
247
Chapter 12: Merge Replication Conicts While creating the publication, you can access the Article Properties dialog box from the Articles page of the New Publication Wizard. This is the same dialog we used in Chapter 10 to change the Synchronization direction setting. The following steps describe how to change the property or check its current value in an existing publication: 1. In SQL Server Management Studio (SSMS), connect to the Publisher in Object Explorer. 2. Expand the Replication folder and its Local Publications subfolder. 3. Right-click your publication and select Properties. 4. When the Publication Properties dialog box appears, go to the Articles page. 5. From the list of articles, select the table article you want to change, and then click the Article Properties button. 6. When a drop-down list appears, select Set Properties of Highlighted Table Article. This opens the Article Properties dialog box shown in Figure 12-1. Here you can view the current setting for the tracking-level property or change its value. 7. Click OK twice to close both dialog boxes. Now that you know how to access the tracking level property, let's take a closer look at the dierences between row-level and column-level tracking.
Row-level tracking
By default, merge replication uses row-level tracking because it requires the least amount of resources. If a row gets updated, the merge triggers record the value from the row's UNIQUEIDENTIFIER column. The UNIQUEIDENTIFIER column identies a row across the Publisher and all Subscribers, even if all other column values have changed. 248
Chapter 12: Merge Replication Conicts During the synchronization of two nodes, the Merge Agent checks if the same row has been changed on both sides. If that has occurred, the Merge Agent records that the row has a conict and resolves the conict according to the conict resolution rules that were set for the article. How to inuence those rules and how to review conicts are described in the Conict Resolvers and Reviewing Conicts sections, below. Row-level tracking requires only the UNIQUEIDENTIFIER value for each changed row to be stored in the change log. Therefore, row-level tracking uses only a minimal amount of storage space. However, this process potentially marks non-conicting changes as conicts. For example, assume Person A updates a customer's phone number on the Publisher and Person B updates the email address of that same customer on the Subscriber. Those two changes are not in conict with each other. However, if both values are stored in the same row of the Customer table, row-level tracking will mark those changes as a conict because both changes aected the same row.
Column-level tracking
Column-level tracking does not consider changes to two dierent columns in the same row as a conict. However, to be able to make the distinction, this form of tracking requires more resources. In addition to recording the UNIQUEIDENTIFIER value for each changed row, column-level tracking also tracks the specic columns that have changed. Consider again the scenario described above, in which one person updates the customer's phone number and another person updates that customer's email address. Because column-level tracking tracks the column information, the Merge Agent can correctly identify this situation as a non-conict. Only if the same column in the same row changes at dierent sites, does the Merge Agent record a conict and handle it according to the conict resolution rules.
249
Conict Resolvers
When a conict is detected, the Merge Agent employs a conict resolver to determine which version of the changes is kept. You can think of a conict resolver as a Merge Agent plug-in whose specic purpose is to deal with conicts. When setting up merge replication, you can choose which conict resolver is used on a per article basis. Chapter 10 briey describes how to select a resolver in the Article Properties dialog box, which you can open from within the New Publication Wizard. As you saw in the previous section, you can also open the dialog box from within SSMS for an existing publication. Figure 12-2 shows the dialog box, opened to the Resolver tab.
Figure 12-2:
250
Chapter 12: Merge Replication Conicts In the Article Properties dialog box, you can choose to use either the default resolver or any other resolver that has been registered with the Distributor. Figure 12-2 shows all the conict resolvers that come pre-installed with SQL Server. A resolver decides which version of the conicting data wins; that is, which version of the changes will be used on both nodes. For example, the resolver selected in Figure 12-2, Maximum Conict Resolver, bases its decision on the value of a single column. You can specify which column it uses by providing a column name in the Enter information needed by the resolver text box under the list of resolvers. In a conict situation, the side that has the larger value in this column wins the conict. This can be useful in a situation where updates can have dierent priorities. Suppose that Person A updates the phone number of a customer on one subscriber. Because the phone number is rarely used to contact customers, Person A sets the value in the update_priority column of that same row to 1. At the same time Person B changes the email of the same customer. Email is the main communication channel for the company, so Person B marks this change as important by setting the value in the priority column to 3. If merge replication is set up to resolve conicts based on the value in the update_priority column and also set up to use the Maximum Conict Resolver, the change to the email will win this conict situation, while the change to the phone number will be lost. The phone number change however will be copied into a conict table so you can review it at a later time. (In the Reviewing Conicts section, below, we discuss the conict table in more detail.) The resolver that is selected by default is aptly named the default resolver. It follows a fairly complex set of rules that are described in the following section.
251
252
Figure 12-3:
In a topology like this, you have to run several synchronization steps to get every change to every node. For example, suppose a user modies data on Node F. To distribute this change, Node F must rst sync with Node C. Then Node C must sync with Nodes A, G and H. Finally Node A must sync to Nodes B, D and E. If at that time a conict is detected between a change at Node D and the original change at Node F, D's change will win because of the higher priority. As a result, Node A now must sync again with B, C and E. After that, C must sync with all of its Subscribers. In this scenario, ve synchronization steps are required to fully synchronize this change. Keep this in mind when you design a complicated layout of merge replication participants. The greater the number of nodes involved, the more steps it takes to fully synchronize each one.
253
Chapter 12: Merge Replication Conicts For the rest of this section, we'll use the term full synchronization to mean a complete synchronization that includes all the steps necessary to get all nodes in sync. Table 12-1 shows which change survives a full synchronization if conicting changes occur on two nodes. The information in the table assumes that all articles use the default resolver and both changes occur before the rst synchronization step.
In short, the default resolver in merge replication adheres to the following synchronization rules: A change on the main Publisher always wins any conict. A change on a node with a client type subscription loses if a conicting change occurred on its direct Publisher before the synchronization. It's immaterial whether the conicting change to the Publisher was applied directly or through synchronization with another node.
254
Chapter 12: Merge Replication Conicts A change on a node with a client type subscription that was successfully synchronized with its direct Publisher without a conict will, at successive synchronization steps, be treated exactly as if the change had originated at that Publisher. If two conicting changes originate at two nodes with server type subscriptions, the change applied to the node with the higher priority wins, independent of the type, number, and priority of nodes between them, and independent of the order of the synchronization steps.
Other resolvers
Several predened resolvers are installed when you set up SQL Server, as you have seen in Figure 12-2. They range from date-dependent resolvers, to resolvers that use the maximum or minimum value of the conicting values, to those that build an average of the conicting values. See SQL Server Books Online for details on how to use these resolvers. There is also one special type of resolver in this list, the Stored Procedure Resolver. It allows you to supply a stored procedure that contains the necessary logic to determine which version wins. This is probably the easiest way to implement a customized resolver. For details on how to implement this type of resolver, I again have to refer you to SQL Server Books Online.
Custom resolvers
Above, I mentioned that resolvers can be thought of as plug-ins. The plug-in interface for resolvers is actually published, so you can write your own conict resolvers using C++. This way, you can really customize how merge replication conicts should be treated.
255
Chapter 12: Merge Replication Conicts After creating your own custom resolver, you must register it with the Distributor before it can be used. For details on how to create a custom resolver that uses the plug-in interface and how to register the resolver with a Distributor, check out SQL Server Books Online.
256
Chapter 12: Merge Replication Conicts The Windows Synchronization Manager is not part of SQL Server; instead it comes pre-installed on Windows desktop operating systems and can be installed on server operating systems. For details on how to make all this work, check out your Windows documentation and SQL Server Books Online.
Reviewing Conicts
The Merge Agent records all automatically resolved conicts. You can review them later and even change their outcome. The following steps describe how to review automatically resolved conicts: 1. First, we need a conict to work with. Execute an update statement against the same two rows in both the subscription and the publication databases. If you used the examples provided when setting up merge replication, you can use the following statement:
UPDATE dbo.Tbl1 SET Data2 = CHECKSUM(NEWID()) WHERE Id IN (13,42);
2. After executing the update in both databases, connect to the Subscriber in Object Explorer and expand the Replication folder and its Local Subscriptions subfolder. Right-click your subscription and then click View Subscription Status, as shown in Figure 12-4.
257
Figure 12-4:
3. In the Synchronization Status dialog box, click Start to synchronize the tables. This should result in two conicts, as shown in Figure 12-5.
258
Figure 12-5:
4. Click Close to dismiss the Synchronization Status dialog box. 5. In SSMS, open a new query window connected to the publication database and run the following query:
SELECT * FROM dbo.Tbl1 WHERE Id IN (13,42);
Leave the query results open for later review. 6. Use Object Explorer to connect to the Publisher, expand the Replication folder, and the Local Publications subfolder. 7. Right-click the publication and then click View Conicts, as shown in Figure 12-6.
259
Figure 12-6:
8. When the Select Conict Table dialog box appears, you can select the table for which you want to review the conicts. Only tables that encountered conicts are shown, together with the number of conicts for each of them. Because we created our two conicts in a single table, the dialog box will list only that table, as shown in Figure 12-7.
260
Figure 12-7:
9. Select Tbl1 and click OK . This opens the Replication Conict Viewer dialog box, shown in Figure 12-8. The Replication Conict Viewer dialog box is split into an upper pane and lower pane. The upper pane contains the list of all conicts that occurred on the selected table. The list species the conict loser, the type of conict, and when the conict was detected. When you select one of the conicts in this list, the bottom pane shows details about the column values of the conicting rows. It includes the values of the winner as well as the loser.
261
Figure 12-8:
10. Select the conict whose Id value equals 42 (probably be the second conict listed in the upper pane), and then click the Remove button. This will remove the conict from the list. Removing an entry like this will not change any data in the replicated tables. It just tells SQL Server that you accept the change. 11. In the upper pane, select the remaining conict, the one whose Id value equals 13, and then click the Submit Loser button at the bottom of the dialog box. This will tell SQL Server that you do not accept the automatic conict resolution and that you're submitting the prior loser of the conict as new winner. Submitting a new winner for a conict will remove the entry from the conict list and will update the Publisher to reect the new values. From there, the changes will be distributed to the other nodes during their next synchronization. 262
Chapter 12: Merge Replication Conicts 12. Close the Replication Conict Viewer dialog box. 13. Run the SELECT statement in Step 5 again, but in a new query window, also connected to the publication database. Compare the result to the results you received in Step 5. For Row 42, they should match. However for Row 13, you should see that the value in the Data2 column changed because we changed the outcome of that particular conict. At this point, you can close the query windows in Management Studio or even close Management Studio itself if you're nished with merge replication for now.
Summary
This chapter explained how merge replication handles synchronization conicts. We talked about the dierent types of conicts and conict resolvers. We also discussed dierent options for providing your own logic for conict resolution. In addition, we provided an in-depth look at how the default resolver works in a multi-tiered merge replication setup. Finally, we examined the capabilities of the merge replication conict viewer. This closes out the part of the book about merge replication. In the next two chapters, we will look at the Replication Monitor and learn a few ways to troubleshoot replication.
263
264
Figure 13-1:
When Replication Monitor opens, you'll see that the main screen is divided into two windows, as shown in Figure 13-2. The left window provides a hierarchical view of the publications associated with each Publisher currently being monitored. By default, the only Publisher listed is the one from which you launched Replication Monitor. On my system, that Publisher instance is SQL2\S12A.
265
Figure 13-2:
The information in the right-hand window shows details about the item selected in the left-hand window. For example, in Figure 13-2, because the Publisher is selected, the right-hand window shows details about the publications associated with that Publisher. 3. Click the My Publishers node or the Replication Monitor node in the left-hand window. The right-hand pane will display links to additional information about monitoring replication. You'll also nd a link for adding a Publisher to Replication Monitor. You do not need to take any other steps for this exercise. Leave Replication Monitor open, because we will start from here in the next exercise.
266
Removing a Publisher
In the left window of Replication Monitor, you can remove individual Publishers from the list. This does not change any data on the Publisher itself; it just stops showing information about this Publisher in Replication Monitor. You probably won't have to remove a Publisher very often, but I've included it here to demonstrate how it works and to set the stage for the next exercise. The following steps describe how to remove a Publisher from Replication Monitor: 1. Right-click the Publisher you want to remove, and then click Remove, as shown in Figure 13-3.
Figure 13-3:
2. Click Yes when prompted to conrm whether you want to remove the selected Publisher.
267
Chapter 13: Replication Monitor 3. Repeat the same steps for the My Publishers node. This is possible only if there are no more Publishers listed under this node. Note that the node is referred to as a group and is used to organize your Publishers. In the next exercise, you'll learn how to create a group. 4. After removing the Publisher and the My Publishers node, the Replication Monitor window will just show the Replication Monitor node on the left-hand window, and the information on the right-hand window, as shown in Figure 13-4.
268
Connecting to a Publisher
If you started Replication Monitor by using the context menu of a Publisher in SSMS, the Publisher is listed automatically. However, you can connect to additional Publishers within Replication Monitor or reconnect to one that you removed before. In this exercise, we'll add back to the list the Publisher we deleted in the previous exercise, as described in the following steps: 1. In Replication Monitor's left-hand window, right-click the Replication Monitor node, and then click Add Publisher, as shown in Figure 13-5.
Figure 13-5:
2. When the Add Publisher dialog box appears, click the Add button, and then click Add SQL Server Publisher, as shown in Figure 13-6.
269
Figure 13-6: Using the Add Publisher dialog box to add a Publisher.
3. When the Connect to Server dialog box appears, provide the necessary connection information. On my system, I'm connecting to the instance SQL2\S12A, as shown in Figure 13-7. Once you've entered the necessary information, click Connect.
270
4. If the connection is successful, a message box appears, similar to the one shown in Figure 13-8. It lets us know that, in order to monitor a Publisher, Replication Monitor needs to connect, not only to that Publisher, but also to the Distributor.
Figure 13-8:
5. When you click OK to close the message box, another Connect to Server dialog box appears, with your publication's Distributor preselected. Provide the necessary credentials and click Connect. 6. You will be returned to the Add Publisher dialog box. It should now list your Publisher and Distributor in the Start monitoring the following Publisher(s) section. You can connect to additional Publishers by clicking the Add button and repeating the steps above. 271
Chapter 13: Replication Monitor 7. Next, you must provide a group under which the Publisher will be listed in Replication Monitor. The bottom half of the Add Publisher dialog box lists all groups that are currently dened. Because we removed the only group in the previous exercise, this list is empty. Click New Group to create a one. This launches the New Group dialog box, as shown in Figure 13-9.
Figure 13-9:
8. Type My Publications in the Group Name text box, and then click OK . This will add the new group to the list of groups and automatically select it. If you have multiple groups listed here, make sure the new one is selected. 9. The last thing you need to set is the refresh interval. It determines how often information about the Publisher is collected from the Publisher as well as the Distributor. The default value of 10 seconds is usually a good choice, so we'll leave that value unchanged. Your Add Publisher dialog should now look similar to the one shown in Figure 13-10.
272
10. Click OK again to close the Add Publisher dialog box. Replication Monitor's left-hand window should again list the Publisher, as shown in Figure 13-11.
273
Note that you cannot create a group inside of another group, nor can you create more than one connection to a Publisher at a time. That means each Publisher can be in only a single group at any given time. If you try to connect to a publisher a second time, Replication Monitor will display a friendly message box telling you it won't tolerate such an attempt. 11. Leave Replication Monitor open for the remainder of the chapter.
274
275
The Publications tab displays information about all publications dened on the selected Publisher. The information is divided into the following columns: Status: This column gives information about the general health of this publication and its subscriptions. There are four possible values: Error Performance Critical Retrying failed command OK.
276
Chapter 13: Replication Monitor Publication: The names of the publication and database it's dened in, in this format: [Database Name]: Publication Name. Subscriptions: This column lists the number of Subscribers for each publication. Synchronizing: This is the number of subscriptions that are currently actively synchronizing. This value is only meaningful for merge and snapshot replication. Current Average Performance and Current Worst Performance: These columns display information about the current performance of all subscriptions combined. Possible values are: Excellent Good Fair Poor Critical. The performance measurement for the last two columns is based on the performance of all subscribers. Performance for transactional subscriptions is measured only if the performance thresholds have been enabled in the Warnings tab (described in the next section). Merge publication performance is displayed only after at least ve synchronizations. The second tab of the Publisher module is the Subscriptions Watch List tab, shown in Figure 13-13. The tab displays a list of subscriptions associated with the selected Publisher, based on subscription type.
277
You select the subscription type from the drop-down list near the top-left corner of the Subscription Watch List tab. You can view information about transactional, merge, or snapshot subscriptions. The list of columns is dierent for each type. (The sections that follow provide more details about what information is displayed.) The drop-down list near the top-right corner of the tab allows you to lter your list of subscriptions based on problem areas. Figure 13-14 shows the list of available options in the drop-down list.
278
If you select one of these lters, only subscriptions that match the lter are included in the list. This can be a great help if you are dealing with a lot of subscriptions. The third tab of the Publisher module, Agents, displays information about the replication agents, as shown in Figure 13-15.
279
In the Agent types drop-down list, you can select which types of agents you want to display. The available types include the following: Snapshot Agent Log Reader Agent Queue Reader Agent Maintenance Jobs. In reality, the last entry in this list is not an agent. Instead, it covers all the additional maintenance jobs that are created by replication.
280
Chapter 13: Replication Monitor After you make a selection, the window will show all agents (or jobs) of the selected type across all publications on this Publisher. The information displayed for each is dependent on its type. However, for each of them there is a lot of information available. Especially for the log reader agents there is more information displayed here than anywhere else in Replication Monitor, so this should be the rst place to check if you think you are having a problem with the log reader. For all agent types, you will nd at least information about the current status, the last start time, the duration, and the last action performed. In addition, for all selections of the Agent types drop-down list, with the exception of Maintenance Jobs, the tab also displays performance information for the most recent run, as well as counts for trans actions and commands processed during the most recent run. The Agent types drop-down list contains neither the Distribution Agent nor the Merge Agent. Those are subscription-specic agents and are therefore not included in the Publication's Agents tab.
281
The Status column indicates the health of the Distribution Agent for this subscription. The column supports the following values: Error Retrying failed command Not Running Running.
282
Chapter 13: Replication Monitor There are also three possible warnings that can be included in addition to the status: Performance critical Expiring soon / Expired Uninitialized subscription. For example, you might see a status of Running, Performance critical. The Performance column provides a rough overview of the speed of the Subscriber. You can nd the same values here that are used for the Publisher performance. The Latency column species the time that it takes for a change to replicate from the Publisher to this Subscriber. The second tab of the publication module is the Tracer Tokens tab. It displays latency measurements from the Publisher to the Distributor, the Distributor to the Subscriber, and the total latency, as shown in Figure 13-17.
283
Chapter 13: Replication Monitor A tracer token is a special mark that gets inserted into the log le of the publication database. A tracer token does not change the data in the replicated tables on the Publisher or any Subscriber. However, to the replication agents, this mark looks like a normal transaction. That means it moves through all the standard replication steps, allowing SQL Server to measure the latency between Publisher and Distributor as well as between the Distributor and each Subscriber. You can insert a new tracer token into the log by pressing the Insert Tracer button on the Tracer Tokens tab. The Tracer Tokens grid displays a single row per Subscriber. You can retrieve previous latency measurements by selecting the date and time from the Time inserted drop-down list. The date and time in this list represent when the token was inserted into the log. The next tab in the publication module is the Agents tab. It displays information about the SQL Server Agent jobs that run the Snapshot Agent and the Log Reader Agent, as shown in Figure 13-18.
284
Chapter 13: Replication Monitor The information includes the job status, the last start time, and the duration of the last execution (which can still be running). The Agents tab also displays information about the last action that was taken by each agent. Information about the Distribution Agents is not included in this tab. Later in the chapter, you'll see where to nd this information. The last tab of the publication module is the Warnings tab, shown in Figure 13-19. The tab lets you enable warnings and congure their thresholds.
For transactional replication, you can specify the thresholds for two warnings. The rst is an expiration warning. If more than the specied percentage of the maximum retention time has passed for a Subscriber, this warning will be displayed for that Subscriber. (See Chapter 7 for information about maximum retention times.)
285
Chapter 13: Replication Monitor The second threshold is related to a latency warning. You'll receive a warning when the latency exceeds the specied time limit (in seconds, minutes, or hours). You can disable either warning by deselecting the Enabled check box associated with the specic warning. The actual warnings are displayed in the Status column on the All Subscriptions tab. A yellow triangle is also tagged onto each level of the Publisher hierarchy in the left-hand window. Figure 13-20 provides an example of what the warning tags look like.
286
287
Chapter 13: Replication Monitor The All Subscriptions tab contains a row for each subscription associated with the selected merge publication. For each row, you can see the current status, connection type, time and duration of the last synchronization, performance-related information, and the delivery rate. The Status column can contain any of the following values: Error Retrying failed command Not synchronizing Synchronizing. There are also four possible warnings that can be included in addition to the status: Performance critical Long-running merge Expiring soon / Expired Uninitialized subscription. For example, you might see a status of Synchronizing, Performance critical. The Performance column can contain any of the following four values: Excellent Good Fair Poor. There are some additional columns shown in Figure 13-21. They are mostly selfexplanatory. Check out SQL Server Books Online for more details about those columns. 288
Chapter 13: Replication Monitor The second tab of the publication module associated with merge publications is the Agents tab. It's similar to the one used for transactional publications (shown in Figure 13-18), except that, for merge publications, it displays information only about the Snapshot Agent. The third tab, Warnings, lets you congure warning thresholds, as shown in Figure 13-22.
The Warnings tab includes ve warnings that you can enable and congure for merge replication. The rst warning is displayed when a subscription is about to expire. The second and third warnings are displayed when a length of a single synchronization exceeds this threshold. The rst of these is specic to dialup connections, and the second is specic to LAN connections; only one of the two is active for any given synchronization, based on the current connection type. The last two warnings are displayed when the rate of rows merged per second drops below the threshold set here. In this case, the rst of these is specic to LAN connections, and the second to dialup connections. The warnings themselves are displayed in the same way as they are for transactional subscriptions. Refer back to Figure 13-20 for an example of how warnings are displayed. 289
The information shown in the three tabs for snapshot publications is similar to the information available for merge publications. However, because of the simpler architecture of snapshot replication, the amount of information available is signicantly reduced. For example, the publication module includes no performance information on the All Subscriptions tab, and the only warning available on the Warnings tab is the expiration warning. 290
Subscription Information
Throughout this chapter, you've seen several examples of how Replication Monitor lists subscriptions in the right-hand window. Everywhere you have a subscription list, you can access more options available to each subscription by right-clicking the subscription. This opens a context menu, as shown in Figure 13-24.
In this case, the subscription is a transactional subscription associated with the MyFirstPublication publication. Notice that, from the context menu, you can start or stop the synchronization process, reinitialize the subscription, or access the subscription's properties or agent prole. In addition, you can click the View Details option to open the Subscription dialog box, shown in Figure 13-25.
291
The Subscription dialog box for a transactional subscription includes three tabs: Publisher To Distributor History, Distributor To Subscriber History, and Undistributed Commands. The rst two tabs contain information about the last synchronizations. The rst shows information about the synchronizations between the Publisher and Distributor, and the second tab shows information about the synchronizations between the Distributor and the selected Subscriber. In the bottom half of each tab, you'll nd a list of the last actions that were performed, such as Bulk copied data into table 'Test' (1000 rows). This information can sometimes be helpful when troubleshooting as it can provide insight into when the problem started. 292
Chapter 13: Replication Monitor The third tab, shown in Figure 13-26, contains information about the number of undistributed commands as well as an estimate for the remaining runtime needed to distribute those commands. This information can be used to judge how long it will take for the subscription to catch up with the publication. However, the time estimate displayed here is not always accurate.
For a merge subscription, the Subscription dialog box contains only a single tab, Synchronization History, which displays information about the last synchronizations, as shown in Figure 13-27. 293
For each merge synchronization, you can display detailed statistical information in the bottom half of the dialog box by selecting that synchronization in the list. If you have a lot of synchronizations, the drop-down list at the top of the window can help narrow down the list of synchronizations. The default is to show the last 100 synchronizations. For a snapshot subscription, the Subscription dialog box also contains only a single tab, the Distributor To Subscriber History tab. It is similar to the one displayed in Figure 13-25 for transactional subscriptions. 294
Alerts
When you enable a warning on a publication's Warnings tab, a yellow triangle is displayed when one of the Subscribers exceeds the set threshold. By default, no additional action is taken. However, you can also set up a SQL Server alert so that SQL Server noties you if that threshold has been exceeded. Replication supports several predened alerts that you can utilize. You can set up the alerts directly in SSMS or on the Warnings tab of Replication Monitor, which is a much simpler process. If you refer back to Figure 13-19, you'll see that the Warnings tab includes the Congure Alerts button. When you click that button, the Congure Replication Alerts dialog box appears, as shown in Figure 13-28.
295
Chapter 13: Replication Monitor To congure an alert, select it from the list and then click the Congure button. This launches a standard alert properties dialog box, prelled with the information needed for the selected alert. An example is shown in Figure 13-29.
296
Chapter 13: Replication Monitor You can use this form to specify what SQL Server should do, and who should be notied when the alert res. For details on how to use alerts, check out the article, Stairway to SQL Server Agent, Level 3: Agent Alerts and Operators at http://www.sqlservercentral.com/ stairway/72403/.1
Summary
In this chapter, you learned about Replication Monitor and the vast amount of information it can provide about your replication environment. We examined the Publisher module and the publication module. We investigated warnings and learned how to set warning thresholds. We also looked briey at the information provided for subscriptions. The chapter closed with an explanation of how to set up SQL Server alerts related to replication.
297
298
Figure 14-1:
299
Figure 14-2:
You can see in Figure 14-2 that the Log Reader Agent has generated errors. You can nd more information about an agent and its errors by double-clicking the agent in this listing. If you do this with the Log Reader Agent, the Log Reader Agent dialog box appears, as shown in Figure 14-3.
300
Figure 14-3:
As you can see, there is not much information available here. However, the error message recommends checking out the agent job history in the Jobs folder. This refers to the job history for the SQL Server Agent job that runs the Log Reader Agent. Remember, the Log Reader Agent runs on the Distributor. So, to get to the job history, connect to the Distributor in Object Explorer (SQL1\S12B, in my case), open the SQL Server Agent folder, and double-click Job Activity Monitor, as shown in Figure 14-4. 301
Figure 14-4:
When the Job Activity Monitor dialog box appears, nd the Log Reader Agent's job. The easiest way to identify this job is to look at the Category column. The category of the Log Reader Agent's job is REPL-LogReader. Right-click the job and then click View History, as shown in Figure 14-5.
302
Figure 14-5:
Opening the history for the Log Reader Agent in Job Activity Monitor.
This opens the Log File Viewer dialog box. On the right-hand side it shows one row per job execution, with the latest job on top. If you click the plus sign at the left end of a row, you can view details about the individual steps that have run as part of the job. Figure 14-6 shows details about the steps in one of those executions.
303
Figure 14-6: SQL Server Agent job history for the Log Reader Agent.
With each execution and execution step in the job history, you'll nd one of the four symbols listed in Table 14-1.
304
Symbol
Meaning
Running Retrying
Table 14-1:
If you refer back to Figure 14-6, you'll see multiple entries for Step 2. In fact, all visible entries are for Step 2, which can happen if a problem is encountered during the execution of that step. If a step fails, SQL Server Agent will either try to re-execute that step or it will mark it as failed, depending on how the job step was congured. In the latter situation, you'll see the Failure symbol from Table 1 next to that step. However, in our Log Reader Agent example, the step keeps retrying, so you see the Retrying symbol instead. In either case, the actual error is often not found in the row that is indicating the problem but in one of the preceding rows. In most cases, that row will still show the Running symbol. In our case, the error message can be found in the second job step row. If you click that row, the bottom half of the window will show detailed information about that job step execution. By scrolling down all the way, you can see the error message. (Refer back to Figure 14-6.) The actual error message is as follows:
Login failed for user 'DOMAIN\SQL2_S12B_LogReader'.
This looks helpful at rst glance, but it really isn't. It is telling us that the login failed. However, at no point does the job step output reveal what it was trying to log on to. Usually a SQL Server error has a telling "Msg" in front, such as the one shown in the following error message:
305
However, since that information is stripped out of our job step message, we can't even be sure that it's a SQL Server error instead of, for example, a Windows error. In this case, however, I know that the attempt to connect to the Distributor SQL Server instance failed. The reason I know this is that errors occurring while connecting to the Distributor are the only ones where no instance name is included. The error here is caused by DOMAIN\SQL2_S12B_LogReader not being a known SQL login on the Distributor. To correct this situation, we're going to use a short T-SQL script (rather than using a wizard) to create the login:
CREATE LOGIN [DOMAIN\SQL2_S12B_LogReader] FROM WINDOWS WITH DEFAULT_ DATABASE=[tempdb]
The default database does not really matter in this case. I usually set it to tempdb for all my logins because that is the place where the least amount of damage can be caused if one forgets to explicitly select a database after logging in. After running the above T-SQL snippet on the Distributor, go back to the Log File Viewer and click Refresh. You should now see a new job step execution, although you might have to wait a minute for this to show up. As it turns out, this new job step execution still ends in a retry. The new error is shown in Figure 14-7.
306
Figure 14-7:
This message is another example of why troubleshooting replication can be difficult. It states that SQL2\S12B does not exist or is not a valid Publisher. It looks as though it's indicating that the agent cannot connect to the Publisher. However, this error is actually still caused on the Distributor. The last part of the error, "you may not have permission to see available Publishers," is pointing to the actual problem. While the Log Reader Agent can now successfully connect to the Distributor, the login has not yet been mapped to a user in the distribution database. Therefore, it cannot access the list of valid Publishers. To x this, we need to run more T-SQL on the Distributor:
USE [distribution] GO CREATE USER [DOMAIN\SQL2_S12B_LogReader] FOR LOGIN [DOMAIN\SQL2_S12B_LogReader] ALTER ROLE [db_owner] ADD MEMBER [DOMAIN\SQL2_S12B_LogReader]
307
Chapter 14: Troubleshooting The T-SQL creates the user account and adds it to the db_owner role (which is required, as you will recall from Chapter 5). Creating the user and granting the missing permissions, however, still does not solve the problem. After another refresh, the job history of the Log Reader Agent still shows continuous retries. Checking the latest execution in the log reveals that there is now a dierent problem: the agent cannot connect to the Publisher. This information is again all the way at the bottom of the step output, as shown in Figure 14-8.
Figure 14-8:
308
Chapter 14: Troubleshooting This is exactly the same error that we had before. However, this time, if you go up a few lines in the output, you will see the helpful remark "Validating publisher." So while the error doesn't seem much more helpful than the rst time we saw it, this additional piece of information at least tells us what the Log Reader Agent was trying to do when the error occurred. So this time, we'll connect to the Publisher and run the same T-SQL snippet as before, in order to resolve this problem:
CREATE LOGIN [DOMAIN\SQL2_S12B_LogReader] FROM WINDOWS WITH DEFAULT_ DATABASE=[tempdb]
Unfortunately, this only leads us to the next problem, as shown in Figure 14-9.
Figure 14-9: Message indicating that the publication database cannot be opened.
309
Chapter 14: Troubleshooting This error message is actually surprisingly helpful. To resolve the issue raised, we need to grant the newly created login db_owner rights in the publication database (ReplA, in my case):
USE [ReplA] GO CREATE USER [DOMAIN\SQL2_S12B_LogReader] FOR LOGIN [DOMAIN\SQL2_S12B_LogReader] ALTER ROLE [db_owner] ADD MEMBER [DOMAIN\SQL2_S12B_LogReader]
After we grant this last bit of access to the publication database, the Log Reader Agent gets to work successfully. As you can see in Figure 14-10, the message associated with the most recent execution indicates that the replication has been successfully started.
Figure 14-10: Message indicating that the Log Reader Agent started successfully.
310
We can quickly discover why our subscription is not yet initialized. The Agents tab, shown in Figure 14-12, tells us that the Snapshot Agent was never executed.
311
This is quickly xed. Right-click the Snapshot Agent listing on the Agents tab, and then click Start Agent, as shown in Figure 14-13.
312
After starting the Snapshot Agent, everything appears to be running great, as you can see in Figure 14-14. The Snapshot Agent usually starts, does its thing, and stops right away. Given that our database is so small, this process should nish in a few seconds. So let's wait. After a few minutes of staring at this screen you probably start wondering why we still show a status of Running. This makes no sense if everything really is running as smoothly as the Replication Monitor leads us to believe.
313
In reality, the Snapshot Agent failed right away. However, Replication Monitor relies on the Snapshot Agent to regularly report status information. Only if that report is not sent for about 10 minutes does Replication Monitor report a problem. You can see this in Figure 14-15. Notice the reported execution duration.
314
Unfortunately, double-clicking the listing for the failed Snapshot Agent doesn't provide us with any more details, as Figure 14-16 shows.
315
The only hint we're given is to make sure everything is still working. However, we know already that's not the case, so let's check out the next tool of choice, the Job Activity Monitor. The Snapshot Agent also runs on the Distributor, so we need to go to the same place we went to earlier for the Log Reader Agent. As before, you can identify the Snapshot Agent job by looking at the job category column. Figure 14-17 shows that a problem was indeed encountered during the last execution of the Snapshot Agent. 316
For more details, let's look at the history for the Snapshot Agent job. Right-click the job and then click View History. This launches the Log File Viewer, shown in Figure 14-18.
317
Figure 14-18 shows the history for my setup. Step 1 succeeded and Step 2 failed during the last execution. Again, the actual error is not in the entries that have the error symbol, but in the last one that does not. In this case, the error is one we've seen before:
Login failed for user 'DOMAIN\SQL2_S12B_Snapshot'.
318
Chapter 14: Troubleshooting A few lines up, we can see that the agent was trying to connect to the Distributor when the error happened. By now, we know what we have to do to x this. Execute the following T-SQL snippet on the Distributor:
CREATE LOGIN [DOMAIN\SQL2_S12B_Snapshot] FROM WINDOWS WITH DEFAULT_ DATABASE=[tempdb]
To see if this change helped, we have to manually start the Snapshot Agent again, as it is not congured to run continuously like the Log Reader Agent. You can use the Replication Monitor to start the Snapshot Agent, as shown in Figure 14-19.
Because we already know that the above change was not sufficient, we do not wait for the Replication Monitor to get to the same realization but head over to the job's history right away. You might have to refresh the history by clicking the Refresh icon in the top row. As expected, Figure 14-20 shows that there is another problem to x. 319
Figure 14-20: The Snapshot Agent's failure to access the distribution database.
The error sounds again very familiar. As before, it seems to tell us that we lost the Publisher in the depth of our network. However, it really means that the Snapshot Agent cannot access the distribution database. The Snapshot Agent also needs db_owner level permissions in this database, so we must run the following T-SQL snippet against the Distributor:
USE [distribution] GO CREATE USER [DOMAIN\SQL2_S12B_Snapshot] FOR LOGIN [DOMAIN\SQL2_S12B_Snapshot] ALTER ROLE [db_owner] ADD MEMBER [DOMAIN\SQL2_S12B_Snapshot]
320
Chapter 14: Troubleshooting As before, to see if this had the desired eect, we must restart the Snapshot Agent. This, however, leads to our next error, which occurs when validating the Publisher. Figure 14-21 shows the latest error message.
To x our latest problem, we need to create the missing login on the Publisher:
CREATE LOGIN [DOMAIN\SQL2_S12B_Snapshot] FROM WINDOWS WITH DEFAULT_ DATABASE=[tempdb]
After running this statement, we can again use Replication Monitor to restart the Snapshot Agent. And then we return to Snapshot Agent's job history. Figure 14-22 shows our latest error. 321
Figure 14-22: The Snapshot Agent's failure to access the publication database.
Again the x is easy. We need only to grant the login db_owner permissions in the publication database by running the following T-SQL snippet on the Publisher:
USE [ReplA] GO CREATE USER [DOMAIN\SQL2_S12B_Snapshot] FOR LOGIN [DOMAIN\SQL2_S12B_Snapshot] ALTER ROLE [db_owner] ADD MEMBER [DOMAIN\SQL2_S12B_Snapshot]
322
Chapter 14: Troubleshooting After restarting the Snapshot Agent and refreshing the history in the SQL Server Agent Log File Viewer, we will be confronted with the last problem we need to x for the Snapshot Agent. The error message that points to the problem is shown in Figure 14-23.
Figure 14-23: The Snapshot Agent's failure to access the snapshot folder.
The error indicates denied access to a lengthy network path. If you get an error like this, the most likely reason is that the Snapshot Agent does not have the required permissions on the snapshot folder. Remember, the account that is used to execute the Snapshot Agent needs to have write access to this folder.
323
Chapter 14: Troubleshooting To grant the required permission, log on to the server that hosts the Distributor (using Remote Desktop, if necessary), and navigate to the snapshot folder in Windows Explorer. Right-click the folder and click Properties. Go to the Sharing tab and click the Advanced Sharing button. In the Advanced Sharing dialog box, click the Permissions button to open the Permissions dialog box, shown in Figure 14-24.
Figure 14-24: Setting the required permissions for the snapshot folder.
Add the required permissions and close all dialog boxes by clicking the OK button of each one. After we've addressed the share-access problem, the publication should be up and running. The Agents tab for our publication in Replication Monitor should inform us that the Snapshot Agent completed successfully after creating a snapshot. The Log Reader Agent, on the other hand, is still running but was able to successfully complete at least one action. Figure 14-25 shows the status of both replication agents. 324
Troubleshooting a Subscription
Although we've addressed the issues with the replication agents associated with our publication, the subscription in our example is still not working. We need to return to Replication Monitor and view our publication's All Subscriptions tab. At rst, it appears that our subscription is running as expected, as shown in Figure 14-26. However, our subscription is still uninitialized.
325
The fact that no Performance or Latency value is displayed is a strong indication that something is seriously wrong. To get more information, you can double-click the uninitialized subscription. This opens a dialog box that displays detail information about the current state of the subscription. The Distributor to Subscriber History tab gives us information about the past data movement between the Distributor and the Subscriber. As you can see in Figure 14-27, there is no sign that anything is wrong.
326
Figure 14-27: History of past data movement between the Distributor and the Subscriber.
So we have to go somewhere else to nd the cause of our problem. The data movement between Distributor and Subscriber is handled by the Distribution Agent. The next thing to check, therefore, is whether the Distribution Agent's job is reporting any problems. Where you nd that job is dependent on the subscription model. In the case of a pull subscription, the Distribution Agent runs on the Subscriber. However, our example is set up as a push subscription, so we need to connect to the Distributor. Once connected, open the Job Activity Monitor and nd the Distribution Agent's job. As before, you can use the job category to identify this job, which is highlighted in Figure 14-28. 327
On rst glance, everything seems ne here too. However, note the Status column, which says: "Between retries." This means that, during the execution of the previous job step, a problem was encountered, and now the SQL Server Agent is waiting a minute before retrying that same step. Right-click the job and select View history to get to the root of this problem. Figure 14-29 shows the history with its many rerun attempts of Step 2.
328
Figure 14-29: The Distribution Agent's job history showing multiple attempts to run.
Figure 14-29 also shows the error that is causing the continuous retries: the connection to the Distributor keeps failing. To address this issue, we must create the missing login by executing the following T-SQL snippet on the Distributor:
CREATE LOGIN [DOMAIN\SQL3_S12B_DistPush] FROM WINDOWS WITH DEFAULT_ DATABASE=[tempdb]
329
Chapter 14: Troubleshooting Not surprisingly, the step continues to fail despite the new login. That's because the login doesn't yet have access to the subscription database. You can see the new error in Figure 14-30.
330
Chapter 14: Troubleshooting To resolve this issue, we must create the user in the distribution database and add it to the db_owner role:
USE [distribution] GO CREATE USER [DOMAIN\SQL3_S12B_DistPush] FOR LOGIN [DOMAIN\SQL3_S12B_DistPush] ALTER ROLE [db_owner] ADD MEMBER [DOMAIN\SQL3_S12B_DistPush]
So far, it looks as if the Replication monitor is not useful at all. However, if you wait long enough after a problem occurs, Replication Monitor will eventually show that there is a problem too. Usually you will have to wait less than 10 minutes for an error to show up. Figure 14-31 shows an example telling us that our subscription still has a problem.
Figure 14-31: The Replication Monitor eventually catching up with the error.
Double-clicking the error opens the Subscription dialog box. In this case, it even shows a useful error message, as you can see in Figure 14-32. 331
Despite the information provided by Replication Monitor in this example, I tend to concentrate on the job history for replication troubleshooting, at least during the setup phase of replication, because the information there is usually more comprehensive and up to date. However, after replication has been running for a while, you might encounter problems about which you can get good details only by using Replication Monitor. For an example, see the section, Data problems, later in this chapter. Let's get back to our current error. It tells us that the process cannot connect to the Subscriber. So, let's create the missing login by running this snippet on the Subscriber:
CREATE LOGIN [DOMAIN\SQL3_S12B_DistPush] FROM WINDOWS WITH DEFAULT_ DATABASE=[tempdb]
332
Chapter 14: Troubleshooting The next two errors, shown in Figures 14-33 and 14-34 are by now neither surprising nor hard to x. Following each gure, you'll nd the T-SQL snippets that you need to run to x the problems. Because both errors deal with access to the subscription database, you must connect to the Subscriber before running these statements.
333
Chapter 14: Troubleshooting To address the error shown in Figure 14-33, run the following T-SQL snippet on the Subscriber:
USE [ReplB] GO CREATE USER [DOMAIN\SQL3_S12B_DistPush] FOR LOGIN [DOMAIN\SQL3_S12B_DistPush]
To address the error shown in Figure 14-34, run the following T-SQL snippet on the Subscriber:
USE [ReplB] GO ALTER ROLE [db_owner] ADD MEMBER [DOMAIN\SQL3_S12B_DistPush]
334
Chapter 14: Troubleshooting The last error that we have to deal with is shown in Figure 14-35.
This is, again, not surprising. To x this problem, you need to log on to the Distributor and grant the account executing the Distribution Agent read access to the snapshot folder share. Figure 14-36 shows what the Permissions dialog box looks like after adding the new permission. This is the same dialog box that is shown in Figure 14-24. Just before that gure, you can also nd details on how to access the dialog box. 335
After performing the last step, the Distribution Agent should now run successfully, as shown in Figure 14-37.
336
If you now go back to Replication Monitor, you should see a happy subscription with a status of Running and performance displayed as Excellent. However, in the rst few minutes after setting up a subscription or xing a subscription problem, Replication Monitor often reports the performance as critical, as shown in Figure 14-38. That usually goes away after a few moments, so don't be too alarmed if performance is o at rst. 337
Tracer tokens
One important tool in the DBA's toolbox is the tracer token. We already covered tracer tokens in Chapter 13, so here we will repeat only the highlights. Tracer tokens allow you to measure the latency between the Publisher and the Distributor as well as between the Distributor and the Subscriber. However, they can also be used to check for problems. If you create a tracer token and it gets replicated to the Subscriber in a reasonable amount of time, you can be fairly condent that everything is working correctly. Figure 14-39 shows a successful tracer token run.
Figure 14-39: Tracer token conrming that the subscription is working properly.
339
Chapter 14: Troubleshooting So, if you are unsure whether data is moving, just create a tracer token and in a few seconds you will know. If you regularly use tracer tokens, you can even detect trends such as increasing latency. That can help you identify problems before they become too painful.
340
Chapter 14: Troubleshooting If such a value shows up, it might just indicate that there is currently no data that needs to be replicated. On a production system, however, it almost always means trouble. In my case, the subscription was marked for re-initialization using an existing snapshot. However, the existing snapshot was already expired, so the subscription never nished its initialization step. If you double-click the subscription, the Subscription dialog box will open and reveal that the initial snapshot is not yet available, as shown in Figure 14-41.
341
Chapter 14: Troubleshooting To resolve this issue, you need to manually start the Snapshot Agent, as we did earlier in this chapter. You might also have to reinitialize the subscription after the Snapshot Agent is nished. Sometimes in this situation the subscription gets stuck and does not use the new snapshot on its own. Replication Monitor is a helpful tool when it properly noties you that there's a problem; however, if it shows that everything is in great shape, make sure you look twice, so you don't miss a subtle hint indicating that there is a problem.
Data problems
If there is a problem in the replicated data, the Distribution Agent will keep trying to resolve it. For example, Figure 14-42 shows the Distributor To Subscriber History for ProblemPublication. It has a bunch of error rows with start times about two-anda-quarter minutes apart. The error is the same for all of them: "The row was not found at the Subscriber when applying the replicated command." This error is caused by a mismatch between the data in the publication database and the subscription database, potentially caused by a delete being executed at the Subscriber. Remember, while the subscription database is technically read-write, the target tables of a subscription to a transactional publication should be handled as if they were read-only.
342
This error prevents the Distribution Agent from continuing because it could cause inconsistent data on the Subscriber. Instead, the Distribution Agent keeps trying, in the hopes that the error magically disappears. Each execution takes about one and a quarter minutes, as you can see in the Duration column in Figure 14-42. During that time, the replication agent shows that everything is working smoothly, which is what Figure 14-43 shows. 343
However, during the remaining minute of the retrial interval, the Replication Monitor display looks vastly dierent, as shown in Figure 14-44.
344
So, if you happen to look at the Replication Monitor while the issue is occurring, you'll see what is shown in either Figure 14-43 or Figure 14-44. Which results you receive depends on whether the process is currently retrying or not. That means that, if you only briey look at the tool, you'll get to see the error in less than half the cases, based on the times in my example. Most problems, however, such as the one mentioned above, will show up in the Subscription dialog box (Figure 14-42) associated with a specic subscription. Therefore it is a good idea to get into the habit of opening the dialog box regularly. Remember, you access the dialog box by double-clicking the subscription itself in Replication Monitor.
345
Chapter 14: Troubleshooting To troubleshoot this and other data-related problems, review the error message itself, such as the one shown at the bottom of Figure 14-42. Notice that it contains a link to a Microsoft help page, which provides an explanation of what went wrong. There you will also nd tips of how to resolve the issue. This link is displayed only when using Replication Monitor. The job history shows the error, but omits the link.
Summary
This chapter did a walk-through of a few troubleshooting scenarios found in a transactional replication setup. It focused on problems you might encounter during the SQL Server replication setup and provided a few ways to identify problems that you might encounter after your replication setup has been running for a while. The takeaway from this chapter is that Replication Monitor, while being a good, and often helpful, tool to get a general feel for the health of your replication installation, does not always make problems obvious. You have to be able to read their subtle hints and then go elsewhere to get complete information. Most of the time this "elsewhere" is the SQL Server Agent job history of one of the Replication Agent's jobs. The chapter also briey mentioned that you should use tracer tokens or a similar tool to regularly monitor the latency of your installation. This not only provides you with information about performance, it also provides an early warning if the continuous data stream is blocked by, for example, a data error. This chapter also concludes this book. I hope you found it to be useful and had as much fun working through it as I had writing it. The book covered transactional replication and merge replication. It also introduced tools for monitoring and troubleshooting. From the beginning, we also paid special attention to following the "least privilege" principle when setting up replication to help ensure that you're creating secure replication installations from the get-go.
346
Pricing and information about Red Gate tools are correct at the time of going to print. For the latest information and pricing on all Red Gate's tools, visit www.red-gate.com
$595
"Just purchased SQL Compare. With the productivity I'll get out of this tool, it's like buying time."
Robert Sondles Blueberry Island Media Ltd
$595
"We use SQL Data Compare daily and it has become an indispensable part of delivering our service to our customers. It has also streamlined our daily update process and cut back literally a good solid hour per day."
George Pantela GPAnalysis.com
$295
"SQL Prompt is hands-down one of the coolest applications I've used. Makes querying/developing so much easier and faster."
Jorge Segarra University Community Hospital
from $295
Deployment Manager
from
Free
Deploys your whole application ASP.NET sites, dependent assemblies, and databases in one process Makes deployment repeatable with a minimum of custom scripting Shows you which version of your software is running on each dev, test, staging, and production environment, from a central dashboard Works with local, remote, and Cloud-based servers Uses public/private key encryption to keep deployments over the Internet secure
"Our old deployment process was cumbersome and stressful now it's almost fun."
Mattias Geigant Developer, BEAB
$795
Compress SQL Server database backups by up to 95% for faster, smaller backups Protect your data with up to 256-bit AES encryption Strengthen your backups with network resilience to enable a fault-tolerant transfer of backups across flaky networks Control your backup activities through an intuitive interface, with powerful job management and an interactive timeline Get integrated backup verification with automated restore + DBCC CHECKDB Quickly, simply, and securely upload and store a copy of your backup offsite, in hosted storage
"SQL Backup Pro cut the backup time for our most mission-critical database by 92%, and provided us with 95% compression. Builtin network resilience has also reduced our failure rate to zero. I'm absolutely amazed at how well it performs."
Kiara Rodemaker Manager, IT Accounting Services, Czarnowski
SQL Monitor
SQL Server performance monitoring and alerting
from
$795
Intuitive overviews at global, cluster, machine, SQL Server, and database levels for up-to-the-minute performance data Use SQL Monitor's web UI to keep an eye on server performance in real time on desktop machines and mobile devices Intelligent SQL Server alerts via email and an alert inbox in the UI, so you know about problems first Comprehensive historical data, so you can go back in time to identify the source of a problem View the top 10 expensive queries for an instance or database based on CPU usage, duration, and reads and writes PagerDuty integration for phone and SMS alerting Fast, simple installation and administration Add your own T-SQL scripts with the custom metrics feature to expand SQL Monitor's range
"Being web based, SQL Monitor is readily available to you, wherever you may be on your network. You can check on your servers from almost any location, via most mobile devices that support a web browser."
Jonathan Allen Senior DBA, Careers South West Ltd
$1,895
Troubleshooting
Get an alert within seconds of a problem arising, gain insight into what happened, and diagnose the issue, fast.
Productivity
Save time writing SQL in SQL Server Management Studio or Visual Studio, with code-completion and customizable SQL snippets.
Change management
Get a simple, clear rundown of your schema and data changes, and sync database changes automatically.
Documentation
Automatically generate database documentation with a couple of clicks in SSMS, so you can save time and keep your team up to date.
SQL Multi Script SQL Compare Standard
SQL Prompt
SQL Doc
The tools in the bundle can be bought separately with a combined value of $3,565, or purchased together for $1,895, saving 45% on the individual tool prices.
SQL Toolbelt
The essential SQL Server tools for database professionals
$2,195
You can buy our acclaimed SQL Server tools individually or bundled. Our most popular deal is the SQL Toolbelt: fourteen of our SQL Server tools in a single installer, with a combined value of $5,930 but an actual price of $2,195, a saving of 65%. Fully compatible with SQL Server 2000, 2005, and 2008. SQL Toolbelt contains:
SQL Compare Pro SQL Data Compare Pro SQL Source Control SQL Backup Pro SQL Monitor SQL Prompt Pro SQL Data Generator SQL Doc
SQL Dependency Tracker SQL Packager SQL Multi Script Unlimited SQL Search SQL Comparison SDK SQL Object Level Recovery Native
"The SQL Toolbelt provides tools that database developers, as well as DBAs, should not live without."
William Van Orden Senior Database Developer, Lockheed Martin
$495
Find memory leaks and optimize memory usage of your .NET applications
Zero in on the causes of memory leaks, fast Visualize the relationship between your objects and identify references which should no longer be held in memory "Freaking sweet! We have a known memory leak that took me about four hours to nd using our current tool, so I red up ANTS Memory Proler and went at it like I didn't know the leak existed. Not only did I come to the conclusion much faster, but I found another one!"
Aaron Smith IT Manager, R.C. Systems Inc.
from
$395
"ANTS Performance Proler took us straight to the specic areas of our code which were the cause of our performance issues."
Terry Phillips Sr Developer, Harley-Davidson Dealer Systems
"I have integrated ANTS Proler into my entire development process and it has truly helped us write better performing applications from the beginning by ensuring that we always know exactly what is going on."
Mitchell Sellers MVP
.NET Reector
$95
"One of the most useful, practical debugging tools that I have ever worked with in .NET! It provides complete browsing and debugging features for .NET assemblies, and has clean integration with Visual Studio."
Tom Baker Consultant Software Engineer, EMC Corporation
SmartAssembly
Prepare your application for the world
Obfuscation: Obfuscate your .NET code to secure it against reverse engineering. Multiple layers of protection defend your software against decompilation and cracking.
$595
"Knowing the frequency of problems (especially immediately after a release) is extremely helpful in prioritizing and triaging bugs that are reported internally. Additionally, by having the context of where those errors occurred, including debugging information, really gives you that leap forward to start troubleshooting and diagnosing the issue."
Ed Blankenship Technical Lead and MVP
Automated Error Reporting: Get quick and automatic reports on exceptions your end-users encounter, and identify unforeseen bugs within hours or days of shipping. Receive detailed reports containing a stack trace and values of the local variables, making debugging easier.