86

A Guide to SQL Server 2000 Transactional and Snapshot Replication

Embed Size (px)

Citation preview

Page 1: A Guide to SQL Server 2000 Transactional and Snapshot Replication
Page 2: A Guide to SQL Server 2000 Transactional and Snapshot Replication

A Guide to SQL Server 2000 Transactional and Snapshot ReplicationCopyright @ 2004 Hilary Cotter

All rights reserved. No part of this work may be reproduced or transmitted inany form or by any means, electronic or mechanical, including photocopying,recording, or by any information storage or retrieval system, without the priorwritten permission of the copyright owner and the publisher.ISBN (pbk) 0-9749736-0-2

Printed and bound in the United States of America 12345678910

Trademark names may appear in this book. Rather than use a trademarksymbol with every occurrence of a trademarked name, we use the names onlyin an editorial fashion and to the benefit of the trademark owner, with nointention of infringement of the trademark. All trademarks belong to theirowners.

Technical Review: Mark AllisonEditor: Kevin CampbellBook Design and Production: Amy Rothstein [email protected] Editor: Linda Devore [email protected] Design: Wendy Reynolds [email protected]: Hilary Cotter

For information on translations, please contact Not While the Surf ’s Up Press by email: [email protected].

The information in this book is distributed on an “as is” basis, without anywarranty. Although every precaution has been taken in the preparation of thiswork, neither the author nor Not While the Surf ’s Up Press shall have any lia-bility to any person or entity with respect to any loss or damage caused oralleged to be caused directly or indirectly by the information contained in thiswork.

The source code for this book is available to readers at http://www.nwsu.comin the Downloads section.

Page 3: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Chapter 2Installing Replication

Let me live like a sky rocket. Let me colour the night sky for a singleinstant, burning with all of my being. And then burn out.

— Yukio Mishima

This chapter focuses on installing replication on your SQL Server. Mostusers will only install replication on their SQL Server and then enableSubscribers. We’ll look at these two options and then look at how to set upyour SQL Server to use a remote Distributor. After looking at theseoptions, we’ll look at Replication Monitor, which is the central point forreplication administration. In the process we’ll cover some of the moreadvanced options and settings. Following that, for those of you who arewizard adverse, we will look at the replication stored procedures that youcan use to carry out the same things.

There are really two parts to installing replication:

• Configuring your SQL Server as a Publisher/Distributor or a Distributor

• Configuring your Subscribers

Recall from Chapter 1 that a Distributor is a SQL Server that stores anddistributes transactions from your Publisher to your Subscriber. For mostreplication solutions, your Publisher and Distributor will be on the sameserver. For high throughput replication solutions, you should look at usinga remote Distributor.

Configuring your SQL Server as a DistributorConfiguring your SQL Server as a Distributor involves running a wizardthat creates a distribution database and several jobs in the msdb database.After your distribution database is installed, you are ready to create yourpublications. Let us walk through the wizards to understand how to config-ure your server as a Distributor. The first time you configure your SQLServer as a Distributor, open up Enterprise Manager (EM), connect to yourSQL server, and on the Tools menu, point to Replication, and then clickConfigure Publishing, Subscribers, and Distributors (Fig. 2.1). You canbypass this altogether and merely click Create and Manage Publications,which is what most DBAs do.

Installing Replication 37

Page 4: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Figure 2.1 Configuring SQL Server for replication

Both options will launch the Configure Publishing and DistributionWizard (Fig. 2.2).

Figure 2.2Splash Screen for theConfigure Publishingand DistributionWizard

Click Next to advance to Select Distributor (Fig. 2.3).

38 Chapter 2

Page 5: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Figure 2.3The Select Distributordialog box

This dialog box allows you to select which Distributor you want to use,or whether you want to configure the local SQL Server as a Distributor. Ifyou are using Transactional replication and you have a high transactionthroughput, you may wish to offload your distribution database to anotherserver. We call this migrating to a remote Distributor. In Merge andSnapshot replication, the location of the Distributor is less critical. A goodindication to migrate to a remote Distributor is when you get large num-bers of deadlocks on your publishing server or whenever operations in EMseem to lock, especially when you are attempting to administer replication.

For now we will be clicking Next to move to the Specify SnapshotFolder dialog box (Fig. 2.4).

Figure 2.4Specify SnapshotFolder dialog box

This dialog box allows you to place your snapshot files in a specificfolder or drive. Notice that the suggested folder location is in the form of a

Installing Replication 39

Page 6: A Guide to SQL Server 2000 Transactional and Snapshot Replication

UNC (Universal Naming Convention) using the administrative share C$.You would want to place your snapshot folder location on another drivefor performance reasons (snapshot generation can be IO intensive), if youare using ftp instead of UNCs, or for space reasons. Space is typically anissue if you are replicating very large tables.

If you chose not to use the default security model replication runsunder, you might want to create a shared directory (for example, shareC:\Program Files\Microsoft SQL Server\MSSQL\ReplData as ReplData, oreven ReplData$) and then you can use an account on your Subscriber thathas rights to read the ReplData share and underlying files and folders butnot your administrative share (the C$ share). For the security consciousreader, the $ in C$ and ReplData$ will make this a hidden share, i.e., thisshare will not show up in a net view \\PublisherServerName. We will becovering more about this later.

Clicking Next may give you the following dialog box (Fig. 2.5).

Figure 2.5The prompt SQL Serverwill display if it can’tverify the share.

You will get this dialog box if your machine is not connected to a net-work or if you are in a workgroup.

If you have entered your own snapshot location, check to verify thatyou have not made a typo. You will not get this prompt if you are loggedon to a network and have correctly spelled your path name.

Click Next to get the Snapshot Folder Path Verification dialog box(Fig.2.6).

Figure 2.6The prompt SQL Serverwill display if it can’tverify the share.

This is a warning about connecting to the administrative share, whichwe discussed earlier. Clicking Yes will give you the Customize theConfiguration dialog box (Fig. 2.7).

40 Chapter 2

Page 7: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Figure 2.7The Customize theConfiguration dialogbox

Typically, you will not have to make any modifications at this point.There are some instances where you might want to set the distributiondatabase properties:

• Use another name for the distribution database;

• Place your distribution database in a folder or drive other than thedefault C:\Program Files\Microsoft SQL Server\MSSQL\Data;

• Enable other Publishers to use the distribution database on this server;

• Select the authentication mode that replication will use to replicatedata from the distribution database to the Subscribers; and/or

• Enable other databases for Transactional, Snapshot, or Mergereplication.

In the above cases you would select the Yes, let me set the distributiondatabase properties, enable Subscribers, or set the Publishing settings,which we will henceforth refer to as advanced options. We will go intothese advanced options in the Distributor Properties section on page 85.

Clicking Next will bring you to the Completing the ConfigurePublishing and Distribution Wizard dialog box (Fig. 2.8).

Installing Replication 41

Page 8: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Figure 2.8The Completing theConfigure Publishingand DistributionWizard dialog box

Clicking Finish will bring you to an information window (Fig. 2.9).

Figure 2.9A progress window illustratingthe configuration steps

You have the option to cancel the progress of the installation of replica-tion on your SQL Server, and the SQL Server will rollback and recoverfrom the installation of replication. If you have any errors, you also cancheck to see at which point in the installation failed. After replication iscompletely set up on your SQL Server, you will receive the prompt illus-trated in Figure 2.10.

Figure 2.10A final dialog box

Click OK. You have finally completed setting up your SQL Server as aPublisher/Distributor. The SQL Server will then throw up another dialogbox (Fig. 2.11) informing you that it has added another folder or node toyour EM (Enterprise Manager) MMC (Microsoft Management Console),

42 Chapter 2

Page 9: A Guide to SQL Server 2000 Transactional and Snapshot Replication

called Replication Monitor. Replication Monitor administers yourPublishers, Subscribers, and replication agents.

Figure 2.11The Distributor Completiondialog box

There is also an advertisement for a node in EM called ReplicationMonitor Group. As this tool is very helpful when you have several SQLServers that are running replication, we’ll have a quick look at enabling thisat the end of this chapter on page 75.

Every time you open up EM and Click your Replication Monitor, youwill get the dialog box shown below unless you select the option Yes, auto-matically refresh Replication Monitor by polling the Distributor(Fig. 2.12).

Figure 2.12The ReplicationMonitor Refreshdialog box

If this dialog box gets too annoying, you can select Do not ask thisagain, and you will never see it again. You can set EM to refresh automati-cally or manually by right clicking Replication Monitor in EM, and point-ing to Refresh Rate and Settings, and selecting or clearing the check boxesfor the Refresh Results Pane group.

Installing Replication 43

Page 10: A Guide to SQL Server 2000 Transactional and Snapshot Replication

If you select the option to have SQL Server automatically refreshReplication Monitor, your Replication Monitor will be refreshed every10 seconds.

Hint: You might find this setting to be too short, as occasion-ally on heavily used servers, EM can become locked by all ofthe update activity going on in your distribution database.Then again, if the time period is too long, your EM won’treflect job status and failures as promptly as if it wererefreshed every 10 seconds, and it will have more informationto pore through when you manually do a refresh, resulting inmore locking. You might want to set a refresh rate of 10 min-utes and then use Replication Alerts to alert you when youhave job failures. Replication Alerts have no performanceimpact on your SQL Server.

We’ll look at setting up manual refreshes later. Right now we’ll selectDo not ask this again and No, I will manually fresh Replication Monitor.

Enabling SubscribersIf you are replicating to a remote SQL Server, in other words, if you arereplicating to a database that does not exist on your local SQL Server, youwill need to enable the remote SQL Server as a Subscriber of your localSQL Server publications.

To do this, go to the Tools menu, point to Replication, and then clickConfigure Publishing, Subscribers, and Distributors in EM (Fig. 2.1).You will then get the Publishers and Distributors Properties dialog box(Fig. 2.13).

44 Chapter 2

Page 11: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Figure 2.13The Publisher and DistributorProperties dialog box

Click the Subscribers tab (Fig.2.14).

Figure 2.14The Enable Subscribers dialogbox

Clicking the Subscribers tab will show a list of all the SQL Servers thatyou have registered in SQL Server EM. If your SQL Server does not appearhere, you can click New to register it. We will cover this in the Enable NewSubscribers section on page 48.

To enable one or more Subscribers you have two options:

• Click the check box to the left of the server name and click Apply. Bydefault, your local SQL Server (Hilary2KP, in this case) will be theonly enabled Subscriber.

Installing Replication 45

Page 12: A Guide to SQL Server 2000 Transactional and Snapshot Replication

• You can click Enable All to enable all the SQL Servers as Subscribers.There is no real performance penalty for choosing to Enable AllSubscribers; in fact it prevents you from having to go back andenable Subscribers on an as needed basis. All this option does is con-figure the Publisher to replicate to the Subscribers.

You also have the option of clicking Enable None, which will disable allenabled Subscribers and drop any subscriptions they may have with thepublications on the local SQL Server. The SQL Server will throw up mes-sage warning you about disabling a Subscriber (Fig. 2.15).

Figure 2.15The Disable EnabledSubscribers dialog box

After you have enabled your SQL Server as a Subscriber, you will noticea browse button (what looks like three dots) to the right of your SQLServer. Clicking Browse will allow you to control how your Subscriber willauthenticate with the Publisher. Clicking Browse will launch theSubscriber Properties dialog box (Fig. 2.16).

Figure 2.16The Subscriber Propertiesdialog box

The most significant option in this dialog box is Agent connection tothe Subscriber. This option is poorly understood by the SQL Server com-munity at large, so I’ll spend a little bit of time explaining it.

46 Chapter 2

Page 13: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Impersonate the SQL Server Agent or SQLAuthentication?There are two options to have your Subscriber connect to your Distributoror Publisher/Distributor:

• Impersonate the SQL Server Agent account on your Publisher

• Use SQL Server Authentication

Under most circumstances you should, if at all possible, use theImpersonate the SQL Server Agent account on your Publisher. It is agood security practice to configure your SQL Servers to use WindowsAuthentication only. However, in some circumstances (for instance whenyou are replicating over the Internet where ports used by WindowsAuthentication are blocked by all security conscious firewall administra-tors), you should use Mixed Authentication. The reason you should use theImpersonate the SQL Server Agent account on your Publisher is thatwhen the Snapshot Agent is downloading your snapshot files to theSubscriber, it has to connect to the path you defined in Figure 2.4. Thispath is by default of this form:

\\PublishingServerName\C$\Program Files\Microsoft SQLServer\MSSQL\ReplData\UNC

Notice that this is an administrator share. The $ sign renders it invisi-ble, so the share name will not show up if you issue a

net view \\ServerName

Only accounts that are in the Administrators group on the Publisherwill be able to connect to this path and download the snapshot files. Whenyou are downloading the snapshot using a push subscription, the Distribu-tion Agent will be using the SQL Server Agent account on the Publisher.

If you are downloading the snapshot using a pull subscription, theDistribution Agent will be using the SQL Server Agent account on theSubscriber. There is a similar configuration option when setting up yourpull subscription agents.

The SQL Server Authentication account is designed to be used for allother cases. These cases can be grouped into the following:

• When you are replicating to Subscribers over the internet

• When your Publisher and Subscriber are in different untrusted domains

• When your Publisher and/or Subscriber are in a workgroup, wherethe number of connections are limited

Installing Replication 47

Page 14: A Guide to SQL Server 2000 Transactional and Snapshot Replication

The Publisher will have to be configured for Mixed ModeAuthentication for SQL Authentication to be possible.

If your Subscriber is in one of the above three categories, it will beunable to connect to the distrib executable (which your Distribution Agentuses) using NT Authentication (or the Impersonate the SQL Server Agentoption). If you are using a SQL Server authentication, you may have tomodify your snapshot share name and its underlying permissions so theSQL Server agent (on the Publisher for push subscriptions and on theSubscriber for pull subscriptions) will be able to download the snapshotfiles. In some cases (e.g. untrusted domains), you will have to open up thepermissions underlying the snapshot share to the Everyone group.

It is possible to use pass-through authentication for the latter two casesas well. Pass-through authentication is where the SQL Server Agentaccounts on the Publisher and Subscriber have the same name and pass-word. The domain authentication check will be bypassed if the localauthentication mechanism detects that the account names and passwordsare the same. For more information on this, check out MicrosoftKnowledge Base article 321822.

You will be unable to use pass through authentication on your DC orPDC.

Enabling New SubscribersThe New button is considerably more interesting. You use this option toenable new SQL Server Subscribers that do not appear in the Subscribertab you see in Figure 2.14, and to enable other types of Subscribers, such as

• Microsoft Jet 4.0 MS Access databases,

• OLE DB Data Sources (Oracle, Sybase, DB2, MySQL, Visual FoxPro)databases, or

• ODBC Data Sources.

Let’s go through some examples of how to set up each type of datasource. Clicking New will display the Enable New Subscriber dialog box(Fig. 2.17).

48 Chapter 2

Page 15: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Figure 2.17The Enable New Subscriber dialogbox

Accepting the prompt for a SQL Server will bring up the same dialogbox you will see when you register any SQL Server in EM, with the excep-tion that upon completing this dialog box, your SQL Server will automati-cally be an enabled Subscriber. Notice that this applet does not discrimi-nate between versions of SQL Server. A SQL Server 2000 server can publishto any SQL 7 server. It can also replicate to a SQL 6.5 server through anODBC DSN.

Configuring an MS Access database as a SubscriberYou can replicate to local MS Access databases. To do this, click MicrosoftJet 4.0 database (Microsoft Access) in Enable New Subscriber.

This will launch the Enable Subscriber-Microsoft Jet 4.0 Database(Fig. 2.18). Notice that I have two Access linked servers already: FoodMartand Adventure Works (ADVWORKS).

Figure 2.18The Enable Subscriber –Microsoft Jet 4.0 Databasedialog box

Click Add to create a new linked server to your Access database orhighlight the existing MS Access linked server (ADVWORKS for example),enter the login and password if any, and click OK. The account you addhere is not an NT account or a SQL account, but rather the account used

Installing Replication 49

Page 16: A Guide to SQL Server 2000 Transactional and Snapshot Replication

by the MS Access database. The default MS Access account is admin withno password.

Add will launch the linked server dialog box (Fig. 2.19). If your Accessdatabase does not already exist, SQL Server will create it for you. You canhave a pre-existing Access database, which can be blank or have objects init.

Figure 2.19The Add Microsoft JetLinked Server dialog box

If you enter the incorrect password you will get an error message whilereplicating to the access database stating:

Error 7399: OLE DB provider 'Microsoft.Jet.OLEDB.4.0'reported an error. OLE DB error trace [OLE/DB Provider'Microsoft.Jet.OLEDB.4.0' IDBInitialize::Initializereturned 0x80004005: ].

In this case, you did not configure the account and password correctlywhile you were configuring this Access database as a Subscriber. Return tothe Enable Subscriber-Microsoft Jet 4.0 Database dialog box (Fig 2.18)and re-enter the account and password there.

Hint: An Access database can be a Subscriber to Transactional,Snapshot, and Merge publications. You can’t make an Accessdatabase a publisher for a Transactional or Snapshot publica-tion, but with Merge, you can create a Merge publication on aSQL Server database and then make the Access database aSubscriber, and all transactions occurring on the MergeSubscriber will be “published” or merged to the SQL Serverdatabase.

50 Chapter 2

Page 17: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Configuring an MSDE SubscriberMSDE (MicroSoft Data Engine) is a redistributable version of the SQLServer 2000. It is very similar to SQL Server, only with certain limitations:

• It does not include SQL Full Text Search.

• It is optimized for 8 simultaneous workloads. Subsequent connec-tions are throttled by a governor.

• Databases are limited to 2 GB in size.

• The Publisher and Distributor must be on the same server. MSDEdoes not permit Remote Distributors.

• An MSDE cannot be a Publisher for a Transactional publication;however, it can be a Publisher for Merge or Snapshot publications. Itcan be a Subscriber for all types of publications.

• If you use MSDE as a Publisher for a Snapshot or Merge publication,you must create the ReplData folder and then create the publication.By default you would create the ReplData folder in the C:\ProgramFiles\Microsoft SQL Server\MSSQL directory

• MSDE does not ship with EM. You must manage it through a work-station or server that has EM installed, or use stored procedures, SQLDMO, or the Replication ActiveX controls to manage it.

To enable an MSDE to be a Subscriber, you would register it in EM andthen enable it as a Subscriber, just like you would enable any other SQLServer as a Subscriber.

Configuring an ODBC data sourceODBC is a data access technology that was designed for always connectedClient-Server applications. In other words, the Client would log on to SQLServer (or another data source) at the start of a session and not log offuntil it was through, sometimes hours or days later. Although ODBC pro-vides very fast access for sequential bulk read operations, it was notdesigned for the large numbers of uses that Web applications support. Norwas it designed for NRHRS (Non Rectangular Heterogeneous Record Sets),like Exchange mail items or the Internet Publishing Provider. OLE DB didprovide these services and was designed with the Internet in mind. ODBCwas and is still very popular because it is simple to configure and test.You can create a subscription to any data source that has an ODBC driverwritten for it that meets the ODBC conformance level 1 or higher specifi-cations. This includes most of the commercial databases out there. Notevery data source with an ODBC driver can be enabled as a Subscriber.Consider the Text Driver or an Excel spread sheet. There are ODBC driversfor them, but they can’t be enabled as Subscribers.

Installing Replication 51

Page 18: A Guide to SQL Server 2000 Transactional and Snapshot Replication

To check to see if your ODBC driver is compatible for replication,download the ODBC Driver Conformance Level tool. Check out MicrosoftKnowledge Base article 279882 for more information about this tool.

For an ODBC data source to support SQL Server replication, it must

• be at least ODBC level-1 compliant, or above,

• be 32-bit, thread-safe, and for the processor architecture (Intel orAlpha) on which the distribution process runs,

• be transaction capable,

• support the Data Definition Language (DDL),

• be readable and writable, i.e. not read-only, and

• support long table names, such as MSreplication_subscriptions.

There are two steps involved in enabling a Subscriber using ODBC forreplication:

• Build a DSN.

• Enable the data source as a Subscriber.

To build the DSN you must launch the odbcad32 executable, which canbe found in %WINDIR%\System32. This program is also found in theControl Panel under the Administrator Tools and is called Data Sources(ODBC). Click Add and browse to locate your driver. If you do not findthe driver for the data source type you are trying to build the DSN for, youmust install the ODBC driver for the data source on the Publisher. Contactthe vendor for the driver.

After you have built and tested the DSN, you must then enable it as aSubscriber. To do this, click ODBC data source in the Enable NewSubscribers dialog box (Fig 2.17). The OBDC driver may then launch adriver-specific login dialog box to login to the data source. For exampleson how to set up popular RDBMSs as Subscribers using ODBC drivers,please refer to the sections below. I was hoping to provide an example ofreplicating to a PostgreSQL server, but I ran into problems using theirODBC driver. There is no OLE DB provider for PostgreSQL, and theperson supporting the ODBC driver has retired due to personal problems.I also ran into problems using other vendors’ ODBC drivers who supportPostgreSQL. If in the future I am able to enable PostgreSQL as aSubscriber, I will post instructions on how to do this on my Web site,http://www.replicationfaq.com.

Configuring an OLE DB data sourceOLE DB was the data access technology that replaced ODBC. OLE DB wasdesigned with the disconnected medium of the Internet in mind, where a data

52 Chapter 2

Page 19: A Guide to SQL Server 2000 Transactional and Snapshot Replication

source could expect large numbers of very fast connects and disconnects. OLEDB was also designed for distributed and asynchronous processing. OLE DBtends to be much faster and is much more scalable than ODBC. Microsoft’snew data access technology is ADO.Net using managed providers.

For an OLE DB provider to support replication, it must support thefollowing objects:

• DataSource object

• Session object

• Command object

• Rowset object

• Error object

To configure an OLE DB data source for replication, you must do the following:

• Build a linked server.

• Enable the linked server as a Subscriber.

You have two options to build a linked server:

• the stored procedure sp_addlinkedserver• Enterprise Manager (EM)

Before you can build a linked server, you must ensure that the OLE DBprovider is installed on your Publisher. To do this, issue asp_enum_oledb_providers command using Query Analyzer (isqlw.exe)and look for a reference to your particular provider in the ProviderDescription column. If your OLE DB provider does not show up here, youmust install it on the Publisher. Contact the vendor for the provider. Evenif your provider does show up in this list, that is no guarantee that it is ableto provide Subscriber services. For instance, there is an Index Server/IndexingServices provider (MSIDXS), but it will not support being a Subscriber.

If your Subscriber is listed, notice the provider name. This will be the@srvproduct and @provider parameter values in the sp_addlinkedserverprocedure. The sp_addlinkedserver procedure has the following parameters:

Table 2.1 Linked Server Parameters

@server Server name

@srvproduct product name

@provider OLE DB provider name

@datasrc OLE DB datasource property

@location OLE DB location property

@provstr OLE DB provider-string property

@catalog OLE DB catalog property

Installing Replication 53

Page 20: A Guide to SQL Server 2000 Transactional and Snapshot Replication

@server@server parameter is the name of your linked server and will be the nameof your Subscriber. This is a string value.

@srvproductThe @srvproduct is the provider name obtained from thesp_enum_oledb_providers. This is a string value.

@datasrcThe @datasrc parameter is the name of the data source. Each OLE DBprovider implements this parameter differently; however, it most fre-quently is the name of your server, the DSN name, or the path to the data-base or data source. This is a string value.

@locationThe @location parameter is typically the database name or the path to thedatabase, but for most providers this parameter is optional. This is a stringvalue.

@provstrThe @provstr parameter is your provider string.

Hint: As the value of this parameter is poorly documented formost OLE DB providers I use the complete provider stringthat I would use when using this provider in VBScript orVisual Basic. I then test to ensure it works, and then removevarious portions until I determine exactly what is necessary toget this to work. Most often it is just the User ID or accountand its password. These typically must be entered as

User ID = replaccount; password=se1cure#;

Ideally, if possible use sp_addlinkedserverlogin to enter theaccount and password.

This is a string value.

@catalogThe @catalog parameter is most frequently the name of your database, andmost frequently is optional. This is a string value.

Please consult some of the examples here for samples of linked servers.

54 Chapter 2

Page 21: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Configuring Sybase Servers for Replication using ODBCYou can configure a Sybase server as a Subscriber to a Transactional orSnapshot publication. The most complex part of setting this up is creatingyour ODBC link. Please see Figure 2.20 for a screenshot of a typical ODBCconnection to a Sybase server.

Figure 2.20A typical ODBC DSN to aSybase server

In my experience, most users have a problem setting up the ODBCconnection to a Sybase server. Most of the problems are either forgettingthat the Sybase database name is case sensitive or forgetting to append theport number after the server name (i.e. ServerName, 5000) in the NetworkAddress section. 5000 is the default listening port for a Sybase server.

When you have built your ODBC DSN and tested it, go to the Toolsmenu, point to Replication, and then click Configure Publishing,Subscribers, and Distributors, select the Subscribers tab and then clickNew. Select ODBC data source and click the Sybase ODBC DSN you havejust built. In Login, enter the account you will be using to connect toSybase and then enter the password and confirm it. Sybase currently usesSQL Authentication.

When you create your publication and get to the Specify SubscriberTypes, ensure that you use Heterogeneous Data Sources.

Installing Replication 55

Page 22: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Configuring Sybase Servers for Replication Using OLE DBThe OLE DB providers in general offer better performance than therespective ODBC drivers. There are two key elements to setting up the OLEDB provider for Sybase:

• Building your IDS file

• Building your linked server

The Sybase IDS file is similar to a DSN, only it is a text file that isdeposited by default in your C:\Sybase\oledb directory (your location mayvary). To build your IDS file, open a command prompt and navigate toC:\Sybase\oledb (your location may vary), and run Sybase ConfigurationManager, which is an executable called sydaadm.exe.

After you open Sybase Configuration Manager, select the menuoption File and point to New and then click Data Source. You will then geta dialog box that allows you to name your data source. Enter the name youwish to use and then click Set Up Data Source. Figure 2.21 is a screenshotof what a configured OLE DB Data Source would look like for Sybase.Click Apply and Close to write your new IDS file for your OLE DB Sybasedata source.

Figure 2.21A configured OLE DB DataSource for a Sybase Server

Once you have configured your IDS, you must build your linked server.There are two ways to do this: through the sp_addlinkedserver procedureand through EM.

To add a Sybase linked server using sp_addlinkedserver, you need toissue the following command:

56 Chapter 2

Page 23: A Guide to SQL Server 2000 Transactional and Snapshot Replication

sp_addlinkedserver @server ='NameOfYourLinkedServer',@srvproduct='Sybase.ASEOLEDBProvider',@provider = 'Sybase.ASEOLEDBProvider',@datasrc= 'Name_Of_Your_IDS_File',@provstr='User ID=ReplAccount;Password=se1cure#;',@catalog='Subscriber_Database_On_Sybase_Server'

When entering the name of your data source, make sure you only enterthe file name, not the extension. So if your IDS file looks like Connect.IDS,you would enter Connect for the name of your @datasrc parameter. Alsomake sure you customize the @provstr parameter for your user id andpassword, and the @catalog for your Subscriber database on the Sybaseserver. You can also leave the @provstr parameter blank and configure theaccount using the sp_addlinkedsrvlogin. Here is statement to add a linkedserver:

sp_addlinkedsrvlogin @rmtsrvname='SybaseServerName',_@useself='False',@locallogin=null,@rmtuser=_'SybaseAccount',@rmtpassword='SybaseAccountPassword'

You can also use EM create a linked server. To do this, connect to yourserver, expand your server, expand the securities folder, right click LinkedServers, and point to New Linked Server (Fig.2.22).

Figure 2.22New Linked Server

In the New Linked Server text box, enter the name you wish to use foryour Sybase Subscriber. In the Provider Name list, select Sybase ASE OLEDB Provider. If the Sybase ASE OLE DB Provider does not appear in thedrop down list, the provider is not installed on your Publisher, and you willneed to install it. You can obtain it from the Sybase Web site.

Installing Replication 57

Page 24: A Guide to SQL Server 2000 Transactional and Snapshot Replication

In the Product Name text box, enter Sybase.ASEOLEDBProvider. In theData Source text box, enter the name of your IDS file. Only enter the filename; do not enter the extension or the directory it is in. So if your IDS fileis called test.IDS and is in your C:\Sybase\oledb directory (your locationmay vary), merely enter “test” in the Data Source text box (Fig. 2.23).

Figure 2.23Configuring a linked server forSybase using the Sybase OLEDB provider

In the Security tab, select Be made using this security context, andenter the Sybase account and password. You could also enter this in theprovider string text box, but then this would be visible to anyone.

Sybase does not support a SQL Server replicating tables with hyphensin them. So if you are replicating hyphenated tables from a SQL Server toSybase, you will have to create your articles with different destination tablenames on the Subscriber.

When you create your publication and get to the Specify SubscriberTypes, ensure that you use Heterogeneous Data Sources (Fig. 2.34).

58 Chapter 2

Page 25: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Figure 2.24The SpecifySubscriber Typesdialog box

Configuring Oracle for Replication using the MicrosoftODBC Driver for OracleThere are two ODBC drivers for Oracle 9i, those from Microsoft (referredto as the Microsoft ODBC driver for Oracle) and those from Oracle(referred to as the Oracle ODBC driver). Both drivers support replication,and there is debate as to which one works the best. On the Microsoft SQLServer replication newsgroup, the consensus seems to be that the Microsoftdriver performs better; however, some users do advocate the Oracle driv-ers, complaining about the instability of the Microsoft drivers. My experi-ence, and that of others, is that the Microsoft drivers are more stable, and Iwonder if the choice doesn’t boil down to personal preference or prejudice.What makes the Microsoft ODBC drivers for Oracle the better choice is thefact that Microsoft supports replicating to Oracle using the MicrosoftODBC driver for Oracle. We’ll be looking at configuring replication withboth drivers. First we’ll look at the Microsoft ODBC driver for Oracle. Toconfigure the Microsoft ODBC driver for Oracle you need the following:

• The name of your Oracle server. I use the Oracle Net Manager toobtain this information.

• An account that has rights to create objects on the Oracle database,preferably the SYSTEM account, and its password.

• The Oracle client installed on the Publisher.

• The name of the Oracle database you are replicating to.

Figure 2.25 is what your Oracle ODBC connection would look likeusing the Microsoft ODBC driver for Oracle.

Installing Replication 59

Page 26: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Figure 2.25Configuring the Microsoft OracleODBC driver

Here I am using the Oracle SYSTEM account to connect with, and myOracle server’s name is NAME. When you have built your ODBC DSN andtested it, open up EM, and on the Tools menu, point to Replication, andthen click Configure Publishing, Subscribers, and Distributors, select theSubscribers tab, and then click New. Select ODBC data source, and clickthe Oracle ODBC DSN you have just built. In the Login section, enter theaccount you will be using to connect to Oracle, and then enter the pass-word and confirm it.

When you create your publication and get to Specify SubscriberTypes, ensure that you use Heterogeneous Data Sources.

Configuring Oracle for Replication using Oracle ODBCDriverTo configure an ODBC DSN to an Oracle server using the Oracle ODBCDriver, you need the following:

• The Oracle client installed on your Publisher.

• The TNS Service Name.

• An account that has rights to create objects on the Oracle database,preferably the SYSTEM account, and its password.

Figure 2.26 is what your ODBC DSN would look like using the OracleODBC driver.

60 Chapter 2

Page 27: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Figure 2.26An OracleODBC DSN

In this case, our Oracle TNS Service Name is NAME, and the User ID Iam connecting to Oracle with is SYSTEM.

When you have built your ODBC DSN and tested it, in EM go to theTools menu, point to Replication, and then click Configure Publishing,Subscribers, and Distributors, select the Subscribers tab, and then clickNew. Select ODBC data source, and locate the Oracle ODBC DSN youhave just built. In Login, enter the account you will be using to connect toOracle, and then enter the password and confirm it.

When you create your publication and get to the Specify SubscriberTypes, ensure that you use Heterogeneous Data Sources.

Configuring Oracle for Replication using Oracle OLE DBThe Microsoft and Oracle OLE DB providers offer better performancethan the ODBC drivers. Again, there is no clear consensus as to whichprovider is superior. Likewise, I am not sure why some DBAs prefer to usethe ODBC driver over the OLE DB provider when creating their OracleSubscriber. To me, the natural choice is OLE DB. To create a Subscriber toan Oracle server using Oracle OLE DB, you must create a linked server toOracle. To create the linked server you must have the following:

• The name of your Oracle server.

• The account you wish to connect to Oracle with and its password.

• The Oracle Client installed locally on the Publisher.

• The name of the user database on the Oracle Server you wish toreplicate to.

Figure 2.27 is what your Oracle linked server would look like when youare using the Oracle OLE DB provider.

Installing Replication 61

Page 28: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Figure 2.27A linked server using the OracleOLE DB provider

In the drop down list Provider Name, select Oracle Provider for OLEDB. In Product name, enter Oracle. In the Data source, enter the name oryour Oracle server. In the Security tab for your linked server, select the bemade using this security context and enter the name of the account youwish to access Oracle with.

When you have built your Oracle linked server, test it by expandingyour linked server and clicking the Tables node. Your linked server shouldconnect to your Oracle server and display a list of tables in your database.Then, in EM, go to the Tools menu, point to Replication, and then clickConfigure Publishing, Subscribers, and Distributors, select theSubscribers tab, and then click New. Select OLE DB data source, andselect the Oracle OLE DB linked server you have just built. In the Loginsection, enter the account you will be using to connect to Oracle, and thenenter the password and confirm it.

When you create your publication and get to the Specify SubscriberTypes, ensure that you use Heterogeneous Data Sources.

Configuring Oracle for Replication using MicrosoftOLE DBTo create a Subscriber to an Oracle server using the Microsoft OLE DB,you must create a linked server to Oracle using the Microsoft OLE DBprovider. To create the linked server you must have the following:

• The name of your Oracle server.

• The account you wish to connect to Oracle with and its password.

62 Chapter 2

Page 29: A Guide to SQL Server 2000 Transactional and Snapshot Replication

• The Oracle Client installed locally on the Publisher.

• The name of the user database on the Oracle Server you wish toreplicate to.

Figure 2.28 is what your Oracle linked server would look like when youare using the Microsoft OLE DB provider for Oracle.

Figure 2.28A linked server using theMicrosoft OLE DB provider forOracle

In the drop down list Provider Name, select Microsoft OLE DBProvider for Oracle. In the Product name, enter Oracle. In Data source,enter the name of your Oracle server. In the Security tab for your linkedserver, select the be made using this security context and enter the nameof the account you wish to access Oracle with.

When you have built your Oracle linked server, test it by expandingyour linked server and clicking the Tables node. Your linked server shouldconnect to your Oracle server and display a list of tables in your database.Then in EM, on the Tools menu, point to Replication, and then clickConfigure Publishing, Subscribers, and Distributors, select theSubscribers tab, and then click New. Select OLE DB data source, and clickthe Oracle OLE DB linked server you have just built. In the Login section,enter the account you will be using to connect to Oracle, and then enterthe password and confirm it.

When you create your publication and get to the Specify SubscriberTypes, ensure that you use the Heterogeneous Data Sources.

Installing Replication 63

Page 30: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Configuring MySQL for ReplicationIt is possible to create a MySQL server as a Subscriber to Transactional andSnapshot replication. Setting up a MySQL Database as a Subscriber is avery simple process; however, there is a bug. If your Distribution Agentstops and restarts, it will continually fail until you re-initialize yourSubscriber.

To enable MySQL as a Subscriber you must

• Install the MySQL ODBC driver, obtainable from the MySQL Web site.

• Create a DSN to your MySQL Server. Please refer to Figure 2.29 foran illustration.

• Enable a new Subscriber as a ODBC data source. Use a MySQLaccount for your DSN that has all rights associated to it (i.e. GRANTALL PRIVILEGES ON AdventureWorks* TOreplaccount@localhost).

• Locate your MySQL DSN (Data Source Name), and select it, enteringthe account name and password.

When you create your publication and get to the Specify SubscriberTypes, ensure that you use Heterogeneous Data Sources.

I have tested this with most recent versions of MySQL, including version4.0.17-nt, and tested inserts, updates, and deletes without any problems(other than the fact that you have to keep your Distribution Agent running).

Figure 2.29 is what your ODBC DSN configuration for a MySQL Serverwould look like.

Figure 2.29An ODBC DSN to aMySQL Server

I am connecting to a MySQL Server running on a UNIX server(FreeBSD), to a database called AdventureWorks, using an account calledreplaccount, to which I have assigned a password. MySQL’s sa account,called “root,” by default has no password, and the guest account is enabled.

64 Chapter 2

Page 31: A Guide to SQL Server 2000 Transactional and Snapshot Replication

In other words, any account can gain access. When you have built yourODBC DSN and tested it, go to EM and select the menu option Toolsmenu, point to Replication, and then click Configure Publishing,Subscribers, and Distributors, select the Subscribers tab, and then ClickNew. Select ODBC data source, and locate the MySQL ODBC DSN youhave just built. In Login, enter the account you will be using to connect toMySQL, and then enter the password and confirm it.

When you create your publication and get to the Specify SubscriberTypes, ensure that you use Heterogeneous Data Sources.

Configuring DB2 for Replication using ODBCDB2 is IBM’s RDBMS offering, and it is widely regarded as one of the pre-mier database systems. DB2 has been implemented on a variety of platforms:

• zOS (formerly called MVS)

• AS400

• AIX (UDB)

• Linux (UDB)

• NT (UDB)

UDB is Universal Database Server, which is a different product offeringfrom the DB2 versions that ship on zOS and AS400.

For DB2/NT, you can use the IBM ODBC driver or OLE DB provider.For the other systems, a variety of solutions exist, e.g. Shadow Direct,DataMirror, IBM’s Client Access, or Microsoft’s Host Integration Server(HIS). Interestingly enough, a merge replication solution was planned forHIS 2000, which would allow Host Systems (like DB2) to be a MergePublisher to SQL Server. You can still see the schematics for this by search-ing on “merge” in the Host Integration Server compiled help file(HIServer.chm), which ships with HIS server or client. Look for a .gif therecalled IF_HREP03.gif. With luck, this will ship in a future version of HIS.

We’ll look at using IBM’s ODBC driver and OLE DB provider to enableDB2/NT as a Subscriber. After that, we will look at how to replicate to DB2AS/400 using Client Access, which is IBM’s connectivity software to con-nect Windows clients to DB2 on the AS400 systems.

To replicate to DB2/NT using ODBC, you must configure your ODBCDSN. Figure 2.30 illustrates a configured OBDC DSN for DB2.

Installing Replication 65

Page 32: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Figure 2.30An ODBC DSNto a DB2 server

The key to getting a correctly configured DSN is having the correctDB2 server name, ALBANYDB204, in our case. After you configure yourDSN, you will have to insert the following entry in your msdb database onyour Distributor:

INSERT INTO msdb.dbo.MSdatatype_mappings VALUES('DB2/NT','nvarchar','VARCHAR',4000,4,1)

When you create your publication and get to the Specify SubscriberTypes, ensure that you use Heterogeneous Data Sources.

Configuring DB2 for Replication using OLE DBTo replicate to DB2/NT using OLE DB, you must create your linked serverusing the IBM OLE DB Provider for DB2. For the Product name, enterIBMDADB2. For Data Source, enter the name of your server running DB2,and for the Provider String, enter the name of your ODBC connection likethis:

DSN=DB2_ODBC_DSN

Your DB2 linked server will read your ODBC DSN for DB2 to obtainconfiguration information, but it will use the IBM OLE DB provider.Figure 2.31 illustrates this.

66 Chapter 2

Page 33: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Figure 2.31Your DB2 linked server

Let me be perfectly clear. If you configured an ODBC DSN to DB2/NTcalled Test, the provider string would be

DSN=Test

and the IBM OLE DB Provider for DB2/NT would be used, but itwould be configured using the parameters in the ODBC DSN named test.

After you configure your linked server, you will have to issue the fol-lowing entry in your msdb database on your Distributor:

INSERT INTO msdb.dbo.MSdatatype_mappings VALUES('DB2/NT','nvarchar','VARCHAR',4000,4,1)

When you create your publication and get to the Specify SubscriberTypes, ensure that you use the Heterogeneous Data Sources option.

Configuring DB2 AS/400 for Replication using ClientAccess and ODBCTo replicate to DB2 AS/400 using Client Access, you would create anotherODBC connection, this time selecting the Client Access driver. The screen-shots below were kindly provided by SQL Server MVP Allan Mitchell.Figure 2.32 illustrates the General Tab of your Client Access DSN.

Installing Replication 67

Page 34: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Figure 2.32The General tab ofthe Client AccessDSN

Notice that you have to select the correct system in the System drop downbox. Then in the Server tab (Fig. 2.33) ensure that you have the correctlibrary listed.

Figure 2.33The Server tab ofthe Client AccessDSN

Using a Remote DistributorThere are times when you will find that performance on your Publisher isdegraded to the point that it becomes necessary to move your Distributorto another SQL Server that will be dedicated as a Distribution server.

68 Chapter 2

Page 35: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Unfortunately there is no single quantifiable identifier to tell you whento use a Remote Distributor. Rather it is when the number of deadlocks onPublisher start to become unacceptable to the applications using this data-base. Another sign is when you can’t manage your publications throughEM or TSQL because of locking problems.

To create a Remote Distributor, connect to your Distribution serverusing EM and install Replication by going to the Tools menu, point toReplication, and then click Configure Publishing, Subscribers, andDistributors and follow the defaults for making this SQL Server its ownDistributor. After you have installed Replication, go back to your Publisher,and select the Tools menu, point to Replication, and then click ConfigurePublishing, Subscribers, and Distributors, and this time select thePublishers tab (Fig. 2.34).

Figure 2.34Configuring a Publisher to use aRemote Distributor

In this case, the Distribution Server is Hilary2kp. I want to enable theAlbanySQL04 to use Hilary2kp as its Distribution Server, so I click thecheck box to the left of the server AlbanySQL04.

When you enable the Publisher to use the local Distributor, you will geta warning that the Distributor Server is password protected (Fig. 2.35). Bydefault, the Distributor Server is password protected so that only otherDBAs who know the password can have Remote Publisher use the localDistributor server.

Installing Replication 69

Page 36: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Figure 2.35Warning dialog box thatthe Distributor server ispassword protected

After you have enabled a Remote Publisher to use the LocalDistributor, you have the option to configure the Publisher’s properties byclicking Browse (…) to the right of the Publisher’s name. Clicking Browsewill launch the Publisher Properties dialog box (Fig. 2.36). You have theoption in this dialog box to configure where the snapshot folder is on yourPublisher, and how the Publisher will connect to the Distributor. For mosttopologies you will be using Impersonate the SQL Server Agent on thepublisher. However, in some cases, you will want to use SQL authentica-tion. These cases are typically where NT Authentication (Impersonate theSQL Server Agent on the publisher) won’t work, such as

• having a Publisher and Distributor in different untrusted domains,

• having a Publisher and Distributor in a workgroup, or

• having a Publisher and Distributor running across the Internet,keeping in mind the security risks associated with doing this.

Please refer to page 47 for a more complete description of these cases.When you use SQL Server authentication, the sa password will be the

sa password of the Distributor Server, not the Publishing Server. If youenter the incorrect password, you may get the following error messagewhen you try to add articles to your publication:

Error 50007: xp_execresultset: unable to get a boundconnection back to server.

Also notice in Figure 2.36 that you can specify the option that Thispublisher requires a password to establish a link to the Distributor.Some DBAs prefer to password protect their Distributor servers so thatonly other DBAs who know the password can use it. Your Distributionserver will be password protected by default.

70 Chapter 2

Page 37: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Figure 2.36Configuring your PublisherProperties when using a RemoteDistributor

Notice that there is a drop down box for the Distribution databasetext box in Figure 2.36. You can have each Remote Publisher publish to adifferent distribution database on the Distributor. For very high through-put systems, the replication metadata tables on the Distributor can get verylarge, and there are some advantages to giving each Publisher its own dis-tribution database. After enabling your Publisher to use the localDistributor server, you must connect to your Publisher using EM, and thenselect the Tools menu, point to Replication, and then click ConfigurePublishing, Subscribers, and Distributors. Click Next on the Welcome tothe Configure Publishing and Distribution Wizard splash screen, and youwill then get the Select Distributor dialog box (Fig. 2.37). Notice that wehave the option of having the server (AlbanySQL04) use its own distribu-tion database, but in this case, we are going to use the Remote Distributor(Hilary2kp). Click Next.

Installing Replication 71

Page 38: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Figure 2.37Selecting a RemoteDistributor

You will then get a prompt for the Administrative Link password(Fig. 2.38). If you have forgotten the Administrative Link password, youcan reset it. Go to the Tools menu, point to Replication, and then clickConfigure Publishing, Subscribers, and Distributors. Enter a new pass-word in the Administrative Link password text box in the Distributor tab(Fig. 2.39). Existing Publishers using the Distributor will fail if you changethe Administrative Link password, so it’s best to treasure yourAdministrative Link password.

Figure 2.38Entering theAdministrative Linkpassword

72 Chapter 2

Page 39: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Figure 2.39Changing the AdministrativeLink password

After entering the password, click Next, and you will have the opportu-nity to customize the publication settings (Fig. 2.40).

Figure 2.40The Customize theConfiguration dialogbox

If you choose to configure the publishing settings, the wizard willlaunch the dialog Enable Publication Databases dialog box (Fig. 2.41). Thiswill allow you to enable databases on the Publisher for Merge,Transactional, or Snapshot publications.

Installing Replication 73

Page 40: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Figure 2.41The EnablePublication Databasesdialog box

Clicking Next in the dialog boxes you see in Figure 2.40 and then 2.41allows you to enable Subscribers to this Publisher.

Figure 2.42Enable Subscribersdialog box

Clicking Next in the Enable Subscribers dialog box will launch a sum-mary page of actions, and there will be a Finish button to click to completethe process. Clicking Finish will launch another dialog box that willannounce the successful completion of the wizard and the installation ofyour remote Distributor.

Migrating to a Remote DistributorMost of the time in the lifetime of your various replication solutions, youwill find that you will migrate from using a Local Distributor to a RemoteDistributor, as opposed to installing a Remote Distributor when you first

74 Chapter 2

Page 41: A Guide to SQL Server 2000 Transactional and Snapshot Replication

deploy replication. It is hard to estimate whether you should start off witha Remote Distributor. If you do have a heavily loaded SQL Server to beginwith, it is a clear choice to initially use a Remote Distributor with PullSubscribers.

Unfortunately, the way you migrate from a Local Distributor to aRemote Distributor involves dropping all subscriptions and publications,and then disabling publishing completely on the Publisher. Then on yourDistribution Server you have to configure it as a Distributor if you have notalready done so. After the Distributor is configured, enable the Publisher topublish to it, and then on the Publisher, configure the Distributor server asthe Distributor. Then recreate your publications and subscriptions, andstart up the agents.

Replication Monitor GroupReplication Monitor Group is a new feature in SQL 2000 that allows you tomonitor replication status and jobs on many servers. Essentially, it presentsto the DBA a list of all the SQL Servers that are running replication thatyou have registered. To enable it, go to the Tools menu, point toReplication, and then click Show Replication Monitor Group (Fig. 2.43).

Figure 2.43 The Show Replication Monitor Group menu item

Another folder or node entitled Replication Monitor Group will beadded to your EM MMC (Fig. 2.44).

Installing Replication 75

Page 42: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Figure 2.44The Replication Monitor Group node

You then have to add to the Replication Monitor Group the serversyou wish to monitor. To do so, right click Replication Monitor Group andclick Add Distributor to Monitor (Fig. 2.45).

Figure 2.45The Replication Monitor Group

You will then get the Add Distributor to Monitor dialog box(Fig. 2.46), which allows you to pick from the SQL Servers and/or theirinstances that you have already registered in EM. You can select multipleservers by holding down the CTRL key and clicking them with yourmouse.

Figure 2.46Adding registered servers toyour Replication MonitorGroup

76 Chapter 2

Page 43: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Clicking OK will display the server(s) you just selected in theReplication Monitor Group (Fig. 2.47).

Figure 2.47The Replication Monitor Group illustrating SQLServers being monitored

What makes Replication Monitor Group so valuable is that SQLServers that have a failed agent on them will show up with a red X onthem. If you did not have Replication Monitor Group, you would have torely on expanding every Replication Monitor Folder and looking for thesered X marks, or rely on alerts or network monitoring software to detecterrors written to the NT Event Log. Replication Monitor Group also pres-ents a lightweight object for you to manipulate your publications andreplication agents without having to drill down through all the folders thatyou would have to otherwise if you were using the SQL Server object yousee in EM.

Figure 2.48 is an illustration of what I am talking about. To see errorsin replication looking at the Server node in EM, you must expand the SQLServer, and then expand Replication Monitor, and click Agents folder, andthen you can see the error. In Replication Monitor Group, the error isplainly visible as soon as you expand it to display all the servers.

Installing Replication 77

Page 44: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Figure 2.48The Replication Monitor Group illustratinga SQL Server with a failed job

This visual exception monitoring and the ability to quickly access yourreplication agents will pay dividends when you have many SQL servers youare monitoring.

Replication MonitorBefore we leave the replication server setup, there are a few more things tolook at. If you right click Replication Monitor, you will notice the followingoptions:

• Performance Monitor

• Distributor Properties

• Refresh Rate and Settings

• Select Columns

• Show Anonymous Subscribers

We’ll look at each of these options in detail in the following sections.

78 Chapter 2

Page 45: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Performance MonitorThe Performance Monitor option is used to launch Performance Monitorwith Replication Counters. As your replication topology grows, you mayrun into performance problems and have to resort to PerformanceMonitor to help identify bottlenecks. The counters supplied in this dialogbox are below:

• SQL Server: Replication Agents: Log Reader

• SQL Server: Replication Agents: Distributor

• SQL Server: Replication Agents: Merge

• SQL Server: Replication Agents: Snapshot

These counters merely report the number of agents of each type running.These replication counters will only be on your system if you selected

the Server Component, Performance Counters sub-component wheninstalling SQL Server.

You can add more Performance Monitor Counter and Objects to thisdefault msc (the MMC Performance Monitor configuration file). To do thisclick Start, click Run and then type perfmon and hit enter. WhenPerformance Monitor (perfmon) launches, go to the menu item Consoleand click Open and navigate to C:\Program Files\Microsoft SQLServer\80\Tools\Binn and open up the perfmon.msc file. You can then addthe Performance Objects and Counters you that are important to you, andthen select the menu item Save. When you launch Performance Monitoragain by right clicking Replication Monitor and clicking PerformanceMonitor, these Performance Objects and Counters will be loaded bydefault.

I find the Performance Object SQL Server Replication Dist with theCounter Dist:Delivery Latency to be one of the more helpful counters. Ialso monitor overall system CPU utilization (Process:%ProcessorTime:_Total, and Process:%Processor Time:sqlservr), server work queues(Server Work Queues:Queue Length:0), and the number of page faults(Memory:Page Faults per sec).

Here is a complete list of Replication Performance Objects available toyou:

• SQLServer: Replication Agents:Running – The number of replicationagents currently running

• SQLServer: Replication Dist:Dist:Delivered Cmds/sec – The numberof commands per second delivered to the Subscriber

• SQLServer: Replication Dist:Dist:Delivered Trans/sec – The numberof transactions per second delivered to the Subscriber

Installing Replication 79

Page 46: A Guide to SQL Server 2000 Transactional and Snapshot Replication

• SQLServer: Replication Dist:Dist:Delivery Latency – The currentamount of time, in milliseconds, elapsed from when transactions aredelivered to the Distributor to when they are applied at theSubscriber

• SQLServer:Replication Logreader: LogReader: Delivered Cmds/sec –The number of commands per second delivered to the Distributor

• SQLServer:Replication Logreader: LogReader: Delivered Trans/sec –The number of transactions per second delivered to the Distributor

• SQLServer:Replication Logreader: LogReader: Delivery Latency –The current amount of time, in milliseconds, elapsed from whentransactions are applied at the Publisher to when they are delivered tothe Distributor

• SQLServer:Replication Merge:Conflicts/sec – The number of con-flicts per second occurring during the merge process

• SQLServer:Replication Merge:Downloaded Changes/sec –The number of rows per second merged from the Publisher to theSubscriber

• SQLServer:Replication Merge:Uploaded Changes/sec – The numberof rows per second merged from the Subscriber to the Publisher.

• SQLServer:Replication Snapshot:Snapshot Delivered Cmds/sec –The number of commands per second delivered to the Distributor

• SQLServer:Replication Snapshot:Snapshot Delivered Trans/sec –The number of transactions per second delivered to the Distributor

Performance monitoring is widely described as an art and not a sci-ence. I don’t really want to discuss the validity of this statement in thisbook. However, what performance monitoring boils down to is identifyingwhat process or hardware component is the bottleneck in your system, orto put it another way, which hardware component or process is degradingoverall performance on your system.

The way to first approach tuning a system is to realize that it takes thesystem several orders of magnitude longer to access hardware resources ascompared to resources in memory. For instance, when I was a child, it wascommon wisdom that data from memory is read 1000 times faster thandata read from disk. With the advances in CPU speed and performanceand disk speed, I am not sure if this ratio still holds true, but the perform-ance hit is still there today. So you should be analyzing your system to min-imize as much hardware interaction as possible.

This normally means you first look at your memory usage patternsbecause, ideally, your system will be able to cache everything in memory. Inthese days when RAM prices are nose diving, you can afford GBs of RAM

80 Chapter 2

Page 47: A Guide to SQL Server 2000 Transactional and Snapshot Replication

on your systems, but still this is not enough to hold the ballooning data-base sizes. It is not uncommon to work with databases that are hundreds ofGB in size.

The NT OS family (NT, Win2k, WinXP, Win2003) and all modern OSshave a memory management technique that creates what is called virtualmemory. On NT, Win2x and WinXP, each process running on yourmachine thinks it has 4 GB of RAM available to it. This 4 GB of virtualmemory is further subdivided into two 2-GB blocks: 2 GB for the userdata, and 2 GB for the system data. The 2 GB available for system data isshared between all system processes and the 2 GB of user data is accessibleby your programs. So a process like a SQL Server will store database pagesin cache using the 2 GB of user memory space, and use the 2 GB of systemdata to communicate with other NT processes. There are switches that youcan set in your boot.ini file to change this memory allocation so that 3 GBof memory is accessible by user processes on NT 4.0 Enterprise and Win2xAdvanced Server products. There is also a /PAE switch that allows Win2xAdvanced Server and above to access more memory. Consult Kb articles274750 and 283037 for more information on this.

You should be asking yourself the question, “But my system only has256 MB of RAM on it. How can I access the 2 GB of RAM?” Keep in mindthis is virtual memory, not physical memory. Your system allows each userprocess to access up to 2 GB of virtual memory. However, OS engineersrealize that at any one time slice, your user process will not need all 2 GB ofmemory; it may need 64 KB or 345 KB (just to throw out some numbers)at any one time. The Virtual Memory Manager will keep recently accessedprocess data in RAM, and the rest of the user data will be stored in a physi-cal file called the Page File (pagefile.sys) in blocks of data called pages. TheVirtual Memory Manager will flush to disk pages that haven’t been recentlyused in the Page File, keeping the most recently accessed pages in RAM. Onwell-tuned systems, the Virtual Memory Manager will only flush pages todisk every minute or so. On poorly tuned systems, the Virtual MemoryManager will be spending all its time paging to disk. The reason for this isthat memory demands have forced it to page data that has been recentlyaccessed to disk, and then it has to read it again as the user process requiresit again. The act of hitting the disk so frequently causes a performance hit(remember our maxim “It takes a system 1000 times longer to access dataoff a disk than off memory.”), which slows your system down even further,causing your system to have to spend more memory resources managingthe page file, and resulting in more page file flushes.

On systems with insufficient memory, the Virtual Memory Managerwill have to rely on the Page File stored on your physical disk to storememory pages. Suppose you don’t have enough CPU on your system. For

Installing Replication 81

Page 48: A Guide to SQL Server 2000 Transactional and Snapshot Replication

instance, say your system runs a Web server that has to crunch a lot of ASPcode to render the ASP pages as HTML and send them back to your clients.In this case, ASP page requests start getting queued along with the userdata to fulfill the page request. Soon your system spends more time manag-ing the queue of requests and less time crunching the ASP pages. What thismeans for your system is that your page file will be flushing these queuedpage requests back to disk.

We use Performance Monitor to identify such bottlenecks. Here aresome of the ones I normally add to my default Performance Monitor man-agement console for replication, along with their descriptions:

• Memory:Available Bytes – The amount of physical memory avail-able to processes running on the computer, in bytes. The VirtualMemory Manager may allocate 2 GB of memory space to userprocesses, but not all of this space is taken. Likewise, not all of thephysical RAM is in use. Available Bytes is a measure of how muchphysical RAM is not in use. Consider Available Bytes as the amountof space available for the Page File to use before having to resort topage faults. Page faults occur when the request for a page could notbe found in RAM and has to be requested from the disk (the PageFile). When Available Bytes goes below 5% to 10%, you are runningout of available memory.

• Memory:Cache Bytes – The total number of bytes that the Systemprocess is currently using. Just like user processes, the VirtualMemory Manager will swap out System data to the page file. Thiscounter has more meaning when used in conjunction with theMemory:Cache Faults per second. A high value of Cache Faults persecond indicates that you should adjust your cache size.

• Memory:Cache Faults per second – The number of faults that occurwhen a page sought in the file system cache is not found there andmust be retrieved from elsewhere in memory (a soft fault) or fromdisk (a hard fault). The file system cache is an area of physicalmemory that stores recently used pages of data for applications.Cache activity is a reliable indicator of most application I/O opera-tions. This counter counts the number of faults, without regard forthe number of pages faulted in each operation.

• Memory:Pages/sec – The number of pages read from or written todisk to resolve hard page faults. Hard page faults occur when aprocess requires code or data that is not in its working set or else-where in physical memory and must be retrieved from disk. Thiscounter was designed as a primary indicator of the kinds of faultsthat cause system-wide delays. It is the sum of Memory:PagesInput/sec and Memory:Pages Output/sec. It is counted in numbers of

82 Chapter 2

Page 49: A Guide to SQL Server 2000 Transactional and Snapshot Replication

pages, so it can be compared to other counts of pages, such asMemory:Page Faults/sec, without conversion. It includes pagesretrieved to satisfy faults in the file system cache (usually requested byapplications) and non-cached mapped memory files. This counterdisplays the difference between the values observed in the last twosamples, divided by the duration of the sample interval. More than 5pages/seconds is an indication of memory bottlenecks.

• Memory:Page Reads/sec – The number of times the disk was read toresolve hard page faults. If you have a large number of PagesReads/sec used in reading as opposed to writing, your system is seri-ously bottlenecked.

• Memory:Pool Paged Bytes – Recall that of the 4 GB of virtualmemory available to any user process, 2 GB are accessible for userdata, and 2 GB are available as shared memory address space bysystem processes. Some of this data is available to be paged to disk.This area is termed Pool Paged Bytes.

• Memory:Pool Nonpaged Bytes – The number of bytes in the nonpagedpool that cannot be paged to disk and must remain in physical memory.

• Memory:Page Faults/sec – The number of page faults per second.This counter includes both hard faults (those that require disk access)and soft or Transition Faults (where the faulted page is found else-where in physical memory and not in the page file on disk; thesetypes of page faults are called Transition Faults). Most processors canhandle large numbers of soft faults without consequence. However,hard faults can cause significant delays. This counter displays the dif-ference between the values observed in the last two samples, dividedby the duration of the sample interval.

• Memory:Transition Faults/sec – The Virtual Memory Managermarks memory pages to be flushed to disk; the page is not immedi-ately flushed to disk. Sometimes the page will be requested again bythe Virtual Memory Manager before it is flushed to disk. Suchrequests are termed soft page reads or Transition faults. The PageFaults per second contains not only hard page faults but also softpage faults. Transition Faults per second can help you to determinethe real number of hard page faults.

• Paging File:% Usage object (_Total) – The amount of the Page Filein use in percent.

• Server:Pool Paged Bytes – The number of bytes of pageable com-puter memory the server is currently using. Can help in determininggood values for the MaxPagedMemoryUsage parameter. If you tunethis value, more memory will be available to your Pool Paged Bytes.

Installing Replication 83

Page 50: A Guide to SQL Server 2000 Transactional and Snapshot Replication

• Server:\Pool Nonpaged Bytes – The number of bytes of non-page-able computer memory the server is using. This value is useful fordetermining the values of the MaxNonpagedMemoryUsage valueentry in the Windows NT Registry. If you tune this value, morememory will be available to your Pool Paged Bytes.

• Processor:% Processor Time (all instances) – The percentage oftime that the processor is executing a non-Idle thread. This counterwas designed as a primary indicator of processor activity. It is calcu-lated by measuring the time that the processor spends executing thethread of the Idle process in each sample interval, and subtractingthat value from 100%. (Each processor has an Idle thread that con-sumes cycles when no other threads are ready to run). It can beviewed as the percentage of the sample interval spent doing usefulwork. This counter displays the average percentage of busy timeobserved during the sample interval. It is calculated by monitoringthe time the service was inactive, and then subtracting that valuefrom 100%. Percentage Processor Time should be less than 75%.

• System:Processor Queue Length (all instances) – The number ofthreads in the processor queue. There is a single queue for processortime even on computers with multiple processors. Unlike disk coun-ters, this counter counts ready threads only, not threads that are run-ning. A sustained processor queue of greater than two threads gener-ally indicates processor congestion. This counter displays the lastobserved value only; it is not an average. This counter indicates thatprocesses are waiting for resources to be available. If other countersreveal that there are no hardware bottlenecks, you need to concen-trate on improving your processor performance possibly by addinganother processor, increasing the L2 cache, or migrating to anothermachine with more horsepower.

So now you are armed with counters to help you to identify bottlenecksin your system. Where do you go from here? How do these counters relateto replication? You will find on heavily used systems, especially when youare doing filtering, that the performance hit of replication can degradeoverall performance. Most significant is the increase in ProcessorUtilization (Processor:% Processor Time [all instances]). All this counterreveals is that your system is busier, or doing more work. Is this a badthing? No, unless your Server Work queues counter is climbing signifi-cantly. Before you rush out and by a Quad or replace all your processorswith ones with higher CPU speeds, ask your self if perhaps the problem is amemory bottleneck or a disk bottleneck, or can’t be solved by using a lesscomplex filter, or perhaps by migrating to pull subscriptions.

84 Chapter 2

Page 51: A Guide to SQL Server 2000 Transactional and Snapshot Replication

After installing replication, you may also notice that your system ispaging more than normal. Expect a greater amount of disk activity, espe-cially when generating snapshots, to cause this. But is this disk activitycausing a bottleneck? The ratio of Page Fault Reads/sec to Page Faults/sec isan indication that you should add memory.

The above counters can help you to identify where the bottlenecks lie.The temptation can be to throw hardware at the problem, whereas therecould be more cost-effective solutions to the problem, like adding memory.

You may also find that by moving to pull subscriptions, which run atstaggered intervals, the load on your Distributor will decrease, and overallperformance will increase.

A Publisher, Subscriber, and Distributor server should be tuned as anetwork application. To do this, right click the My Computer icon, pointto Properties, click the Advanced tab, click Performance Options, andselect Applications.

Distributor PropertiesThe Distributor Properties menu item allows you to fine tune your distri-bution database or even to locate the distribution database on anotherserver or drive. Selecting the menu option for Distributor Properties willlaunch the Publishers and Distributor Properties dialog box (Fig. 2.49).

Figure 2.49Distributor Properties tab

This dialog box is equivalent to the option to set the AdvancedProperties you would see in the Customize the Distributor Propertiesdialog box (Fig. 2.7) if you were to select Yes, let me set the distributiondatabase properties, enable Publishers, or set the publishing settings.

Installing Replication 85

Page 52: A Guide to SQL Server 2000 Transactional and Snapshot Replication

The Administrative link password allows you to password protect yourdistribution database. There is no built-in NT Authentication analog forthis option. When you enable Remote Publishers to publish to your distri-bution database, they will have to supply the Administrative link passwordat that time. We will discuss the Agent profiles at the end of this section.

Clicking Properties will allow you to configure some aspects of yourdistribution database and Distributor properties (Fig. 2.50).

Figure 2.50Distribution DatabaseProperties

The settings that you can modify here are Transaction retention andHistory retention. Transaction retention means that transactional datawill be retained no more than 72 hours before being deleted from the repli-cation system tables (MSrepl_transactions and MSrepl_commands). Bydefault, the distribution clean up wizard will clean up the transactions thathave been replicated to the Subscribers every 10 minutes. The values forTransaction retention and History retention should be larger than thevalue of the Subscription expiration period (right click on your publica-tion and select publication properties, and look in the subscription expira-tion section). If all three of these settings don’t match, you may find yoursubscriptions expire prematurely.

If you are doing custom programming where you are rolling your ownreplication agents, you may want to store the transactions, which would beotherwise flushed, for a longer time period for debugging or logging. Youcan set this retention time period here. This option is not valid when usingsnapshot replication or merge replication. Some DBAs like to use thisoption as a measure of disaster recovery. We cover this in Chapter 10, onTroubleshooting.

86 Chapter 2

Page 53: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Hint: Some DBAs prefer to modify the “At least value” to sev-eral days, which will make your MSrepl_transactions andMSrepl_commands tables very large. However, if a Subscriberhas to be restored from yesterday’s backup, the DistributionAgent will backfill the missing transactions to sync up theSubscriber using the commands stored in the MSrepl_transac-tions and MSrepl_commands tables. If these commands hadbeen flushed, you would have to do a resynchronization.

The History retention period is by default 2 days, whichmeans historical information is stored for 2 days before beingpurged from MSdistribution_history. You might want tochange this value to 3 or 4 days to account for long weekends,so that when you come back into the office, you can see whathas failed or succeeded over the weekend, and to prevent pre-mature subscription expiration.

I find this handy as I capture this information to determine overallthroughput per Subscriber over a weekend, and detect problem links wherelow latencies are required to meet SLAs.

Notice also that all Publishers that can publish transactions to thisdatabase are listed in These Publishers use this database list box. In Figure2.50, the local Publisher, Hilary2kp, and Hilary2kp\test (another instance)are listed as Publishers.

Clicking OK returns us to the opening tab for the DistributionProperties tab.

The New button allows you to create another distribution database.Existing publications using the old distribution database will have to bedropped and moved to the new distribution database. New Publishers(note that I mean a new publication server, not new publications) can pub-lish to this new distribution database if you enable them in the Publisherstab (Fig. 2.34). If they were already enabled before you created the new dis-tribution database, they will publish to the old distribution database.

It is entirely possible to create a different distribution database for eachremote Publisher.

If you run out of space on your existing distribution database, youmust resort to adding a new file group to your existing distribution data-base. Use a command similar to the one below:

ALTER DATABASE [distribution] ADD FILE(NAME =N'distribution_1_Data', FILENAME = N'd:\SQLData\dist.mdf', SIZE = 1, FILEGROWTH = 10%)ALTER DATABASE [distribution] ADD LOG FILE(NAME =N'distribution_1_Log', FILENAME = N'd:\SQLData\dist.ldf', SIZE = 1, FILEGROWTH = 10%)

Installing Replication 87

Page 54: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Click New to launch the Distribution Properties dialog box (Fig 2.51)which allows you to create another distribution database on another drive,or another folder, for that matter.

Figure 2.51The Distribution DatabaseProperties tab

Notice here we can name the distribution database to anything (thedefault will be distribution1) and we can place the data file and the log fileswherever we want. The data file should be placed on a RAID 5, and the logfile on a RAID 1, 10, or 01 array. The new distribution database will havethe same retention periods for the transactions and the history as the origi-nal distribution database.

Agent ProfilesThe Agent Profiles button allows you to set what profile you want yourreplication agents to run under. A profile is a named group of settings thatyou can apply to an agent. Each profile encapsulates a set of functionality,and you have the ability to build your own. For instance, let’s look at theMerge Agent’s profiles. The Merge Agent has profiles for

• a default setting,

• a high volume setting,

• two data validation profiles,

• a slow link profile for low bandwidth links,

• a verbose profile for debugging purposes, and

• a Windows Synchronization Manager profile.

Figure 2.52 illustrates the Agent Profile dialog box, showing all the tabsfor the various replication agents tabs.

88 Chapter 2

Page 55: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Figure 2.52The Agent Profile dialogbox

Notice how you can apply the profile that you select to all existingagents, by selecting Change all existing Distribution Agents to use theselected profile. The new profile will be active when the agent is stoppedand restarted.

Clicking View Details (Fig. 2.53) will allow you to examine the variousconfiguration settings for this profile. The New Profile button will allowyou to build a new profile.

Figure 2.53The Agent Profile Details dialogbox

The View Details button will allow you to check the settings of a profile.Notice the –LoginTimeout value of 15 seconds. This is acceptable forDistribution agents that are connecting with Publishers, Distributors, orSubscribers that are not under load, but you will find that on some loadedPublishers, Distributors, or Subscribers (especially Subscribers that are con-necting to the Distributor over slow, low bandwidth or lossy links), you will

Installing Replication 89

Page 56: A Guide to SQL Server 2000 Transactional and Snapshot Replication

want to adjust this value to 60 or 120 seconds. To do this, you might want toset up a Slow Link Profile. Click New Profile in the Agent Profiles dialogbox (Fig. 2.52). This will launch the New Profile dialog box (Fig. 2.54).

Figure 2.54The Replication Agent ProfileDetails dialog box

In Figure 2.54 we have set the LoginTimeout value to 120. I have posi-tioned the cursor at the –QueryTimeout parameter.

Hint: If you have large snapshots, you might want to bumpthis value to a large value, perhaps 10 minutes or more.

Give your profile a name and click OK. Your new profile will thenappear in the Distribution Agent Profiles dialog box. Click the radio buttonin the Use column next to your new profile to select it, and then click OK(Fig. 2.55).

Figure 2.55Selecting the new profile

90 Chapter 2

Page 57: A Guide to SQL Server 2000 Transactional and Snapshot Replication

You will have to stop and start your agent for this profile to be used byyour Distribution Agent.

Refresh Rate and SettingsIf you right click your Replication Monitor Node, you have the option

to set your Refresh Rate and Settings (Fig. 2.56). This allows you to con-trol how often you want your replication agents polled.

Figure 2.56 Refresh Rate and Settings

Selecting Refresh results pane and Refresh server tree will refresh yourresults pane and server tree. The results pane is the right-hand portion ofyour MMC when you expand any of the replication nodes. The server treeis the left-hand portion in any of the replication nodes. You want to set thisfrequency according to your monitoring needs. I normally leave it off andrefresh as needed. If you select Refresh results panes, your ReplicationMonitor will be automatically refreshed every 10 seconds. This may causesome added load on your Distributor and may cause some locking.

The inactivity threshold is the amount of time SQL Server will allow areplication agent to go without hearing back from it. Normally this heart-beat interval is set up for 10 minutes, but for some larger publications, orfor some Subscribers that are on low bandwidth links, you will need tobump this value up. If you pick an inactivity threshold value that is toolow, the job may be marked as failed prematurely.

Hint: This is especially the case when you are distributinglarge snapshots that take over 10 minutes to push a single tableto a Subscriber. Once, I set this value to 1440 (1 day) whilesending a particularly large snapshot over a particularly low

Installing Replication 91

Page 58: A Guide to SQL Server 2000 Transactional and Snapshot Replication

bandwidth link to Guam before leaving work one day. Thenext day, my snapshot job had just completed. You might wantto do the same when you encounter the same conditions.

The Show anonymous subscriptions check box will display anony-mous Subscribers in the results pane and the server tree node. By default,this check box will be enabled. If you have hundreds of anonymousSubscribers, you will want to uncheck this option; otherwise your MMCperformance will be degraded and your MMC will look cluttered.Replication Monitor will still report job failures for these anonymousSubscribers.

Please see the Show Anonymous Subscriptions (on page 94) sectionfor more information on this option.

Select ColumnsThis menu option allows you to configure your results pane for youragents. You can configure the columns displayed for the following agents:

• Trans(actional) Publication View

• Merge Publication View

• Snapshot Agents

• Miscellaneous Agents

• Merge Agents

• Distribution Agents

• Log Reader Agents

• Queue Reader Agents

This option is illustrated in Figure 2.57.

92 Chapter 2

Page 59: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Figure 2.57Select Columns

You can select the columns that you wish to show up in each view, orselect the order of them. I like to move the Status and the Conflictscolumns closer than the way Microsoft orders them for the Merge Agentstab. Use Move Up and Move Down for this. This way the conflicts and jobfailures are more visible, and you can sort the Columns to display list tomake the failed jobs bubble to the top. In the default configuration, thePublisher Conflicts and Subscriber Conflicts columns for the merge repli-cation agents are too far to the right to display and are easily missed. I nor-mally uncheck the Type column. The Type column is either push or pull.My reasoning is that you should know what type of publication you haveset up, and if you forget, you can add this column back in, refresh, note thepublication type, and then exclude it again.

The Status column is the status of your agent. It can be Started,Succeeded, In progress, Idle, Retry, Fail, etc. This is another column thatshould be moved closer to the top. The Reset button will always reset yourcolumn arrangement to Microsoft’s defaults. These settings are stored inthe following registry key:

HKEY_CURRENT_USER\Software\Microsoft\_Microsoft SQL Server\80\Tools\SQLEW\Replication

You can export this key into a reg file for recovery options or to deployit to other servers or machines you will be running EM on.

Installing Replication 93

Page 60: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Show Anonymous SubscriptionsThere are two types of subscriptions:

• Named

• Anonymous

Named subscriptions are subscriptions that are tracked by name in thedistribution database. Transactions are retained in the MSrepl_transactionsand MSrepl_commands tables until they are replicated to the namedSubscriber. History information for the subscription is stored in the distri-bution database as well.

Anonymous subscriptions are most often used with pull subscriptions,especially when you are replicating over the Internet or have manySubscribers. Transactions are retained in the MSrepl_transactions andMSrepl_commands tables until the retention period for the server hasexpired. You set this in the Distribution Database Properties dialog box(Fig. 2.51). You can only create pull subscriptions that are anonymous; youcan’t create anonymous push subscriptions.

Figure 2.58 shows an anonymous subscription: Hilary2kp\Test:c-156.

Figure 2.58 Anonymous Subscriptions showing up in the publicationsfolder

If Show Anonymous Subscriptions is not selected, this subscriptionwill not show up, as illustrated in Figure 2.59.

94 Chapter 2

Page 61: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Figure 2.59 Anonymous Subscriptions hidden in the Publishers folder

The Show Anonymous Subscriptions option will show agents for theanonymous subscriptions if this option is checked. I normally leave thisunchecked, as there is some overhead with enabling this option. Note thatthe anonymous subscriptions will show up in the Publishers folder as wellas in the replication agents’ folders. Please refer to Chapters 3, 4, and 5 forinformation on how to set up anonymous subscriptions.

Replication AlertsIf you expand the Replication Monitor folder in EM, you will notice threenodes or folders: Publishers, Agents, and Replication Alerts. ReplicationAlerts are illustrated in Figure 2.60.

Figure 2.60 Replication Alerts

Installing Replication 95

Page 62: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Replication Alerts are alerts that are replication specific. There are eightdefault Replication Alerts.

Table 2.2 Replication Alerts

Description

Raised when an agent shuts down

Raised when an agent fails

Raised when an agent retries

Raised when an agent succeeds

Raised when a Subscriber expires and is

dropped

Raised when an agent passes data

validation

Raised when Subscriber is reinitialized

after a data validation failure

These alerts will be raised whenever one of the above conditions happen.You can have these alerts write a message to the event log, execute a job,email an operator, send out a network message, or send out a page.

The problem with these alerts is in most distributed environments, youget far too many job failures or job retries. In fact, many DBAs will eitherset their jobs to restart every 10 minutes, and then configure them to runcontinuously, or will have the job return to the first step on failure. Figure2.61 illustrates this technique. I first heard about this technique from GaryWhitley, a Microsoft PSS support engineer in Charlotte, N.C.

Figure 2.61A Distribution Agentjob which loops back torestart on failure

Alert

Replication: agent custom shutdown

Replication: agent failure

Replication: agent retry

Replication: agent success

Replication: expired subscription

dropped

Replication: Subscriber has passed

data validation

Replication: Subscriber reinitialized

after validation failure

96 Chapter 2

Page 63: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Replication Stored ProceduresMost DBAs will install replication using the Install Replication Wizard;however, you can also use the replication stored procedures shown below.This is not the complete set of replication stored procedures; rather, it isthe subset that are used to install, configure, modify, and drop replicationand replication objects. For a detailed study of replication stored proce-dures, go to Chapter 6.

Replication Stored Procedures to InstallReplicationTo install replication, you need to run the first 3 stored procedures in order.We’ll look at each stored procedure and its options, then present an example.

sp_adddistributorThe sp_adddistributor stored procedure is used to configure your serveras a Distributor or, if you are using a remote Distributor, to configure yourserver to use the remote Distributor. It creates an entry in the sysservers table,marks the server entry as a Distributor, and stores property information.

The procedure has the following parameters:

• @distributor

• @heartbeat_interval

• @password

• @from_scripting

@distributorThe name of the server acting as your distributor. There is no default. Hereis an example of its use:

sp_adddistributor @distributor='hilary2kp\test'

If you are using a remote Distributor, the value of the @distributorparameter would be your Distribution server name, and you would issuethis statement on your Publisher.

The data type for the @distributor parameter is sysname.

@heartbeat_intervalHow long a replication agent can run before reporting back to the SQLServer. If the @heartbeat_interval exceeds this value, the job is consideredsuspect and marked as failed. The default is 10 minutes and is an integer.

sp_adddistributor @distributor='hilary2kp\test',@heartbeat_interval=20

Installing Replication 97

Page 64: A Guide to SQL Server 2000 Transactional and Snapshot Replication

In the above example, we are setting the heartbeat interval to 20 min-utes. The data type for the @heartbeat_interval parameter is int.

@passwordYour Administrative Link password, the password that remote Publishersneed to know to use your local Distributor. The default is NULL, whichwill force the SQL Server to auto generate a random password. Here is anexample of its use:

sp_adddistributor @distributor='hilary2kp\test',@heartbeat_interval=10, @password='se1cure#'

The data type for the @password parameter is sysname.

@from_scriptingFor internal use only.

sp_adddistributiondbThe sp_adddistributiondb procedure creates a new distribution databaseand installs the Distributor schema.

The sp_adddistributiondb procedure has the following parameters:

• @database

• @data_folder

• @data_file

• @data_file_size

• @log_folder

• @log_file

• @log_file_size

@databaseThe name of your distribution database. There is no default. Here is anexample of its use:

sp_adddistributiondb 'distribution'

The data type for the @database parameter is sysname.

@data_folderThe directory used to store the distribution database data file. This param-eter is optional with a default of your SQL Server data directory:C:\Program Files\Microsoft SQL Server\Mssql\Data. Here is an example ofits use:

sp_adddistributiondb 'distribution',

• @min_distretention

• @max_distretention

• @history_retention

• @security_mode

• @login

• @password

• @createmode

• @database

98 Chapter 2

Page 65: A Guide to SQL Server 2000 Transactional and Snapshot Replication

@data_folder='D:\Program Files\Microsoft SQLServer\Mssql\Data'

The data type for the @data_folder parameter is nvarchar(255).

@data_fileThe name of the database file for your distribution database. The default isthe name of your database. In the above examples, it will bedistribution.mdf. This parameter is optional. Here is an example of its use:

sp_adddistributiondb 'distribution',@data_folder='D:\Program Files\Microsoft SQLServer\Mssql\Data', @data_file='distribution.mdf'

Note that if you do not append the .mdf on your data file name, it willcreate a database without the .mdf extension and still work.

The data type for the @data_file parameter is nvarchar(255).

@data_file_sizeThe initial data file size in MB. The default is 2 MB, and this parameter isoptional. This parameter is an integer value in MB, so a value of 5 wouldcreate a distribution database with a data file of 5 MB. This parametermust be used in conjunction with an @createmode setting of 1. Here is anexample of its use:

sp_adddistributiondb 'distribution',@data_folder='D:\Program Files\Microsoft SQLServer\Mssql\Data', @data_file='distribution.mdf',@data_file_size=5, @create_mode=1

The data type for the @data_file_size parameter is int.

@log_folderThe @log_folder parameter is very similar to the @data_folder parameter,only its value specifies where the log file should be located. Ideally, on high-volume servers, your log file should be on a RAID 1 or 10 array. This valueis optional and has a default as your SQL Server data directory. Here is anexample of its use:

sp_adddistributiondb 'distribution',@data_folder='D:\Program Files\Microsoft SQLServer\Mssql\Data', @data_file='distribution.mdf',@log_folder='D:\Program Files\Microsoft SQLServer\Mssql\Data', @log_file_size=50

The data type for the @log_folder parameter is nvarchar(255).

Installing Replication 99

Page 66: A Guide to SQL Server 2000 Transactional and Snapshot Replication

@log_fileThe name of the database log file for your distribution database. Thedefault is the name of your database. In the above examples, it will be dis-tribution.ldf. This parameter is optional. Here is an example of its use:

sp_adddistributiondb 'distribution',@data_folder='D:\Program Files\Microsoft SQLServer\Mssql\Data', @data_file='distribution.mdf',@log_folder='D:\Program Files\Microsoft SQLServer\Mssql\Data', @log_file='distribution.ldf',@log_file_size=50

The data type for the @log_folder parameter is int.

@log_file_sizeThe initial log file size in MBs. The default is 2 MBs, and this parameter isoptional. This parameter is an integer value in MBs, so a value of 5 wouldcreate a distribution database with a log file of 5 MBs. This parameter mustbe used in conjunction with a @createmode setting of 1. Here is an exam-ple of its use:

sp_adddistributiondb 'distribution',@data_folder='D:\Program Files\Microsoft SQLServer\Mssql\Data', @data_file='distribution.mdf',@log_folder='D:\Program Files\Microsoft SQLServer\Mssql\Data', @log_file='distribution.ldf',@log_file_size=50,@create_mode=1

The data type for the @log_file_size parameter is int.

@min_distretentionDetermines the minimum time transactions will stay in the MSrepl_com-mands and MSrepl_transactions tables. Replicated transactions (transac-tions that are applied on the Subscriber) will be deleted every time theDistribution Clean up Agent runs. Transactions that are not replicated willremain in the tables until they are older than the value specified in the@max_distretention parameter, and they will then be removed by theDistribution Clean up Agent. By default the Distribution Clean up Agentruns every 10 minutes. DBAs occasionally want to keep the transactionslonger for debugging or disaster recovery purposes. Here is an example ofits use:

sp_adddistributiondb 'distribution',@min_distretention=24

The data type for the @min_distretention parameter is int.

100 Chapter 2

Page 67: A Guide to SQL Server 2000 Transactional and Snapshot Replication

@max_distretentionThe maximum time in hours that transactions are stored in theMSrepl_commands and MSrepl_transactions table before being removed bythe Distribution Clean up Agent. The default is 72 hours. Subscriptionsthat have not received replicated commands and that are older than the@max_distretention period are marked as inactive and need to be reini-tialized. Here is an example of its usage:

sp_adddistributiondb 'distribution',@max_distretention=24

The data type for the @max_distretention parameter is int.

@history_retentionThe number of hours that historical information of the Distribution,Merge, Queue Reader, Log Reader, and Snapshot agents is stored. Thedefault is 48 hours. I prefer to set this value to 72 hours to account for longweekends. The historical data for these agents is retained in the followingtables:

• MSsnapshot_history • MSmerge_history

• MSlogreader_history • MSrepl_errors

• MSdistribution_history • MSqreader_history

Here is an example of its usage:

sp_adddistributiondb 'distribution', @history_retention=72

The data type for the @history_retention parameter is int.

@security_modeControls the authentication mechanism used when creating the distribu-tion database and related objects. The default is 0, which is SQL Serverauthentication; 1 specifies Windows Authentication. If you select SQLServer authentication, you must specify a login and password. Here is anexample of its usage illustrating SQL Server authentication:

sp_adddistributiondb 'distribution', @security_mode =0,@login='sa', @password='se1cure#'

Here is an example of its usage illustrating NT authentication:

sp_adddistributiondb 'distribution', @security_mode =1

The data type for the @security_mode parameter is int.

Installing Replication 101

Page 68: A Guide to SQL Server 2000 Transactional and Snapshot Replication

@loginThe SQL Server login you want to use to create the distribution databaseand related objects. Use this parameter in conjunction with a@security_mode parameter of 1. The default is ‘sa’. This parameter isoptional. Here is an example:

sp_adddistributiondb 'distribution', @security_mode =0,@login='sa', @password='se1cure#'

Here is an example illustrating the optional usage of this parameter:

sp_adddistributiondb 'distribution', @security_mode =0,@password='se1cure#'

If you specify @login and @password with the @security_mode of 1(NT authentication), these values will be ignored.

The data type for the @login parameter is sysname.

@passwordThe @password is the password for the login specified in the @loginparameter. This password is used when creating the distribution databaseand related objects. There is no default. Please refer to the usage of the@login parameter for an example of this parameter.

The data type for the @password parameter is sysname.

@createmodeControls how the SQL Server builds the distribution database. Table 2.3lists the values for this parameter.

Table 2.3 @CreateMode Values (This table comes from BOL)

Value Description

0 The distribution database is created by attaching a copy of thedistribution database model files (distmdl.mdf).

1 The distribution database is created using the Create Databasecommand, or an existing distribution database is used andthen the instdist.sql file is run to create the replication objects.The advantage of this option is that you can modify theinstdist.sql script yourself to include custom storedprocedures, to add agents, or to configure other parameters.

2 For internal use only.

The data type for the @createmode parameter is int.

102 Chapter 2

Page 69: A Guide to SQL Server 2000 Transactional and Snapshot Replication

sp_adddistpublisherThe sp_adddistpublisher stored procedure configures a Publisher to usethe distribution database. This procedure is executed in the distributiondatabase and has the following parameters:

• @publisher • @working_directory

• @distribution_db • @trusted

• @security_mode • @encrypted_password

• @login • @thirdparty_flag

• @password

@publisherThe name of your Publisher, whether the Publisher is on the same server asthe Distributor or on a different server than the Distributor. Here is anexample. This stored procedure is issued on your Distributor in the distri-bution database:

sp_adddistpublisher @publisher=@@servername,@distribution_db='distribution',@working_directory='\\hilaryk2p\temp'

The data type for the @publisher parameter is sysname.

@distribution_dbThe name of the distribution database. This parameter is not optional andthere is no default. Please consult the @publisher parameter for an exam-ple of its usage.

The data type for the @distribution_db parameter is sysname.

@security_modeSets the authentication mode used by the replication agents as they con-nect to the Publisher. This parameter is optional with a default of NULL,which means the SQL Server will decide based on the Operating System(OS) type of the Distributor. If the OS on the Distributor is Win9x, SQLAuthentication will be used. NT 4.0, Win2k, and Win2003 will use NTAuthentication. A value of 0 will force SQL Server authentication, and avalue of 1 will force NT Authentication.

You will want to use SQL Authentication when NT Authenticationwon’t work. For example, if

• your Publisher and Distributor are on different servers in differentuntrusted domains;

• your Publisher and Distributor are on different servers in a work-group; or

Installing Replication 103

Page 70: A Guide to SQL Server 2000 Transactional and Snapshot Replication

• your Publisher and Distributor are on different servers connectedacross the Internet

Here is an example using SQL Authentication:

sp_adddistpublisher @publisher=@@servername,@distribution_db='distribution',@working_directory='\\hilaryk2p\temp', @security_mode=0,@login='sa', @password='se1cure#'

Here is an example using NT Authentication:

sp_adddistpublisher @publisher=@@servername,@distribution_db='distribution',@working_directory='\\hilaryk2p\temp', @security_mode=1

The data type for the @security_mode is int.

@loginThe login you wish your Publisher to use to connect with your Distributor.This parameter is required if @security_mode is 0. The default is sa. Thisparameter is used by replication agents to connect to the Publisher. Pleaserefer to the section on the @security_mode parameter for an example ofhow this parameter works.

The data type for the @login parameter is sysname.

@passwordThe password you wish your Publisher to use to connect with yourDistributor when logging on using the login in the @login parameter. Thisparameter is required if @security_mode is 0. The default is NULL. Thisparameter is used by replication agents to connect to the Publisher. Pleaserefer to the section on the @security_mode parameter for an example ofhow this parameter works.

The data type for the @password parameter is sysname.

@working_directoryThe path that is used to store your snapshot files. The name should bespecified in the UNC format. Please refer to the section on the @publisherparameter for an example of how this parameter works.

The data type for the @working_directory parameter is nvar-char(255).

@trustedWhen you use a remote Distributor, you can lock down your distributiondatabase so that only Publishers who know the Administrative Link pass-word can use your Distributor. You can bypass this by using the @trustedparameter. Setting the @trusted parameter to ‘True’ will allow bypass to

104 Chapter 2

Page 71: A Guide to SQL Server 2000 Transactional and Snapshot Replication

locked down Distributors, so remote Publishers don’t need to enter theAdministrative Link password.

This parameter has three values:

• True: Remote Publishers do not need to enter an Administrative Linkpassword in the @password parameter when using a localDistributor.

• False: Remote Publishers do need to enter an Administrative Linkpassword in the @password parameter when using a localDistributor.

• NULL: If you have a remote Publisher, this value defaults to true. Ifyou have a local Publisher, this value defaults to False, but any pass-word set for the Distributor is also set for the local distributionPublisher.

Here is an example of its usage for a remote Publisher (this is run onthe Distributor in the distribution database):

sp_adddistpublisher @publisher='RemoteServerName',@distribution_db='distribution',@working_directory='\\hilaryk2p\temp', @trusted='true'

If I examine the properties for this Publisher on the Distributor, I willnotice that the This Publisher requires a password to establish a link tothe Distributor check box is unchecked. This is illustrated in Figure 2.62.

Figure 2.62A Trusted Publisher using theLocal Distributor

The data type for the @trusted parameter is nvarchar(5).

Installing Replication 105

Page 72: A Guide to SQL Server 2000 Transactional and Snapshot Replication

@encrypted_passwordUsed internally by the SQL Server when transmitting the AdministrativeLink password. This is encrypted so that network sniffers will not be ableto read the Administrative Link password.

The data type for the @encrypted_password parameter is bit.

@thirdparty_flagUsed when you are using the ActiveX Distribution to publish from aHeterogeneous data source to a local SQL Server Distributor. The default is0, which is a local SQL Server database, and the other possible value is 1,which is another vendor’s RDBMS, or another data source.

The data type for the @thirdparty_flag parameter is bit.

Replication Stored Procedures to Modify theDistributorThe following replication stored procedures are used to change the proper-ties of your distribution database and the publishers that use it. Most ofthese stored procedures, when issued without any parameters, will displaya list of which properties they can change. You then have the option ofspecifying that property, along with the value you wish to change thatproperty to.

sp_changedistpublisherThe sp_changedistpublisher allows you to make changes to the propertiesof the distribution Publisher. This stored procedure is executed at theDistributor on any database.

This stored procedure has the following parameters.

• @publisher

• @property

• @value

@publisherThe name of your Publisher. There is no default and this parameter is notoptional. Here is an example of its usage:

sp_changedistpublisher @@servername

Running this procedure will display a list of properties that can bechanged for your Publisher.

The data type for the @publisher parameter is sysname.

106 Chapter 2

Page 73: A Guide to SQL Server 2000 Transactional and Snapshot Replication

@propertyThe @property parameter is the property you wish to change the value of.Here is an example for changing the status of your Publisher:

sp_changedistpublisher @@servername, @property='active',@status='false'

Here is a list of the properties you can modify for an existing Publisher:

• Active: Whether a remote Publisher is using the local server as aDistributor. A value of 0 indicates no; a value of 1 indicates yes.

• distribution_db: The name of the distribution db.

• login: The login the Publisher is using to connect to the Distributor ifyou are using a security_mode of 0.

• password: The password the Publisher is using to connect to theDistributor if you are using a security_mode of 0.

• security_mode: The security mode the Publisher will use to connectto the Distributor. This property has two values: 0 for SQL ServerAuthentication, 1 for NT Authentication.

• working_directory: The working directory for the snapshot files. Thisshould be in the format of a UNC.

The data type for the @property parameter is sysname.

@valueThe @value parameter contains the new value you wish to use for theproperty you are changing. This parameter is not optional for all proper-ties, and if it is optional, it has a value of NULL, which will be the defaultfor that property. Please refer to the section on the @property parameterfor an example of how this parameter works.

The data type for the @value parameter is nvarchar(255).

sp_changedistributiondbThe sp_changedistributiondb changes the properties of the distributiondatabase. This stored procedure is executed at the Distributor on the distri-bution database.

This stored procedure has the following parameters:

• @database

• @property

• @value

Installing Replication 107

Page 74: A Guide to SQL Server 2000 Transactional and Snapshot Replication

@databaseThe name of your distribution database on your Distributor. There is nodefault for this parameter and it is not optional.

Here is an example illustrating the usage of the @database parameter,changing the history_retention property:

sp_changedistributiondb @database='distribution',@property='history_retention',@value=90

The data type for the @database parameter is sysname.

@propertyThe property you wish to change on your distribution database. Thisparameter is optional and has a default of NULL. If you do not specify aparameter, a list of all the properties you can change will be displayed. Hereis an example of its usage, displaying all properties you can change.

sp_changedistributiondb @database='distribution'

Here is a list of the properties you can change:

• history_retention

• max_distretention

• min_distretention

Please refer to the section on the @database parameter for an example ofhow this parameter works.

The data type for the @property is sysname.

@valueThe value you wish to change the property specified in the @propertyparameter to. This parameter is not optional for all properties, and if it isoptional, it has a value of NULL, which will be the default for that prop-erty. Please refer to the section on the @database parameter for an exampleof how this parameter works.

The data type for the @value parameter is nvarchar(255).

sp_changedistributor_passwordThe sp_changedistributor_password stored procedure changes theAdministrative Link password for a Distributor. This stored procedure isexecuted at the Publisher on the distribution database.

This procedure has a single parameter:

• @password.

An example of its usage:

sp_changedistributor_password @password='se1cure#'

108 Chapter 2

Page 75: A Guide to SQL Server 2000 Transactional and Snapshot Replication

The data type for the @password parameter is sysname.

sp_changedistributor_propertyThe sp_changedistributor_property stored procedure is used to makechanges to the properties of your Distributor server. This stored procedureis executed at the Distributor on the distribution database.

This stored procedure has the following parameters:

• @property

• @value

@propertyThe name of the property you wish to modify. The only property you canmodify is the heartbeat_interval parameter. If you run this stored proce-dure without specifying any properties or using a property value of NULL,this property is displayed. Here is an example of its usage:

sp_changedistributor_property@property='heartbeat_interval', @value=20

The heartbeat_interval is the amount of time that can elapse before areplication agent is considered suspect.

The data type for the @property parameter is sysname.

@valueThe value of the property you wish to change. In this case, the only prop-erty you can change is the heartbeat_interval property. The default is null,which will change the heartbeat_interval to 10 minutes.

The data type for the @value parameter is nvarchar(255).

Replication Stored Procedures to DisplayReplication PropertiesThe following replication stored procedures are used to display the proper-ties of your Distributor, distribution database, and the Publishers that useit. The stored procedures either return a results set or allow you to checkthe value of an individual property. When the stored procedure returns aresults set, I explain what each of the columns mean in the tables accompa-nying that stored procedure’s description.

sp_helpdistpublisherThe sp_helpdistpublisher stored procedure returns the properties of aPublisher that is using the local Distributor. This procedure is run on theDistributor in any database. The parameters for this stored procedure are

Installing Replication 109

Page 76: A Guide to SQL Server 2000 Transactional and Snapshot Replication

• @publisher

• @check_user

@publisherThe name of your Publisher. This parameter is optional, and if the @pub-lisher parameter is not used, a list of all Publishers will be returned. Here isan example that returns a list of all publishers using the local Distributor:

sp_helpdistpublisher

Here is an example that displays the properties of the local Publisher:

sp_helpdistpublisher @publisher=@@servername

The data type for the @publisher parameter is sysname.

@check_userThe @check_user parameter is undocumented and is for internal use only.Here is a list of the columns returned by the sp_helpdistpublisher proce-dure and a brief description of them.

110 Chapter 2

Page 77: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Table 2.4 Columns returned by the sp_helpdistpublisher (This table comes from BOL.)

sp_helpdistributiondbThe sp_helpdistributiondb stored procedure is used to display propertiesof your distribution database. This stored procedure is executed at theDistributor on the distribution database. This stored procedure has a singleparameter, which is the name of your distribution database.

Here is a list of the columns returned by the sp_helpdistributiondbprocedure and a brief description of them.

Column Name Description

Name Name of Publisher

distribution_db The name of the Distribution database forthe specified Publisher

security_mode Security mode used by the replication agentin a push subscription to connect to thePublisher. Possible values are 0 for SQLAuthentication, and 1 for NTAuthentication.

Login If the security mode is 0, the login is thename of the account used by the Publisherto connect with the Distributor.

Password Password returned (in simple encryptedform)

Active Whether a remote Publisher is using thelocal server as a Distributor. Possible valuesare 0 for no, and 1 for yes.

working_directory The UNC path of your snapshot folder. Bydefault it is \\ServerName\C$\ProgramFiles\Microsoft SQLServer\MSSQL\ReplData

Trusted Whether the Publisher is trusted and doesnot have to use the Administrative LinkPassword, or is untrusted and does have to.

thirdparty_flag Whether the Publisher is using a MicrosoftSQL Server database (0) or is aHeterogeneous data source (1).

Installing Replication 111

Page 78: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Table 2.5 Columns returned by the sp_helpdistributiondb storedprocedure (This table comes from BOL.)

Column name Description

distribution_database Name of the database

min_distretention Minimum retention period, in hours,before replicated transactions are deleted

max_distretention Maximum retention period, in hours,before transactions are deleted

history retention Number of hours to retain replicationagent history

history_clean up_agent Name of the History Clean up Agent

distribution_clean up_agent Name of the Distribution Clean upAgent

Status Not supported

data_folder Name of the directory used to store thedistribution database’s data files

data_file Name of the database file

data_file_size Initial data file size in megabytes

log_folder Name of the directory for the databaselog file

log_file Name of the log file

log_file_size Initial log file size in megabytes

sp_helpdistributorThe sp_helpdistributor stored procedure displays information about theDistributor, distribution database, working directory, and SQL ServerAgent user account. This stored procedure is executed at the Distributor onany database.

The sp_helpdistributor procedure has the following parameters:

• @distributor • @history_cleanup_agent

• @distribdb • @distrib_cleanup_agent

• @directory • @publisher

• @account • @local

• @min_distretention • @rpcsrvname

• @max_distretention • @distributor

• @history_retention

112 Chapter 2

Page 79: A Guide to SQL Server 2000 Transactional and Snapshot Replication

This stored procedure can be used in two ways. You can execute it with-out any parameters and return the results set illustrated in Table 2.5:

sp_helpdistributor

Or you can query a specify property/parameter. The list of parametersis specified above.

Declare @distributorname varchar(255)exec sp_helpdistributor @distributor = @distributornameOUTPUTprint @distributorname

This will display only the name of the Distributor. Some parameterswill display only the results set illustrated in Table 2.5, e.g. the @publisherparameter.

@distributorThe name of the Distributor server. There is no default, but this parameteris optional. This is an output parameter. For an example of its usage, pleaserefer to the above code sample.

The data type for the @distributor parameter is sysname.

@distribdbThe name of the distribution database. There is no default, but this param-eter is optional. This is an output parameter. Here is an example of thisparameter’s usage:

Declare @distribdnname varchar(255)exec sp_helpdistributor @distributor = @distribdnnameOUTPUTprint @distribdnname

This will display only the name of the distribution database.The data type for the @distribdb parameter is sysname.

@directoryThe name of the folder where your snapshot files are created and stored. Bydefault this path is \\ServerName\C$\Program Files\Microsoft SQLServer\MSSQL\ReplData. There is no default, but this parameter isoptional. This is an output parameter. Here is an example of this parame-ter’s usage:

Declare @directoryname varchar(255)exec sp_helpdistributor @directory = @directorynameOUTPUTprint @directoryname

This will display only the name of the snapshot share.The data type for the @directory parameter is nvarchar(255).

Installing Replication 113

Page 80: A Guide to SQL Server 2000 Transactional and Snapshot Replication

@accountThe name of the NT account used by the Publisher to connect to theDistributor. There is no default, but this parameter is optional. This is anoutput parameter. Here is an example of this parameter’s usage:

Declare @accountname varchar(255)exec sp_helpdistributor @account = @accountname OUTPUTprint @accountname

This will display only the name of the account used by the Publisher toconnect to the Distributor’s snapshot share where the snapshot files arecreated and stored.

The data type for the @account is nvarchar(255).

@min_distretentionThe minimum length of time that replicated transactions are stored in thedistribution database before the Distribution Clean Up Agent will removethem. There is no default, but this parameter is optional. This is an outputparameter. Here is an example of this parameter’s usage:

Declare @retentiontime varchar(255)exec sp_helpdistributor @min_distretention =@retentiontime OUTPUTprint @retentiontime

This will display only the minimum distribution retention time.The data type for the @min_distretention is int.

@max_distretentionThe maximum length of time that replicated transactions are stored in thedistribution database before the Distribution Clean Up Agent will removethem. There is no default, but this parameter is optional. This is an outputparameter. Here is an example of this parameter’s usage:

Declare @retentiontime varchar(255)exec sp_helpdistributor @max_distretention =@retentiontime OUTPUTprint @retentiontime

This will display only the maximum distribution retention time.The data type for the @max_distretention is int.

@history_retentionThe maximum length of time that historical information from the replica-tion agents is stored in the distribution database. There is no default, butthis parameter is optional. This is an output parameter. Here is an exampleof its usage:

114 Chapter 2

Page 81: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Declare @historyretentiontime varchar(255)exec sp_helpdistributor @history_retention =@historyretentiontime OUTPUTprint @historyretentiontime

This will display only the history retention time.The data type for the @history_retention is int.

@history_cleanup_agentThe name of the History clean up agent. By default, the SQL Server willname this agent “Agent history clean up: distribution”. There is no default,but this parameter is optional. This is an output parameter. Here is anexample of its usage:

Declare @history_cleanupagent_name varchar(255)exec sp_helpdistributor @history_cleanup_agent =@history_cleanupagent_name OUTPUTprint @history_cleanupagent_name

This will display only the history clean up agent name.The data type for the @history_cleanupagent is nvarchar(100).

@distrib_cleanup_agentThe distribution clean up agent. By default, the SQL Server will name thisagent “Distribution clean up: distribution”. There is no default, but thisparameter is optional. This is an output parameter. Here is an example ofits usage:

Declare @distrib_cleanupagent_name varchar(255)exec sp_helpdistributor @distrib_cleanup_agent =@distrib_cleanupagent_name OUTPUTprint @distrib_cleanupagent_name

This will display only the distribution clean up agent name.The data type for the @distrib_cleanupagent is nvarchar(100).

@publisherThe Publisher. If you have more than one Publisher, only the localPublisher will be displayed. There is no default, but this parameter isoptional. Here is an example of its usage:

exec sp_helpdistributor @publisher = @@servername

This will display only the results set illustrated in Table 2.5.The data type for the @publisher is sysname.

@localThe @local parameter determines whether the results set display should befor the local Publisher or the Distributor. Here is an example of its usage:

Installing Replication 115

Page 82: A Guide to SQL Server 2000 Transactional and Snapshot Replication

exec sp_helpdistributor @local = @@servername

This will display only the results set illustrated in Table 2.5.The data type for the @local is sysname.

@rpcsrvnameThe replication executables (distrib, logreader, snapshot, qrdrsvc, replmerg)do all their server-to-server communication via Remote Procedure Calls(RPCs). The @rpcsrvname is the name of the server that issues these calls.The server that the SQL Server replication uses is a virtual server, which isby default a remote server called repl_distributor. You can see this virtualserver if you expand the security folder for your server in EM, and thenexpand the remote server node. Here is an example of its usage:

Declare @rpcserver_name varchar(255)exec sp_helpdistributor @rpcsrvname = @rpcserver_nameOUTPUTprint @rpcserver_name

This will display only the RPC server name. The data type for the@rpcsrvname is sysname.

Table 2.5 Columns returned by issuing a sp_helpdistributor(This table comes from BOL.)

Column Name Description

Distributor Name of the Distributordistribution database Name of the distribution databaseDirectory Name of the path where the snapshot files

are storedAccount Name of the NT account used by the

Publisher to connect with the Distributormin distrib retention Minimum distribution retention periodmax distrib retention Maximum distribution retention periodhistory retention History retention periodhistory clean up agent Name of the History Clean up Agentdistribution clean up Name of the Distribution Clean up Agent

agentrpc server name Name of the remote or local Distributorrpc login name Login used for remote procedure calls to the

remote Distributor

If the distribution database is not installed, a NULL value is returned.

116 Chapter 2

Page 83: A Guide to SQL Server 2000 Transactional and Snapshot Replication

Replication Stored Procedures to DropReplicationThe following stored procedures are used to drop or disable theDistributor. These stored procedures are listed in the order that they mustbe run to drop replication. If you are bold you can issue a

sp_dropdistpublisher @publisher= @@servername,@no_checks=1

or a

sp_dropdistributor @no_checks=1

and be done with it; however, this is not always the wisest choice if youhave remote Publishers using this Distribution server.

sp_dropdistpublisherThe sp_dropdistpublisher stored procedure will drop Publishers using thelocal distribution database. This stored procedure is executed at theDistributor on any database. This stored procedure has 2 parameters:

• @publisher

• @no_checks

@publisherThe @publisher parameter is the name of the Publisher you want to dropfrom the local Distributor. This parameter is not optional and there is nodefault. Here is an example of its usage:

sp_dropdistpublisher @publisher='albanysql02'

The data type for the @publisher is sysname.

@no_checksSometimes a remote Publisher using your local Distributor will go offlineunexpectedly and will have to drop it from your local distribution data-base. If you try to run sp_dropdistpublisher when the remote Publisher isoffline, this procedure will fail. If you set the value of @no_checks to 1, thesp_dropdistpublisher stored procedure will not attempt to contact theremote Publisher, and the stored procedure will succeed. If there is achance that the remote Publisher will come back online, you will have tomanually remove replication from this server by issuing sp_dropdistribu-tor with @ignore_distributor = 1 on the remote Publisher.If the value of @no_checks is 0, and the remote Publisher is offline, thisprocedure will fail. If the Publisher is local, and you issue this commandand there are any publications, this procedure will again fail, and you will

Installing Replication 117

Page 84: A Guide to SQL Server 2000 Transactional and Snapshot Replication

have to manually drop the publications. The default for this stored proce-dure is 0. Here is an example of its usage:

sp_dropdistpublisher @publisher='albanysql02',@no_checks=1

If you have only a local Publisher, you can issue this command and itwill completely disable replication without your having to issue any of nexttwo stored procedures.

The data type for the @no_checks is bit.

sp_dropdistributiondbThe sp_dropdistributiondb stored procedure drops the local distributiondatabase. This stored procedure is executed at the Distributor on any data-base and has the following single parameter:

• @database

@databaseThe @database parameter is the name of your distribution database,which by default is called distribution. There is no default for this parame-ter. Here is an example of its usage:

sp_dropdistributiondb @database='distribution'

The data type for the @database is sysname.

sp_dropdistributorThe sp_dropdistributor stored procedure uninstalls the Distributor. Thisstored procedure is executed at the Distributor or on a remote Publisher onany database. This stored procedure has two parameters:

• @no_checks

• @ignore_distributor

@no_checksThe @no_checks parameter will completely disable replication if it has asetting of 1. Any remote Publishers using this distribution database will beorphaned, and you will have to connect to them and issue an sp_dropdis-tributor with @ignore_distributor = 1. The default for this procedure is 0,and this parameter is optional. If you specify a value of @no_checks forthis procedure, if there is a distribution database on your Distributor, thisprocedure will fail. Here is an example of its usage:

sp_dropdistributor @no_checks=1

The data type for the @no_checks is bit.

118 Chapter 2

Page 85: A Guide to SQL Server 2000 Transactional and Snapshot Replication

@ignore_distributorAllows the user to drop replication, but it leaves the distribution databaseintact. This parameter is used in recovery operations when the Distributoris offline or being uninstalled. The default for this procedure is 0. A valueof 0 for this parameter will cause the SQL Server to connect with theDistributor and remove all replication objects. If the SQL Server is unableto connect to the Distributor, the stored procedure fails. If this parameterhas a value of 1, the SQL Server attempts to connect to the Distributor, andif it does so, it will remove all replication objects. If it can’t connect to theDistributor, the procedure succeeds, but no replication objects areremoved. The data type for the @ignore_distributor is bit.

SummaryThis chapter focused on installing replication on your server, as well asenabling Subscribers. You should have learned all aspects of installing andconfiguring your distribution database through Enterprise Manager, howto configure your local Distributor for remote Publishers, and how toenable Subscribers. We took a look at how to enable replication to othervendors’ databases. We then took a brief look at profiles, and ReplicationAlerts, their usage and shortcomings.

We then had a look at the replication stored procedures that are neces-sary to install, configure, and remove replication. We will now move on insubsequent chapters to how to create your publications using EM, storedprocedures, SQL DMO, and ActiveX controls and how to deploy them toSubscribers.

Installing Replication 119

Page 86: A Guide to SQL Server 2000 Transactional and Snapshot Replication