diff --git a/3316.pdf b/3316.pdf new file mode 100644 index 0000000..f1cacb7 Binary files /dev/null and b/3316.pdf differ diff --git a/9781590596500.jpg b/9781590596500.jpg new file mode 100644 index 0000000..55f2c24 Binary files /dev/null and b/9781590596500.jpg differ diff --git a/AppendixB/AppendixBcodes.txt b/AppendixB/AppendixBcodes.txt new file mode 100644 index 0000000..bd2d221 --- /dev/null +++ b/AppendixB/AppendixBcodes.txt @@ -0,0 +1,487 @@ +Appendix B1. T-SQL code for the physical database structure +/* ============================================================ */ +/* Database name: Mysales */ +/* DBMS name: Microsoft SQL Server 2005 */ +/* ============================================================ */ + +/* ============================================================ */ +/* Schema: myorder */ +/* ============================================================ */ +create SCHEMA myorder +/* ============================================================ */ +/* Table: ZONE */ +/* ============================================================ */ +create table [myorder].[ZONE] +( + ZoneID smallint not null, + ZonePlace varchar(20) null , + constraint PK_ZONE primary key (ZoneID) +) + +/* ============================================================ */ +/* Table: BillTO */ +/* ============================================================ */ +create table [myorder].[BillTO] +( + BillTo smallint not null, + Name varchar(30) null , + WhseAddress1 varchar(30) null , + Whse_City varchar(20) null , + Whse_Postal_Code varchar(7) null , + Phone varchar(20) null , + SlsPerson int null , + Zone smallint null , + constraint PK_BILLTO primary key (BillTo) +) + + +/* ============================================================ */ +/* Table: Stock */ +/* ============================================================ */ +create table [myorder].[Stock] +( + StockId int not null, + Whse varchar(10) null , + QtyOnHand decimal null , + QtyOnOrd decimal null , + QtyAvail decimal null , + constraint PK_STOCK primary key (StockId) +) + + +/* ============================================================ */ +/* Table: SalesPerson */ +/* ============================================================ */ +create table [myorder].[SalesPerson] +( + SalesID int not null, + Name varchar(30) null , + WhseAddress1 varchar(30) null , + Whse_City varchar(20) null , + Whse_Postal_Code varchar(7) null , + Phone varchar(20) null , + Zone smallint null , + constraint PK_SALESPERSON primary key (SalesID) +) +/* ============================================================ */ +/* Table: Customer */ +/* ============================================================ */ +create table [myorder].[Customer] +( + CustID int not null, + BillTo smallint not null, + Name varchar(30) null , + WhseAddress1 varchar(30) null , + Whse_City varchar(20) null , + Whse_Postal_Code varchar(7) null , + Phone varchar(20) null , + Email_Addr varchar(20) null , + Zone smallint null , + SlsPerson int null , + constraint PK_CUSTOMER primary key (CustID) +) + + +/* ============================================================ */ +/* Table: OrderHeader */ +/* ============================================================ */ +create table [myorder].[OrderHeader] +( + CustID int not null, + OrderID int not null, + Order_Date datetime null , + Ship_Date datetime null , + Whse varchar(10) null , + Zone smallint null , + PayMethod varchar(7) null , + FreightCharge bit null , + InvoiceNum numeric null , + InvoiceDate datetime null , + SlsPerson int null , + constraint PK_ORDERHEADER primary key (OrderID) +) + + +/* ============================================================ */ +/* Table: OrderDetail */ +/* ============================================================ */ +create table [myorder].[OrderDetail] +( + OrderID int not null, + ItemID numeric null , + ItemDescription varchar(30) null , + Qty numeric null , + QtyShip numeric null , + QtyBO numeric null , + BOYesNo bit null , + Price decimal null , + Discount decimal null , + Amount decimal null , +) + + +/* ============================================================ */ +/* Table: ShipTO */ +/* ============================================================ */ +create table [myorder].[ShipTO] +( + CustID int not null, + ShipTO smallint not null, + Name varchar(30) null , + WhseAddress1 varchar(30) null , + Whse_City varchar(20) null , + Whse_Postal_Code varchar(7) null , + Phone varchar(20) null , + SlsPerson int null , + Zone smallint null , + constraint PK_SHIPTO primary key (CustID, ShipTO) +) + +/* ============================================================ */ +/* Table: CustSales */ +/* ============================================================ */ +create table [myorder].[CustSales] +( + CustID int not null, + SalesID int not null, + constraint PK_CUSTSALES primary key (CustID, SalesID) +) +go + +/* ============================================================ */ +/* Schema: myinventory */ +/* ============================================================ */ +create SCHEMA myinventory + + +/* ============================================================ */ +/* Table: Warehouse */ +/* ============================================================ */ +create table [myinventory].[Warehouse] +( + WhseID int not null, + WhseName varchar(20) null , + WhseAddress1 varchar(30) null , + Whse_City varchar(20) null , + Whse_Postal_Code varchar(7) null , + constraint PK_WAREHOUSE primary key (WhseID) +) +/* ============================================================ */ +/* Table: Item */ +/* ============================================================ */ +create table [myinventory].[Item] +( + ItemID int not null, + Description varchar(30) null , + Vendor int null , + Category varchar(20) null , + Color varchar(10) null , + Unit char(4) null + constraint CKC_UNIT_ITEM check ( + Unit in ('EA','BOX','DZ','PAIR')), + constraint PK_ITEM primary key (ItemID) +) + +/* ============================================================ */ +/* Table: Vendor */ +/* ============================================================ */ +create table [myinventory].[Vendor] +( + VendorID numeric not null, + Name varchar(30) null , + WhseAddress1 varchar(30) null , + Whse_City varchar(20) null , + Whse_Postal_Code varchar(7) null , + Phone varchar(20) null , + constraint PK_VENDOR primary key (VendorID) +) + + +/* ============================================================ */ +/* Table: PurchaseOrderDetail */ +/* ============================================================ */ +create table [myinventory].[PurchaseOrderDetail] +( + PoNum numeric not null, + PoHNum int not null, + ItemID numeric null , + ItemDescription varchar(30) null , + Price decimal null , + Qty numeric null , + BOYesNo bit null , + Discount decimal null , + Amount decimal null , + constraint PK_PURCHASEORDERDETAIL primary key (PoNum) +) + + +/* ============================================================ */ +/* Table: PriceList */ +/* ============================================================ */ +create table [myinventory].[PriceList] +( + PriceId int not null, + ItemidPricelist int not null, + ItemID int null , + Price decimal null , + Discount decimal null , + Cost decimal null , + constraint PK_PRICELIST primary key (PriceId, ItemidPricelist) +) + + +/* ============================================================ */ +/* Table: PurchaseOrderHeader */ +/* ============================================================ */ +create table [myinventory].[PurchaseOrderHeader] +( + PoHNum int not null, + VendorID numeric not null, + PO_Date datetime null , + AccountNum numeric null , + AccountName varchar(20) null , + constraint PK_PURCHASEORDERHEADER primary key (PoHNum) +) + + +/* ============================================================ */ +/* Table: StockItem */ +/* ============================================================ */ +create table [myinventory].[StockItem] +( + StockId int not null, + ItemID int not null, + constraint PK_STOCKITEM primary key (StockId, ItemID) +) + +go +/* ============================================================ */ +/* Scehma: myfinance */ +/* ============================================================ */ +create SCHEMA myfinance +/* ============================================================ */ +/* Table: CashReceipt */ +/* ============================================================ */ +create table [myfinance].[CashReceipt] +( + CustID int null , + Receiptdate datetime null , + ReferenceOrderNum numeric(10) null , + ReceiptAmount decimal(6,2) null , + UnappliedAmount decimal(6,2) null , + GLnum varchar(30) null , + Posted bit null , + CRID integer not null, + constraint PK_CASHRECEIPT primary key (CRID) +) + +/* ============================================================ */ +/* Table: AccountsReceivable */ +/* ============================================================ */ +create table [myfinance].[AccountsReceivable] +( + AccountID int not null, + InvoiceNo int not null, + CustID int not null, + Amount decimal null , + InvoiceDate datetime null , + PaymentStatus bit null , + ReferenceNum int null , + Balancedue decimal(6,2) null , + InvoiceDuedate datetime null , + GLAccount varchar(30) null , + constraint PK_ACCOUNTSRECEIVABLE primary key (AccountID, InvoiceNo) +) + + +/* ============================================================ */ +/* Table: AccountInvoice */ +/* ============================================================ */ +create table [myfinance].[AccountInvoice] +( + AccountID int not null, + InvoiceNo int not null, + CRID integer null , + constraint PK_ACCOUNTINVOICE primary key (AccountID, InvoiceNo) +) +go + +alter table [myinventory].[PurchaseOrderHeader] add constraint FK_PURCHASE_RELATION__VENDOR foreign key (VendorID) + references [myinventory].[Vendor](VendorID) +go + +alter table [myorder].[OrderHeader] add constraint FK_ORDERHEA_REF_185_CUSTOMER foreign key (CustID) + references [myorder].[Customer] (CustID) +go + +alter table [myfinance].[AccountsReceivable] add constraint FK_ACCOUNTS_REF_188_CUSTOMER foreign key (CustID) + references [myorder].[Customer] (CustID) +go + +/*alter table [myorder].[OrderDetail] add constraint FK_ORDERDET_REF_233_ORDERHEA foreign key (OrderID) + references [myorder].[OrderHeader] (OrderID)*/ +go + +alter table [myorder].[ShipTO] add constraint FK_SHIPTO_REF_220_CUSTOMER foreign key (CustID) + references [myorder].[Customer] (CustID) +go + +alter table [myorder].[CustSales] add constraint FK_CUSTSALE_REF_2432_CUSTOMER foreign key (CustID) + references [myorder].[Customer] (CustID) +go + +alter table [myorder].[CustSales] add constraint FK_CUSTSALE_REF_243_SALESPER foreign key (SalesID) + references [myorder].[SalesPerson] (SalesID) +go + +alter table [myinventory].[StockItem] add constraint FK_STOCKITE_RELATION__STOCK foreign key (StockId) + references [myorder].[Stock] (StockId) +go + +alter table [myinventory].[StockItem] add constraint FK_STOCKITE_RELATION__ITEM foreign key (ItemID) + references [myinventory].[Item] (ItemID) +go + +alter table [myinventory].[PurchaseOrderDetail] add constraint FK_PURCHASE_RELATION__PURCHASE foreign key (PoHNum) + references [myinventory].[PurchaseOrderHeader] (PoHNum) +go + +alter table [myinventory].[PriceList] add constraint FK_PRICELIS_RELATION__ITEM foreign key (ItemID) + references [myinventory].[Item] (ItemID) +go + +alter table [myfinance].[AccountInvoice] add constraint FK_ACCOUNTI_RELATION__ACCOUNT foreign key (AccountID, InvoiceNo) + references [myfinance].[AccountsReceivable] (AccountID, InvoiceNo) +go + +alter table [myfinance].[AccountInvoice] add constraint FK_ACCOUNTI_REF_861_CASHRECE foreign key (CRID) + references [myfinance].[CashReceipt] (CRID) +go + +************************************************* +view: vw_CustomerInvoiceStatus +************************************************ +create view [myorder].[vw_CustomerInvoiceStatus] as +select b.custid, a.amount, a.invoicedate, a.paymentstatus, a.balancedue, +a.invoiceduedate, b.name as customername, b.phone, c.name as salespersonname, +c.zone +from myorder.customer as b, myfinance.accountsreceivable as a, +myorder.custsales as d, myorder.salesperson as c +where a.Custid = b.custid +and b.custid = d.custid +and d.salesid = c.salesid +go + +************************************************* +view: vw_ItemEnquiry +************************************************ +create view [myorder].[vw_ItemEnquiry] as +select a.itemid, a.description, b.price, d.stockid, d.whse, d.qtyonhand, d.qtyonord +from myinventory.item as a, myinventory.pricelist as b, myinventory.stockitem as c, +myorder.stock as d +where a.itemid = b.itemid +and b.itemid = c.itemid +and c.itemid = d.stockid +go +************************************************* +view: vw_OrderStatus +************************************************ +create view [myorder].[vw_OrderStatus] as +select a.custid, a.name, b.orderid, b.ship_date, c.itemid, c.itemdescription, +c.qtyship, c.qty +from customer a, orderheader b, OrderDetail c +where a.custid = b.custid +and b.orderid = c.OrderID +go + +******************************************************************** +procedure: myorder.usp_GetCustomerInvoicePaymentDue +********************************************************************* +IF OBJECT_ID ( 'myorder.usp_GetCustomerInvoicePaymentDue', 'P' ) IS NOT NULL + DROP PROCEDURE myorder.usp_GetCustomerInvoicePaymentDue; +go + +CREATE PROCEDURE myorder.usp_GetCustomerInvoicePaymentDue + @customername varchar(40) + +AS +set nocount on + +if(select paymentstatus from myorder.vw_CustomerInvoiceStatus)>0 +begin +select custid,amount,customername, +case when datepart(dd,invoicedate)>datepart(dd,invoiceduedate) +then invoicedate end +from myorder.vw_CustomerInvoiceStatus +where customername=@customername +end + +Select Sum(amount) as TotalAmount, Max(Amount) as MaxAmount,custid,customername +from myorder.vw_CustomerInvoiceStatus +group by amount, custid,customername +having custid>1 +go + +******************************************************************** +procedure: usp_InsertCustomerInvoice +********************************************************************* +IF OBJECT_ID ( 'myorder.usp_InsertCustomerInvoice', 'P' ) IS NOT NULL + DROP PROCEDURE myorder.usp_InsertCustomerInvoice; +go + +/* insert customer invoice in accountsreceivable table */ +CREATE PROCEDURE myorder.usp_InsertCustomerInvoice +@accountid int, +@invoiceno int, +@custid int, +@amount decimal, +@invoicedate datetime, +@paymentstatus bit, +@referencenum bit, +@balancedue decimal(6,2), +@invoiceduedate datetime, +@glaccount varchar(30) + +AS +set nocount on + +INSERT myfinance.AccountsReceivable(AccountID, InvoiceNo, CustID, Amount, InvoiceDate, +PaymentStatus, ReferenceNum, Balancedue, InvoiceDuedate, GLAccount) +SELECT +@accountid, +@invoiceno, +@custid, +@amount, +@invoicedate, +@paymentstatus, +@referencenum, +@balancedue, +@invoiceduedate, +@glaccount + +/* if values are inserted then find the names of the customer and the identity of the salesperson */ +if @@rowcount<>0 +select a.custid, a.name as Customername, a.phone, a.slsperson, b.amount,b.invoicedate +from myorder.customer a, myfinance.accountsreceivable b +where a.custid=@custid +go + +******************************************************************** +procedure: usp_GetItemAbovePremiumPrice +********************************************************************* +IF OBJECT_ID ( 'myinventory.usp_GetItemAbovePremiumPrice', 'P' ) IS NOT NULL + DROP PROCEDURE myinventory.usp_GetItemAbovePremiumPrice; +go + +/* find those items that are above average and will be sold to +premium customers*/ +CREATE PROCEDURE myinventory.usp_GetItemAbovePremiumPrice +AS +declare @avgprice decimal +set @avgprice=(select avg(price) from myinventory.pricelist) + select a.itemid, a.description,a.vendor,a.category,a.color,a.unit, + b.price + from myinventory.item a, myinventory.pricelist b + where a.itemid=b.itemid and + b.price>@avgprice +go \ No newline at end of file diff --git a/Codes/Chapter02/Chapter02codes.txt b/Codes/Chapter02/Chapter02codes.txt new file mode 100644 index 0000000..dbb0fb0 --- /dev/null +++ b/Codes/Chapter02/Chapter02codes.txt @@ -0,0 +1,156 @@ +Code from sidebar To GUI or not to GUI + +declare @publisher_name as sysname; +set @publisher_name =(select name from msdb..MSdistpublishers where name=@@servername); +print @publisher_name; + +/*drop the publisher */ +exec sp_dropdistpublisher @publisher=@publisher_name,@no_checks=0; + +declare @distributiondb as sysname; +set @distributiondb =(select name from sys.sysdatabases where name ='distribution'); +/*drop the distribution database */ +exec sp_dropdistributiondb @distributiondb; + +/*remove the local Distributor */ +exec sp_dropdistributor; + + go + +Listing 2-1. Configuring the Distributor server and the distribution database +Use master +go +/* declare the variables */ +declare @distributor as sysname; +declare @distributorserver_msg as varchar(50); + +/*get the default instance of the name of the server +and use that as the Distributor */ + +set @distributor = (select convert (sysname,serverproperty('servername'))); + +/*set the name and then print the name of the Distributor server */ + +set @distributorserver_msg='The name of the Distributor server:'; +print @distributorserver_msg + ' ' +@distributor; +/* add the Distributor */ +exec sp_adddistributor @distributor=@distributor; + +/* install the distribution database on the default directory + and use Windows Integrated Authentication*/ + +declare @distributiondb as sysname; +set @distributiondb ='distribution'; +exec sp_adddistributiondb @database =@distributiondb,@security_mode=1; +go + +Listing 2-2. Configuring the Publisher server +/* declare the variables */ +declare @distributor as sysname; +declare @publisher as sysname; +declare @publisherserver_msg as varchar (50); + +/*get the default instance of the name of the server and + use that as the Distributor */ + +set @distributor = (select convert (sysname,serverproperty('servername'))); + + +/*set the name and then print the name of the Publisher server. +The Publisher and the Distributor are residing on the same server */ + +set @publisher =@distributor; +set @publisherserver_msg='The name of the publisher server:'; +print @publisherserver_msg +' '+ @publisher; + + +/*now add the Publisher to the same Distributor as +installed locally --- remember that sp_adddistpublisher can +be used for snapshot, transactional and merge replication*/ + +use distribution + +declare @distributiondb as sysname; +set @distributiondb ='distribution'; +exec sp_adddistpublisher @publisher, @security_mode=1, @distribution_db=@distributiondb, +@publisher_type = 'MSSQLSERVER'; +go +Listing 2-3. Remote server link +use master +go +/* declare the table variable */ + +declare @servername_dist table +( +serverid smallint, +servername sysname); + +/* want the names of the server id and the corresponding server names from the sys.sysservers and then insert into the table variable */ + +insert into @servername_dist (serverid, servername) select srvid, srvname from +sys.sysservers; + +/* we then retrieve the name of the server from the table variable */ + +select * from @servername_dist; +go +Listing 2-4. Retrieving the category type of the distribution database +use master +go +/* declare the table variable */ + +declare @databasename_dist table +( +dbname sysname, +categorytype int, +databaseid smallint +); + +/* want the names of the database, the database id and the category type from the sys.sysdatabases and then insert into the table variable */ + +insert into @databasename_dist(dbname,databaseid,categorytype) select name, +dbid,category from sys.sysdatabases; + +/* we then retrieve the name, the id and the category type of the database from the table variable */ +select databaseid, dbname, categorytype from @databasename_dist order by +databaseid; +go + +Listing 2-5. Retrieving the type of the Publisher and the security mode of the login +use msdb +go +/* declare the table variable */ + +declare @publishertype_dist table +( +servername sysname, +distdb sysname, +security int, +publishertype sysname +); +/* want the names of the server, the database, the security mode and +the Publisher type from the MSdistpublishers and then insert into the +table variable */ + +insert into @publishertype_dist(servername,distdb,security,publishertype) +select name, distribution_db,security_mode,publisher_type from +MSdistpublishers; + +/* we then retrieve the names of the server, the database, the security mode and the Publisher type from the table variable */ + +select servername,distdb,security,publishertype from @publishertype_dist; +go +Listing 2-6. Retrieving descriptions of the agent profiles +use msdb +go +/*retieve data from MSagent_profiles to see the agent definition */ + +select profile_id, +profile_name, +agent_type, +type, +description, +def_profile +from MSagent_profiles; +go + diff --git a/Codes/Chapter05/Chapter05codes.txt b/Codes/Chapter05/Chapter05codes.txt new file mode 100644 index 0000000..074699a --- /dev/null +++ b/Codes/Chapter05/Chapter05codes.txt @@ -0,0 +1,455 @@ +Listing 5-1. Dropping a pull subscription +/* Execute this on the Distributor server on the distribution database. The Distributor server is on the same machine as the Publisher server */ + +use distribution +go + +/*Declare a table variable */ + +declare @subscription_pull table +(publisher_id smallint, +publisher_db sysname, +subscriber_db sysname, +subscription_type int, +sync_type tinyint, +status tinyint); + +/* Insert data into the table variable from the MSsubscriptions table in the distribution database */ + +insert into @subscription_pull select +publisher_id, +publisher_db, +subscriber_db, +subscription_type, +sync_type, +status from distribution..MSsubscriptions +where subscription_type=1 and status =2 + +/* Check the data of the @subscription_pull table variable */ + +select * from @subscription_pull + +/* Declare table variable that will store the Publisher, the publication database, the type of publication, and the name of the publication using sp_helpsubscription_properties */ + +declare @subscriberinfo table +(publisher sysname, +publisher_db sysname, +publication_type int, +publication sysname); + +/* Insert the data into the @subscriberinfo table variable */ + +insert into @subscriberinfo +exec sp_helpsubscription_properties + +/* Check the data for the @subscriberinfo table variable */ +select * from @subscriberinfo + +/* Execute on the Subscriber on the subscription db - use the name of the Publisher, the publication database, and the name of the publication*/ + +exec sp_droppullsubscription 'BIO-V7V30JTZLZS','mysales_new','pub_mysalesnew' + +/* Finally, on the Publisher server on the publication database, remove the subscription for the Publisher*/ + +exec sp_dropsubscription 'pub_mysalesnew','all', 'BIO-V7V30JTZLZS' +go + +Listing 5-2. Dropping a push subscription +/* Execute this on the Distributor server on the distribution database. The Distributor server is on the same machine as the Publisher server */ + +use distribution +go + +/*Declare a table variable */ + +declare @subscription_push table +(publisher_id smallint, +publisher_db sysname, +subscriber_db sysname, +subscription_type int, +sync_type tinyint, +status tinyint); + +/* Insert data into the table variable from the MSsubscriptions table in the distribution database */ + +insert into @subscription_push select +publisher_id, publisher_db, subscriber_db, subscription_type, sync_type, +status from distribution..MSsubscriptions +where subscription_type=0 and status =2 + +/* Check the data of the @subscription_push table variable */ + +select * from @subscription_push + +/* Declare table variable that will store the Publisher and the +Subscriber information from the MSSubscriber_info table */ + +declare @subscriberinfo table +(publisher sysname, +subscriber sysname); + +/* Insert the data into the @subscriberinfo table variable */ + +insert into @subscriberinfo +select publisher, subscriber from distribution..MSsubscriber_info + +/* Check the data for the @subscriberinfo table variable */ +select * from @subscriberinfo + +/* Finally, on the Publisher server on the publication database +remove the subscription for the Publisher*/ + +exec sp_dropsubscription 'pub_mysalesnew','all', 'BIO-V7V30JTZLZS' +go +Listing 5-3. Dropping a publication +/* Use the distribution database to find the name of the publication */ + +Use distribution +Go + +Select * from MSpublications +Go + +/* Use the publication database */ +Use mysales_new +Go + +/* Finally drop the publication */ +sp_droppublication 'pub_mysalesnew' +Listing 5-4. Creating a snapshot publication +/* Enable the database for replication */ + +use master +exec sp_replicationdboption @dbname = 'mysales_new', +@optname = 'publish', +@value = 'true' +go + +/* Add the snapshot publication */ + +use [mysales_new] + +exec sp_addpublication @publication = 'pub_mysalesnew', +@description = 'Snapshot publication of database ''mysales_new'' +from Publisher ''SHW-TOR-WS039''.', +@sync_method = 'native', +@repl_freq = 'snapshot', +@status = 'active', +@allow_push = 'true', +@allow_pull = 'true', +@allow_anonymous = 'false', + +@immediate_sync = 'false', +@allow_sync_tran = 'false', +@autogen_sync_procs = 'false', +@retention = 336, +@allow_queued_tran = 'false', +@snapshot_in_defaultfolder = 'true', +@compress_snapshot = 'false', +@allow_dts = 'false', +@allow_subscription_copy = 'false', +@add_to_active_directory = 'false', +@replicate_ddl=1 +go +Listing 5-5. Creating the Snapshot Agent +/* Execute the stored procedure under the current publication database*/ + +use [mysales_new] + +exec sp_addpublication_snapshot @publication = 'pub_mysalesnew', +@frequency_type = 8, +@frequency_interval = 4, +@frequency_relative_interval = 1, +@frequency_recurrence_factor = 1, +@frequency_subday = 1, +@frequency_subday_interval = 1, +@active_start_time_of_day = 0, +@active_end_time_of_day = 235959, +@active_start_date = 0, +@active_end_date = 0, +@job_login = null, +@job_password = null, +@publisher_security_mode = 1 +go +Listing 5-6. Granting publication access to the users +/* Grant access to the current publication database and execute +on the publication database*/ + +exec sp_grant_publication_access @publication = 'pub_mysalesnew', +@login = 'distributor_admin' +go +exec sp_grant_publication_access @publication = 'pub_mysalesnew', +@login = 'sa' +go +Listing 5-7. Adding the articles to the publication +/* Adding each of the articles in the current publication */ + +use [mysales_new] +exec sp_addarticle @publication = 'pub_mysalesnew', +@article = 'AccountsReceivable', +@source_owner = 'myfinance', +@source_object = 'AccountsReceivable', +@type = 'logbased', +@description = null, +@creation_script = null, +@pre_creation_cmd = 'drop', + +@destination_table = 'AccountsReceivable', +@destination_owner = 'myfinance', +@vertical_partition = 'false' +go + +use [mysales_new] +exec sp_addarticle @publication = 'pub_mysalesnew', +@article = 'AccountInvoice', +@source_owner = 'myfinance', +@source_object = 'AccountInvoice', +@type = 'logbased', +@description = null, +@creation_script = null, +@pre_creation_cmd = 'drop', + +@destination_table = 'AccountInvoice', +@destination_owner = 'myfinance', +@vertical_partition = 'false' +go + +use [mysales_new] +exec sp_addarticle @publication = 'pub_mysalesnew', +@article = 'BillTo', +@source_owner = 'myorder' +@source_object = 'BillTo', +@type = 'logbased', +@description = null, +@creation_script = null, +@pre_creation_cmd = 'drop', + +@destination_table = 'BillTo', +@destination_owner = 'myorder', +@vertical_partition = 'false' +go +From sidebar Dropping An Article + +You can drop an article by executing the sp_droparticle stored procedure on the publication database on the Publisher server. The syntax for the code is as follows: +sp_droparticle @publication, @article, @ignore_distributor, +@force_invalidate_snapshot, @publisher, @from_drop_publication +Listing 5-8. Starting the Snapshot Agent job +/* Start the Snapshot Agent and execute this on the publication database*/ + +exec sp_startpublication_snapshot 'pub_mysalesnew' +Listing 5-9. Running the Snapshot Agent executable +/* Execute on the distribution database */ + +use distribution +go + +declare @distpub sysname; +set @distpub =(select convert(sysname, serverproperty('servername'))) +declare @publisherdatabases table +(pub_id smallint, +pubdb sysname, +id int) +insert into @publisherdatabases(pub_id,pubdb, id) +select publisher_id, publisher_db, id from MSpublisher_databases + +if (select top 1 publication_type from MSpublications)<>1 +begin +print 'this is not snapshot replication' +end +else +begin +declare @pubname sysname; +declare @pubdb sysname; +declare @cmd varchar(4000); +set @pubname= +(select top 1 b.publication +from @publisherdatabases a, MSpublications b where a.pub_id +=b.publisher_id) +set @pubdb= (select pubdb from @publisherdatabases) +/*end */ + +/* Execute the Snapshot Agent */ +set @cmd= +'"C:\Program Files\Microsoft SQL Server\90\COM\snapshot.exe" +-Publication @pubname -Publisher @distpub -Distributor @distpub + -DistributorSecurityMode 1' +exec xp_cmdshell '@cmd' +end +From the Sidebar:Enabling xp_cmdshell +/*Execute this on the master database */ +Use master +Go + +Exec sp_configure 'show advanced options', 1 +Go +Reconfigure with override +Go +Exec sp_configure 'xp_cmdshell', 1 +Go +Reconfigure with override +Go +Listing 5-10. Checking the status of the type of subscriptions for the publication +/* Check the allow_push column to see whether the subscription supports push subscriptions. Execute this on the distribution database*/ + +use distribution +go +Select publication, publisher_db, publication_type, allow_push from MSpublications +Listing 5-11. Adding the push subscription +/* Run the stored procedure on the publication database that supports +push subscription */ + +use mysales_new +go + +exec sp_addsubscription @publication = 'pub_mysalesnew' +@subscriber = 'BIO-V7V30JTZLZS', +@destination_db ='subpush_mysales_new', +@subscription_type = 'Push', +@sync_type = 'automatic', +@article = 'all', +@update_mode = 'read only', +@subscriber_type = 0 +Listing 5-12. Executing the agent +/*Execute this code on the publication database */ + +exec sp_addpushsubscription_agent @publication = 'pub_mysalesnew', +@subscriber = 'BIO-V7V30JTZLZS', +@subscriber_db = 'subpush_mysales_new', +@job_login = null, +@job_password = null, +@subscriber_security_mode = 1, +@frequency_type = 1, +@frequency_interval = 0, +@frequency_relative_interval = 0, +@frequency_recurrence_factor = 0, +@frequency_subday = 0, +@frequency_subday_interval = 0, +@active_start_time_of_day = 0, +@active_end_time_of_day = 0, +@active_start_date = 0, +@active_end_date = 19950101, +@enabled_for_syncmgr = 'False', +@dts_package_location = 'Distributor' +Listing 5-13. Checking whether the publication supports pull subscriptions +/*Execute it on the publication database */ + +sp_helppublication 'pub_mysalesnew' +Listing 5-14. Enabling the names of the publication, publication database, and Publisher server on the Subscriber server +/* Execute the code on the Subscriber server. Execute this on the +subscription database */ + +declare @publisher sysname; +declare @publication sysname; +declare @pbdb sysname; +set @publisher='BIO-V7V30JTZLZS'; +set @publication = 'pub_mysalesnew'; +set @pbdb ='mysales_new'; + +/* Add the pull subscription on the Subscriber server. Execute this on the subscription database */ + +exec sp_addpullsubscription +@publisher=@publisher, +@publication=@publication, +@publisher_db=@pbdb, + +@update_mode='read only' + +/* Add the Distribution Agent to synchronize the pull subscription. Execute this on the subscription database*/ + +exec sp_addpullsubscription_agent +@publisher=@publisher, +@publication=@publication, +@publisher_db=@pbdb, +@distributor=@publisher +@job_login=null, +@job_password=null +Listing 5-15. Enabling the subscriptions on the Publisher server +/* Execute this on the Publisher server. Execute on the publication database */ +/*declare the variables first */ + +declare @subscriber sysname; +declare @publication sysname; +declare @subdb sysname; +set @subscriber= 'BIO-V7V30JTZLZS'; +set @publication ='pub_mysalesnew'; +set @subdb ='subpull_mysales_new'; + +/* Now register the pull subscription */ + +exec sp_addsubscription +@publication=@publication, +@subscriber=@subscriber, +@destination_db=@subdb, +@article='all', +@subscription_type='pull', +@subscriber_type=0, +@update_mode='read only' +Listing 5-16. Synchronizing the pull subscription using the Distribution Agent +declare @subscriber sysname; +declare @subdb sysname; +declare @publisher sysname; +declare @pbdb sysname; +declare @distributor sysname; +declare @cmd varchar(1000); + +set @subscriber='BIO-V7V30JTZLZS'; +set @subdb ='subpull_mysales_new'; +set @publisher='BIO-V7V30JTZLZS'; +set @distributor = @publisher; +set @pbdb ='mysales_new'; + + +/* Execute the Distribution Agent */ + +set @cmd= +'"C:\Program Files\Microsoft SQL Server\90\COM\distribution.exe" +-Subscriber @subscriber -SubscriberDB @subdb -Publisher @publisher +-PublisherDB @pubdb -Distributor @distributor -DistributorSecurityMode 1 -Continuous +-SubscriptionStreams 4' +exec xp_cmdshell '@cmd' +go +Listing 5-17. Configuring an anonymous subscription +/* Execute the code on the Subscriber server; execute this on the +subscription database*/ + +declare @publisher sysname; +declare @publication sysname; +declare @pbdb sysname; + +/* Assign values to variables */ + +set @publisher='BIO-V7V30JTZLZS'; +set @publication ='pub_mysalesnew_anon'; +set @pbdb ='mysales_new'; + +/* Add the pull subscription on the Subscriber server; execute this on the subscription database */ + +exec sp_addpullsubscription +@publisher=@publisher, +@publication=@publication, +@publisher_db=@pbdb, + +@update_mode='read only' + +/* Add the agent to synchronize the pull subscription; execute this +on the subscription database*/ + +exec sp_addpullsubscription_agent +@publisher=@publisher, +@publication=@publication, +@publisher_db=@pbdb, +@distributor=@publisher, +@job_login=null, +@job_password=null + +/* Execute sp_addpublication on the Publisher server on the publication database; execute this on the publication database*/ + +use mysales_new +go + +exec sp_addpublication +@publication='pub_mysalesnew_anon', +@allow_pull='true', +@allow_anonymous='true', +@immediate_sync='true', +@independent_agent='true' diff --git a/Codes/Chapter06/Chapter06 codes.txt b/Codes/Chapter06/Chapter06 codes.txt new file mode 100644 index 0000000..2a54208 --- /dev/null +++ b/Codes/Chapter06/Chapter06 codes.txt @@ -0,0 +1,41 @@ +Listing 6-1. Execute the sp_lock stored procedure +/*Execute this on the publication database */ + +Use mysales +Go + +Exec sp_lock + +Listing 6-2. Viewing manager resources of active locks held by the publication database +/* Execute this on the publication database */ +Use mysales +Go + +Select * from sys.dm_tran_locks +Listing 6-3. Getting size information for sparse files in the current database file +/* Need to run from the current publication database */ +/* Declare the variables */ +declare @dbname sysname +declare @fileid int +declare @dbid smallint + +/* Get the name of the current database */ +set @dbname =(select db_name(db_id())); + +/* Get the current database id */ +set @dbid = (select db_id()); + +/* Get the ID of the data file for the current database. + Type=0 from the sys.database_files correspond to the +data file while type=1 correspond to the log file */ + +set @fileid= (select file_id from sys.database_files where type=0); + +/*Get the maximum bytes on the disk for the current data file and the corresponding SQL Server pages from fn_virtualfilestats */ + +select db_name(db_id()) as currentdatabase, +bytesondisk, +(bytesondisk/8192)as pages +from +fn_virtualfilestats (@dbid,@fileid) + diff --git a/Codes/Chapter07/Chapter07codes.txt b/Codes/Chapter07/Chapter07codes.txt new file mode 100644 index 0000000..7a7ebb7 --- /dev/null +++ b/Codes/Chapter07/Chapter07codes.txt @@ -0,0 +1,230 @@ +Listing 7-1. Executing sp_help_publication_access on a publication +/* Execute the stored procedure on the publication database + that contains the publication */ + +Use mysales_new +Go + +sp_help_publication_access 'pub_mysalesnew' + +Listing 7-2. Removing a login name from the PAL +/* Execute this on the publication database on the Publisher server */ + +sp_revoke_publication_access @publication='pub_mysalesnew', +@login=[BIO-V7V30JTZLZS\Sujoy Paul] + +Listing 7-3. Finding out whether the database is being published or not +/* Execute this on the publication database on the Publisher server */ + +Use mysales_new +Go + +Exec sp_dboption 'mysales_new' + +Listing 7-4. Viewing category column in bits on replication. +/* Execute on any database */ +Use mysales_new +Go + +select name,dbid, category,filename from sys.sysdatabases + +Listing 7-5. Finding the name of the publications that have been added in the syspublications system table +/* Execute this on the publication database on the Publisher */ + +select name, repl_freq, status, +sync_method, +independent_agent, +immediate_sync, +allow_push, +allow_pull, +allow_anonymous, +retention, +snapshot_in_defaultfolder, +alt_snapshot_folder, +compress_snapshot, +replicate_ddl +from syspublications + +Listing 7-6. Finding the articles added in the sysarticles system table when they were added to the publication +/* Execute this on the publication database */ + +select creation_script, +dest_table, +del_cmd, +ins_cmd, +upd_cmd, +name, +objid, +pubid, +type, +dest_owner +from sysarticles + +Listing 7-7. Getting information about the publications +/* Execute this on the distribution database */ + +select +publication_type, +publisher_db, +publication, +thirdparty_flag, +independent_agent, +immediate_sync, +allow_push, +allow_pull, +allow_anonymous, +retention, +sync_method, +vendor_name +from MSpublications +order by +publication_type + +Listing 7-8. Getting information on the articles in a publication +/* Execute this on distribution database */ + +select +publisher_db , +publication_id , +article , +destination_object , +source_owner , +source_object +from MSarticles +where source_owner like 'myinventory' + +Listing 7-9. Getting the data stored by the Snapshot Agent +/* Execute this on the distribution database */ +use distribution +go + +select +id, +name, +publisher_db, +publication, +publication_type, +job_id, +publisher_security_mode, +publisher_login, +job_step_uid +from MSsnapshot_agents + +Listing 7-10. Getting the history of the snapshot +/* Execute this on the distribution database */ +use distribution +go + +select +agent_id, +runstatus, +start_time, + time, +duration, +comments, +delivered_transactions, +delivered_commands, +delivery_rate, +error_id +from MSsnapshot_history where delivered_commands <>0 + +Listing 7-11. Getting the history associated with the Distribution Agent +/* Execute this on the distribution database */ +use distribution +go + +select +agent_id, +runstatus, +start_time, +time, +duration, +comments, +delivered_transactions, +delivery_rate, +error_id +from MSdistribution_history where +delivered_commands <>0 and runstatus<>3 + +Listing 7-12. Retrieving information about the subscriptions +/* Execute this on the distribution database */ +use distribution +go + +select +publisher_db, +publication_id, +article_id, +subscription_type, +subscriber_db, +status, +independent_agent +from MSsubscriptions where subscriber_db like 'sub%' + +Listing 7-13. Determining the Publisher and Subscriber servers for push subscriptions +/* Execute this on the distribution database */ +use distribution +go + +select +publisher, +subscriber, +type, +security_mode +from MSsubscriber_info +Listing 7-14. Viewing agent profile parameters +/* Execute this on the msdb database */ +use msdb +go + +select agent_type, +parameter_name, +default_value, +min_value, +max_value +from MSagentparameterlist +where agent_type=1 +Listing 7-15. Adding a new parameter to the Snapshot Agent profile +/* Execute this on the msdb database */ +use msdb +go +/*1. List all the profiles for the Snapshot Agent */ + +exec sp_help_agent_profile @agent_type=1 + +/* 2. Select the profile_id from step 1. Find out the parameters +and the corresponding values that are being used */ +/* profile_id=17 has a profile_name of Snapshot Agent profile-maxbcpthreads */ + +exec sp_help_agent_parameter @profile_id=17 + +/*3. Find out the available parameters and the corresponding +default, the minimum and the maximum values */ + +select agent_type, +parameter_name, +default_value, +max_value +from MSagentparameterlist +where agent_type=1 + +/*4. Now add the parameter MaxNetworkOptimization and set it to a value of 1*/ + +exec sp_add_agent_parameter @profile_id=17, +@parameter_name='MaxNetworkOptimization', +@parameter_value='1' + +Listing 7-16. Getting information from the MSreplication_subscription table +/* Execute this on a subscription database that is used for pull subscriptions */ + +Use subpull_mysales_new +Go + +select publisher, +publisher_db, +publication, +independent_agent, +subscription_type, +distribution_agent, +time +from MSreplication_subscriptions diff --git a/Codes/Chapter09/Chapter09codes.txt b/Codes/Chapter09/Chapter09codes.txt new file mode 100644 index 0000000..e262fda --- /dev/null +++ b/Codes/Chapter09/Chapter09codes.txt @@ -0,0 +1,1283 @@ +Listing 9-1. Enabling and creating the standard publication for transactional replication +/*Execute this on the publication database, mysales_copy */ + +use [mysales_copy] +exec sp_replicationdboption +@dbname = 'mysales_copy', +@optname = 'publish', +@value = 'true' +Go + +/* Add the transactional publication */ +/* The @synch_method is set to concurrent for transactional replication */ + +use [mysales_copy] +exec sp_addpublication @publication = 'pub_mysales_copy_myinventory', +@description = 'Transactional publication of database ''mysales_copy'' from +Publisher ''BIO-V7V30JTZLZS\BIOREPL_PEER''.', + +@sync_method = 'concurrent', +@retention = 0, @allow_push = 'true', @allow_pull = 'true', +@allow_anonymous = 'true', @snapshot_in_defaultfolder = 'true', + +@compress_snapshot = 'false', +@allow_subscription_copy = 'false', @add_to_active_directory = 'false', +@repl_freq = 'continuous', @status = 'active', + +@independent_agent = 'true', @immediate_sync = 'true', +@allow_sync_tran = 'false', @autogen_sync_procs = 'false', +@allow_queued_tran = 'false', + @replicate_ddl = 1, + +@allow_initialize_from_backup = 'false', + @enabled_for_p2p = 'false', + @enabled_for_het_sub = 'false' +go +Listing 9-2. Finding out whether the Log Reader Agent exists or not +/*Execute this on the publication database */ + +Use mysales_copy +Go + +sp_helplogreader_agent +Listing 9-3. Adding articles, including the usp_item_duplicates stored procedure +/* Execute sp_addarticle for the StockItem article */ + +use [mysales_copy] +exec sp_addarticle @publication = 'pub_mysales_copy_myinventory', +@article = 'StockItem', @source_owner = 'myinventory', +@source_object = 'StockItem', @type = 'logbased', +@description = null, +@creation_script = null, @pre_creation_cmd = 'drop', +@schema_option = 0x000000000803509F, + +@identityrangemanagementoption = 'manual', +@destination_table = 'StockItem', @destination_owner = 'myinventory', +@vertical_partition = 'false', + +@ins_cmd = 'CALL sp_MSins_myinventoryStockItem', +@del_cmd = 'CALL sp_MSdel_myinventoryStockItem', +@upd_cmd = 'SCALL sp_MSupd_myinventoryStockItem' +GO + +/* Execute sp_addarticle for the Customer article */ + +use [mysales_copy] +exec sp_addarticle @publication = 'pub_mysales_copy_myinventory', +@article = 'Customer', @source_owner = 'myorder', +@source_object = 'Customer', @type = 'logbased', + +@description = null, @creation_script = null, +@pre_creation_cmd = 'drop', @schema_option = 0x000000000803509F, + @identityrangemanagementoption = 'manual', + +@destination_table = 'Customer', @destination_owner = 'myorder', +@vertical_partition = 'false', + +@ins_cmd = 'CALL sp_MSins_myorderCustomer', +@del_cmd = 'CALL sp_MSdel_myorderCustomer', +@upd_cmd = 'SCALL sp_MSupd_myorderCustomer' +GO + +/* Execute sp_addarticle for the Stock article */ + +use [mysales_copy] +exec sp_addarticle @publication = 'pub_mysales_copy_myinventory', +@article = 'Stock', @source_owner = 'myorder', +@source_object = 'Stock', @type = 'logbased', + +@description = null, @creation_script = null, +@pre_creation_cmd = 'drop', @schema_option = 0x000000000803509F, + @identityrangemanagementoption = 'manual', + +@destination_table = 'Stock', @destination_owner = 'myorder', +@vertical_partition = 'false', + +@ins_cmd = 'CALL sp_MSins_myorderStock', +@del_cmd = 'CALL sp_MSdel_myorderStock', +@upd_cmd = 'SCALL sp_MSupd_myorderStock' +GO + +/* Execute sp_addarticle for the Item article */ + +use [mysales_copy] +exec sp_addarticle @publication = 'pub_mysales_copy_myinventory', +@article = 'Item', @source_owner = 'myinventory', +@source_object = 'Item', @type = 'logbased', + +@description = null, @creation_script = null, +@pre_creation_cmd = 'drop', @schema_option = 0x000000000803509F, + @identityrangemanagementoption = 'manual', + +@destination_table = 'Item', @destination_owner = 'myinventory', +@vertical_partition = 'false', + +@ins_cmd = 'CALL sp_MSins_myinventoryItem', +@del_cmd = 'CALL sp_MSdel_myinventoryItem', +@upd_cmd = 'SCALL sp_MSupd_myinventoryItem' +GO + +/* Execute sp_addarticle for the Warehouse article */ + +use [mysales_copy] +exec sp_addarticle @publication = 'pub_mysales_copy_myinventory', +@article = 'Warehouse', @source_owner = 'myinventory', +@source_object = 'Warehouse', @type = 'logbased', + +@description = null, @creation_script = null, +@pre_creation_cmd = 'drop', @schema_option = 0x000000000803509F, + @identityrangemanagementoption = 'manual', + +@destination_table = 'Warehouse', +@destination_owner = 'myinventory', @vertical_partition = 'false', + +@ins_cmd = 'CALL sp_MSins_myinventoryWarehouse', +@del_cmd = 'CALL sp_MSdel_myinventoryWarehouse', +@upd_cmd = 'SCALL sp_MSupd_myinventoryWarehouse', +@filter_clause = '[Whse_City] =''Vancouver''' + +/* Add the article filter */ + +exec sp_articlefilter @publication = 'pub_mysales_copy_myinventory', +@article = 'Warehouse', @filter_name = 'FLTR_Warehouse_1__63', + +@filter_clause = '[Whse_City] =''Vancouver''', +@force_invalidate_snapshot = 1, + @force_reinit_subscription = 1 + +/* Add the article synchronization object */ + +exec sp_articleview @publication = 'pub_mysales_copy_myinventory', +@article = 'Warehouse', @view_name = 'SY C_Warehouse_1__63', +@filter_clause = '[Whse_City] =''Vancouver''', +@force_invalidate_snapshot = 1, @force_reinit_subscription = 1 +GO + +/* Add the stored procedure */ + +use [mysales_copy] +go + +/* Check the source owner and the destination owner of the +stored procedure before executing the following code.*/ + +exec sp_addarticle @publication = 'pub_mysales_copy_myinventory', + @article = 'usp_item_duplicates', +@source_owner = 'dbo', @source_object = 'usp_item_duplicates', + + @type = 'proc schema only', +@description = null, @creation_script = null, +@pre_creation_cmd = 'drop', +@schema_option = 0x0000000008000001, +@destination_table = 'usp_item_duplicates', +@destination_owner = 'dbo' +GO +Listing 9-4. Creating the Snapshot Agent +/* Execute the stored procedure on the current publication database */ + +exec sp_addpublication_snapshot +@publication = 'pub_mysales_copy_myinventory', + @frequency_type = 1, +@frequency_interval = 0, + +@frequency_relative_interval = 0, +@frequency_recurrence_factor = 0, +@frequency_subday = 0, + +@frequency_subday_interval = 0, +@active_start_time_of_day = 0, +@active_end_time_of_day = 235959, + +@active_start_date = 0, +@active_end_date = 0, +@job_login = null, + +@job_password = null, +@publisher_security_mode = 1 +Listing 9-5. Starting the Snapshot Agent job +/* Execute this on the publication database */ +Use mysales_copy +Go + +Exec sp_startpublication_snapshot 'pub_mysales_copy_myinventory' +Go +Listing 9-6. Setting up a push subscription for standard transactional replication +/* Execute this on the publication database */ +use mysales_copy +go + +exec sp_addsubscription @publication = + 'pub_mysales_copy_myinventory', +@subscriber = 'BIO-V7V30JTZLZS\BIOREPL_PEER', +@destination_db = 'mysalescopy_stpub_remotepush', + +@subscription_type = 'Push', + @sync_type = 'automatic', +@article = 'all', +@update_mode = 'read only', +@subscriber_type = 0 + +exec sp_addpushsubscription_agent @publication = + 'pub_mysales_copy_myinventory', +@subscriber = 'BIO-V7V30JTZLZS\BIOREPL_PEER', + +@subscriber_db = 'mysalescopy_stpub_remotepush', +@job_login = null, + @job_password = null, +@subscriber_security_mode = 1, + @frequency_type = 64, + +@frequency_interval = 0, + @frequency_relative_interval = 0, +@frequency_recurrence_factor = 0, + @frequency_subday = 0, + @frequency_subday_interval = 0, + @active_start_time_of_day = 0, + +@active_end_time_of_day = 235959, +@active_start_date = 20060111, +@active_end_date = 99991231, + +@enabled_for_syncmgr = 'False', +@dts_package_location = 'Distributor' +go +Listing 9-7. Setting up a pull subscription for standard publication for transactional replication +/*1. Execute this on the Publisher server on the publication +database */ + +use mysales_copy +go + +exec sp_addsubscription @publication = + 'pub_mysales_copy_myinventory', +@subscriber = 'BIO-V7V30JTZLZS\BIOREPL_PEER', +@destination_db = 'mysalescopyinven_stdpub_remotepull', + +@sync_type = 'Automatic', +@subscription_type = 'pull', +@update_mode = 'read only' +Go + +/* 2. Execute this on the subscription database on the Subscriber server */ + +use mysalescopyinven_stdpub_remotepull +go + +exec sp_addpullsubscription @publisher = + 'BIO-V7V30JTZLZS\BIOREPL_PEER', @publication = + 'pub_mysales_copy_myinventory', +@publisher_db = 'mysales_copy', + +@independent_agent = 'True', +@subscription_type = 'pull', + +@description = '', +@update_mode = 'read only', +@immediate_sync = 1 + +exec sp_addpullsubscription_agent @publisher = + 'BIO-V7V30JTZLZS\BIOREPL_PEER', + @publisher_db = 'mysales_copy', +@publication = 'pub_mysales_copy_myinventory', + +@distributor = 'BIO-V7V30JTZLZS\BIOREPL_PEER', +@distributor_security_mode = 1, +@distributor_login = '', +@distributor_password = null, + +@enabled_for_syncmgr = 'False', +@frequency_type = 64, +@frequency_interval = 0, +@frequency_relative_interval = 0, +@frequency_recurrence_factor = 0, + +@frequency_subday = 0, + @frequency_subday_interval = 0, + @active_start_time_of_day = 0, + @active_end_time_of_day = 235959, +@active_start_date = 20060113, + +@active_end_date = 99991231, +@alt_snapshot_folder = '', + @working_directory = '', +@job_login = null, +@job_password = null, +@publication_type = 0 +GO +Listing 9-8. Configuring the transactional publication +/*1. Enable the replication database */ + +use master + +exec sp_replicationdboption @dbname = 'mysales_copy', +@optname = 'publish', +@value = 'true' + +GO + +/* 2. Add the transactional publication for immediate +update subscriptions */ + +use [mysales_copy] +go +exec sp_addpublication @publication = 'pub_updsub_mysales_copy', +@description = 'Transactional publication with updatable +subscriptions of database ''mysales_copy'' from Publisher +''BIO-V7V30JTZLZS\BIOREPL_PEER''.', + +@sync_method = 'concurrent', +@retention = 0, + +@allow_push = 'true', +@allow_pull = 'true', +@snapshot_in_defaultfolder = 'true', + +@allow_subscription_copy = 'false', +@add_to_active_directory = 'false', +@repl_freq = 'continuous', + +@status = 'active', +@independent_agent = 'true', +@immediate_sync = 'true', + +@allow_sync_tran = 'true', +@autogen_sync_procs = 'true', +@allow_queued_tran = 'true', + +@conflict_policy = 'pub wins', +@centralized_conflicts = 'true', +@conflict_retention = 14, + +@queue_type = 'sql', +@replicate_ddl = 1, +@allow_initialize_from_backup = 'false', + +@enabled_for_p2p = 'false', +@enabled_for_het_sub = 'false' +GO + +/* 3. Execute the stored procedure on the current publication database to create the Snapshot Agent */ + +use [mysales_copy] +go + +exec sp_addpublication_snapshot @publication = + 'pub_updsub_mysales_copy', @frequency_type = 1, +@frequency_interval = 0, + +@frequency_relative_interval = 0, +@frequency_recurrence_factor = 0, +@frequency_subday = 0, + +@frequency_subday_interval = 0, +@active_start_time_of_day = 0, +@active_end_time_of_day = 235959, + +@active_start_date = 0, @active_end_date = 0, +@job_login = null, @job_password = null, +@publisher_security_mode = 1 + +/* 4. Add the articles */ + +use [mysales_copy] +go + +/* Execute sp_addarticle for the Customer article */ + +exec sp_addarticle @publication = 'pub_updsub_mysales_copy', +@article = 'Customer', @source_owner = 'myorder', + @source_object = 'Customer', @type = 'logbased', + +@description = null, @creation_script = null, +@pre_creation_cmd = 'drop', +@schema_option = 0x0000000008035CDF, + +@identityrangemanagementoption = 'manual', +@destination_table = 'Customer', +@destination_owner = 'myorder', @status = 16, + + @vertical_partition = 'false' +GO + +/* Execute sp_addarticle for the Item article */ + +exec sp_addarticle @publication = 'pub_updsub_mysales_copy', +@article = 'Item', @source_owner = 'myinventory', +@source_object = 'Item', @type = 'logbased', + +@description = null, @creation_script = null, +@pre_creation_cmd = 'drop', +@schema_option = 0x0000000008035CDF, + +@identityrangemanagementoption = 'manual', +@destination_table = 'Item', +@destination_owner = 'myinventory', @status = 16, + +@vertical_partition = 'false' +GO + +/* Execute sp_addarticle for the StockItem article */ + +exec sp_addarticle @publication = 'pub_updsub_mysales_copy', +@article = 'StockItem', @source_owner = 'myinventory', +@source_object = 'StockItem', @type = 'logbased', + +@description = null, @creation_script = null, +@pre_creation_cmd = 'drop', + @schema_option = 0x0000000008035CDF, +@identityrangemanagementoption = 'manual', + +@destination_table = 'StockItem', +@destination_owner = 'myinventory', + @status = 16, +@vertical_partition = 'false' +GO + +/* Execute sp_addarticle for the Warehouse article */ + +exec sp_addarticle @publication = 'pub_updsub_mysales_copy', +@article = 'Warehouse', + @source_owner = 'myinventory', +@source_object = 'Warehouse', + @type = 'logbased', + +@description = '', @creation_script = null, +@pre_creation_cmd = 'drop', + @schema_option = 0x0000000008035CDF, + @identityrangemanagementoption = 'manual', + +@destination_table = 'Warehouse', +@destination_owner = 'myinventory', + @status = 16, +@vertical_partition = 'false' +GO + +/* Execute sp_addarticle for the usp_item_duplicates article */ + +exec sp_addarticle @publication = 'pub_updsub_mysales_copy', +@article = 'usp_item_duplicates', + @source_owner = 'dbo', +@source_object = 'usp_item_duplicates', + +@type = 'proc schema only', + @description = null, +@creation_script = null, + @pre_creation_cmd = 'drop', +@schema_option = 0x0000000008000001, + +@destination_table = 'usp_item_duplicates', +@destination_owner = 'dbo' +GO +Listing 9-9. Verifying whether the publication supports immediate updating subscriptions +/* Execute this on the publication database */ + +Use mysales_new +Go + +sp_helppublication + +Listing 9-10. Creating the pull subscription +/* Execute this on the subscription database on the Subscriber that is going to be used for pull subscription */ + +use mysalescopy_upd_remotepull +go + +exec sp_addpullsubscription +@publisher='BIO-V7V30JTZLZS\BIOREPL_PEER', +@publication = 'pub_updsub_mysales_copy', +@publisher_db = 'mysales_copy', @independent_agent = 'True', + +@subscription_type = 'pull', +@update_mode = 'failover', +@immediate_sync = 1 +go +Listing 9-11. Adding the scheduled agent to synchronize the pull subscription +/* Execute this on the subscription database on the Subscriber server */ + +Use mysales_copy +Go + +exec sp_addpullsubscription_agent +@publisher = 'BIO-V7V30JTZLZS\BIOREPL_PEER', +@publisher_db = 'mysales_copy', @publication = 'pub_updsub_mysales_copy', + +@distributor = 'BIO-V7V30JTZLZS\BIOREPL_PEER', +@distributor_security_mode = 1, @distributor_login = '', +@distributor_password = null, +@enabled_for_syncmgr = 'False', +@frequency_type = 64, +@frequency_interval = 0, + +@frequency_relative_interval = 0, +@frequency_recurrence_factor = 0, +@frequency_subday = 0, + +@frequency_subday_interval = 0, +@active_start_time_of_day = 0, +@active_end_time_of_day = 235959, + +@active_start_date = 20060108, +@active_end_date = 99991231, +@alt_snapshot_folder = '', @working_directory = '', + +@job_login = null, @job_password = null, +@publication_type = 0 +GO +Listing 9-12. Configuring the Subscriber server triggers for immediate updating subscriptions +/* Execute this on the subscription database on the Subscriber server */ + +use mysalescopy_upd_remotepull +go + +exec sp_link_publication @publisher = + 'BIO-V7V30JTZLZS\BIOREPL_PEER', + @publication = 'pub_updsub_mysales_copy', + @publisher_db = 'mysales_copy', + @security_mode = 0, + @login = 'sa', + @password = null +go +Listing 9-13. Adding the subscription on the Publisher server +/* Execute this on the publication database on the Publisher server */ + +use [mysales_copy] +go + +exec sp_addsubscription @publication = 'pub_updsub_mysales_copy', +@subscriber = 'BIO-V7V30JTZLZS\BIOREPL_PEER', +@destination_db = 'mysalescopy_upd_remotepull', + + @sync_type = 'Automatic', +@subscription_type = 'pull', +@update_mode = 'failover' +GO + +Listing 9-14. Adding the push subscription and agent, and configuring the triggers' security settings +/* Execute this code on the publication database on the Publisher */ + +use mysales_copy +go + +/* Add the push subscription on the Publisher */ + +exec sp_addsubscription @publication = 'pub_updsub_mysales_copy', +@subscriber = 'BIO-V7V30JTZLZS\BIOREPL_PEER', +@destination_db = 'mysalescopy_upd_remotepush', + +@subscription_type = 'Push', +@sync_type = 'automatic', +@article = 'all', + +@update_mode = 'failover', +@subscriber_type = 0 +go + + +/* Add the push subscription agent on the Publisher server */ + +exec sp_addpushsubscription_agent +@publication = 'pub_updsub_mysales_copy', + @subscriber = 'BIO-V7V30JTZLZS\BIOREPL_PEER', +@subscriber_db = 'mysalescopy_upd_remotepush', + +@job_login = null, @job_password = null, +@subscriber_security_mode = 1, +@frequency_type = 64, + +@frequency_interval = 0, +@frequency_relative_interval = 0, +@frequency_recurrence_factor = 0, + +@frequency_subday = 0, +@frequency_subday_interval = 0, +@active_start_time_of_day = 0, + @active_end_time_of_day = 235959, + +@active_start_date = 20060108, +@active_end_date = 99991231, +@enabled_for_syncmgr = 'False' +go + +/* Configure the security information using sp_link_publication on the +Subscriber server*/ + +use mysalescopy_upd_remotepush +go + +exec sp_link_publication +@publisher = 'BIO-V7V30JTZLZS\BIOREPL_PEER', + @publisher_db = 'mysales_copy', +@publication = 'pub_updsub_mysales_copy', + +@distributor = 'BIO-V7V30JTZLZS\BIOREPL_PEER', + +@security_mode = 0, +@login = 'spaul', +@password = null +go + +Listing 9-15. Configuration of the push subscription for queued updating +/* Add the push subscription on the Publisher server */ + +use mysales_copy +go + +exec sp_addsubscription @publication = 'pub_updsub_mysales_copy', + @subscriber = 'BIO-V7V30JTZLZS\BIOREPL_PEER', +@destination_db = 'mysalescopy_qud_remotepush', + +@subscription_type = 'Push', +@sync_type = 'automatic', +@article = 'all', + +@update_mode = 'queued failover', +@subscriber_type = 0 + +/* Add the push subscription agent on the Publisher */ + +exec sp_addpushsubscription_agent @publication = + 'pub_updsub_mysales_copy', +@subscriber = 'BIO-V7V30JTZLZS\BIOREPL_PEER', +@subscriber_db = 'mysalescopy_qud_remotepush', + +@job_login = null, @job_password = null, + @subscriber_security_mode = 1, +@frequency_type = 64, + +@frequency_interval = 0, +@frequency_relative_interval = 0, +@frequency_recurrence_factor = 0, + +@frequency_subday = 0, @frequency_subday_interval = 0, +@active_start_time_of_day = 0, +@active_end_time_of_day = 235959, + +@active_start_date = 20060108, +@active_end_date = 99991231 +@enabled_for_syncmgr = 'False' +go + +/* Add the sp_link_publication since the subscription has the +@update_mode parameter +Set to 'queued failover' */ + +/* Execute this on the subscription database on the Subscriber server */ + +use mysalescopy_qud_remotepush +go + +exec sp_link_publication @publisher = +'BIO-V7V30JTZLZS\BIOREPL_PEER', +@publisher_db = 'mysales_copy', +@publication ='pub_updsub_mysales_copy', + +@distributor = 'BIO-V7V30JTZLZS\BIOREPL_PEER', +@security_mode = 0, @login = 'sa', +@password = null +go +Listing 9-16. Configuring a pull subscription for queued updating +/* 1. Execute this on the subscription database on the Subscriber server */ + +use mysalescopy_qud_remotepull +go + +exec sp_addpullsubscription @publisher = +'BIO-V7V30JTZLZS\BIOREPL_PEER', + @publication ='pub_updsub_mysales_copy', +@publisher_db = 'mysales_copy', + +@independent_agent ='True', +@subscription_type ='pull', +@update_mode = 'queued failover', + +@immediate_sync = 1 + +/* 2. Configure the security settings since the subscription has @update_mode parameter set to 'queued failover' */ +/* Execute this on the Subscriber server */ + +exec sp_link_publication @publisher = 'BIO-V7V30JTZLZS\BIOREPL_PEER', +@publication = 'pub_updsub_mysales_copy', +@publisher_db ='mysales_copy', + +@security_mode = 0, +@login ='sa', +@password = null + +exec sp_addpullsubscription_agent @publisher = +'BIO-V7V30JTZLZS\BIOREPL_PEER', +@publisher_db = 'mysales_copy', +@publication = 'pub_updsub_mysales_copy', + +@distributor = 'BIO-V7V30JTZLZS\BIOREPL_PEER', +@distributor_security_mode = 1, +@distributor_login = '', + +@distributor_password = null, +@enabled_for_syncmgr = 'False', +@frequency_type = 64, + +@frequency_interval = 0, +@frequency_relative_interval = 0, +@frequency_recurrence_factor = 0, + +@frequency_subday = 0, +@frequency_subday_interval = 0, +@active_start_time_of_day = 0, + +@active_end_time_of_day = 235959, +@active_start_date = 20060108, +@active_end_date = 99991231, + +@alt_snapshot_folder = '', +@working_directory = '', +@job_login = null, + +@job_password = null, +@publication_type = 0 +Go + +/* Add the subscription on the Publisher server */ + +use mysales_copy +go + +exec sp_addsubscription @publication = +'pub_updsub_mysales_copy', +@subscriber = 'BIO-V7V30JTZLZS\BIOREPL_PEER', +@destination_db = 'mysalescopy_qud_remotepull', + +@sync_type = 'Automatic', +@subscription_type = 'pull', +@update_mode = 'queued failover' +GO +Listing 9-17. Verifying the subscription supports the failover option +/* Execute this on the publication database for the push subscription */ +Use mysales_copy +Go + +sp_helpsubscription 'pub_updsub_mysales_copy' +go +Listing 9-18. Changing the mode of the updatable subscription +/* Execute this on the subscription database on the Subscriber server */ + +sp_setreplfailovermode 'BIOREPL_PEER','mysales_copy', +'pub_updsub_mysales_copy','queued' +Listing 9-19. Adding the publication on node A, BIOREPL server +/*Execute this on the BIOREPL server */ + +use purchaseorder_repl +go + +select DATABASEPROPERTYEX ('purchaseorder_repl', 'IsSyncWithBackup') +go + +/* If the preceding select statement returns 0, execute sp_replicationdboption. If it returns a value of 1, +the database is enabled for publication.*/ + +sp_replicationdboption @dbname='purchaseorder_repl', +@optname='publish', +@value='true' +go + +sp_addpublication @publication='pub_purchaseorder_repl', +@restricted='false', +@sync_method='native', + +@repl_freq='continuous', +@allow_push='true', + +@allow_pull='true', + +@immediate_sync='true', +@allow_sync_tran='false', + +@autogen_sync_procs='false', +@retention=60, +@independent_agent='true', + +@enabled_for_p2p='true', +@status='active', +@allow_initialize_from_backup='true' +go +Listing 9-20. Adding the articles to the publication on node A +/*Execute this on the publication database */ +use purchaseorder_repl +go + +sp_addarticle @publication='pub_purchaseorder_repl', +@article='vendor', +@source_owner='dbo', + +@source_object='vendor', +@destination_table='[BIO-V7V30JTZLZS\BIOREPL_PEER].[purchaseorder_peer].[vendor]', + +@type='logbased', +@creation_script='null', +@schema_option='null', + +@status=16, +@ins_cmd='CALL sp_ins_vendor', +@del_cmd='XCALL sp_del_vendor', + +@upd_cmd='XCALL sp_upd_vendor', +@sync_object='null' +Go +Listing 9-21. Adding the subscription on node A +/* Execute this on the subscription database on node A, BIOREPL server */ + +exec sp_addsubscription @publication='pub_purchaseorder_repl', +@subscriber ='BIO-V7V30JTZLZS\BIOREPL_PEER', +@destination_db ='purchaseorder_peer', + +@subscription_type = 'Push', +@sync_type = 'replication support only', +@article = 'all', + +@subscriber_type = 0 +Go +Listing 9-22. Adding the push subscription agent on node A +/* Execute this on node A, BIOREPL server, on the publication database */ + +exec sp_addpushsubscription_agent +@publication='pub_purchaseorder_repl', +@subscriber = 'BIO-V7V30JTZLZS\BIOREPL_PEER', +@subscriber_db = 'purchaseorder_peer', + +@job_login = null, +@job_password = null, +@subscriber_security_mode = 1, + +@frequency_type = 64, +@frequency_interval = 0, +@frequency_relative_interval = 0, + +@frequency_recurrence_factor = 0, +@frequency_subday = 0, +@frequency_subday_interval = 0, + +@active_start_time_of_day = 0, +@active_end_time_of_day = 235959, +@active_start_date = 20060111, + +@active_end_date = 99991231, +@enabled_for_syncmgr = 'False', +@dts_package_location = 'Distributor' +Listing 9-23. Add the publication on node B +/*Execute this on node B, BIOREPL_PEER server */ +/*Execute on the publication database */ + +use purchaseorder_peer +go +/* If the preceding select statement returns 0, execute + sp_replicationdboption. If it returns a value of 1, +the database is enabled for publication. Go straight to +addition of the publication*/ + +sp_replicationdboption @dbname='purchaseorder_peer', +@optname='publish', +@value='true' +go + +/*Addition of the publication*/ +sp_addpublication @publication='pub_purchaseorder_peer', +@restricted='false', +@sync_method='native', +@repl_freq='continuous', + +@status='active', +@allow_push='true', +@allow_pull='true', + +@immediate_sync='false', +@allow_sync_tran='false', +@autogen_sync_procs='false', + +@retention=60, +@independent_agent='true', +@enabled_for_p2p='true', + +@status='active', +@allow_initialize_from_backup='true' +go +Listing 9-24. Adding the articles to the publication on node B, BIOREPL_PEER +/* Add this article to the publication */ +/*Execute this on the publication database */ +use purchaseorder_peer +go + +exec sp_addarticle @publication='pub_purchaseorder_peer', +@article='vendor', +@source_owner='dbo', + +@source_object='vendor', +@destination_table='[BIO-V7V30JTZLZS\REPL].[purchaseorder_peer].[vendor]', +@type='logbased', + +@creation_script='null', +@schema_option='null', +@status=16, + +@ins_cmd='CALL sp_ins_vendor', +@del_cmd='XCALL sp_del_vendor', +@upd_cmd='XCALL sp_upd_vendor', + +@sync_object=null +Go +Listing 9-25. Adding the subscription on node B, BIOREPL_PEER +/* Execute this on the subscription database on the BIOREPL_PEER server */ + +exec sp_addsubscription @publication='pub_purchaseorder_peer', +@subscriber ='BIO-V7V30JTZLZS\BIOREPL', +@destination_db ='purchaseorder_peer', + +@subscription_type = 'Push', +@sync_type = 'replication support only', +@article = 'all', + +@subscriber_type = 0 +Go +Listing 9-26. Add the push subscription agent on node B, BIOREPL_PEER +/*Execute this on the publication database on node B*/ +exec sp_addpushsubscription_agent +@publication='pub_purchaseorder_repl', +@subscriber = 'BIO-V7V30JTZLZS\BIOREPL', +@subscriber_db = 'purchaseorder_peer', + +@job_login = null, +@job_password = null, +@subscriber_security_mode = 1, + +@frequency_type = 64, +@frequency_interval = 0, +@frequency_relative_interval = 0, + +@frequency_recurrence_factor = 0, +@frequency_subday = 0, +@frequency_subday_interval = 0, + +@active_start_time_of_day = 0, +@active_end_time_of_day = 235959, +@active_start_date = 20060111, @active_end_date = 99991231, + +@enabled_for_syncmgr = 'False', +@dts_package_location = 'Distributor' +Listing 9-27. Adding the Log Reader Agent on both the nodes +/* Execute this on the BIOREPL(A) node */ + +sp_addlogreader_agent @joblogin='spaul', +@jobpassword='****', +@publisher_security_mode=1, + +@publisher_login='spaul' +@publisher_password='password', +go + +/* Execute this on the BIOREPL_PEER(B) node */ + +sp_addlogreader_agent @joblogin='spaul', +@jobpassword='****', +@publisher_security_mode=1, + +@publisher_login='spaul' +@publisher_password='password', +Go +Listing 9-28. Ensuring that all the peer-to-peer nodes have received the data +/*1. Execute this on the purchaseorder_repl publication database on +the BIOREPL server */ +/* insert the row first on the publication database */ + +insert into vendor values +(2,'Ferns Gardens','24 Wayne Blvd.','Toronto','M5h 2KL', +'1-800-123-4567') +go +/* 2. Execute this on the BIOREPL_PEER server node*/ +/* Execute this on the publication database on this node */ + +/* Declare the table variable*/ +declare @peertopeertable_received table +(id int, +publication sysname, +sent_date datetime, +description varchar(255)); + +/*Read the data from the MSpeer_request table */ + +insert into @peertopeertable_received +(id, publication, sent_date, description)select id,publication,sent_date, +description from MSpeer_request + +/* Retrieve the data */ + +select * from @peertopeertable_received +go +Listing 9-29. Ensuring BIOREPL_PEER receives the responses in the result set + /* Execute this on the publication database on the node that is being checked */ + +Sp_helppeerresponses '4' +Go +Listing 9-30 Adding the publication in mysales +/*Execute this on the master database */ + +use master +go + +---Enable the databases for transactional publishing. +sp_replicationdboption @dbname='mysales1', +@optname='publish', +@value='true'; +sp_replicationdboption @dbname='mysales2', +@optname='publish', +@value='true'; +GO +Listing 9-31. Adding the publication, articles, and Log Reader Agent for the mysales database +/*Execute this on the mysales database */ +use mysales +go + +DECLARE @publication AS sysname; +DECLARE @article1 AS sysname; +DECLARE @article2 AS sysname; +DECLARE @login AS sysname; +DECLARE @password AS varchar(512); +SET @publication = 'bidirectional_mysalespub'; +SET @article1 = 'Item'; +SET @article2 = 'Item2'; +---SET @login = 'BIO-V7V30JTZLS\SujoyPaul'; +---SET @password = 'sujoy'; + +--- Add the publication ----- + + +EXEC sp_addpublication @publication = @publication, +@restricted = 'false', +@sync_method = 'native', +@repl_freq = 'continuous', +@description = 'publ1', +@status = 'active', +@allow_push = 'true', +@allow_pull = 'true', +@allow_anonymous = 'false', +@enabled_for_internet = 'false', +@independent_agent = 'false', +@immediate_sync = 'false', +@allow_sync_tran = 'false', +@autogen_sync_procs = 'false', +@retention = 60; + +--- Add the articles --- + +EXEC sp_addarticle @publication = @publication, +@article = @article1, +@source_owner = 'myinventory', +@source_object = @article1, +@destination_table = @article2, +@type = 'logbased', +@creation_script = null, +@description = null, +@pre_creation_cmd = 'drop', +@schema_option = 0x00000000000000F1, +@status = 16, +@vertical_partition = 'false', +@ins_cmd = 'CALL sp_MSins_myinventoryItem ', +@del_cmd = 'XCALL sp_MSdel_myinventoryItem', +@upd_cmd = 'XCALL sp_MSupd_myinventoryItem', +@filter = null, +@sync_object = null; + +--- Add the Log Reader Agent + +EXEC sp_addlogreader_agent +/* the login name should be valid Windows Login in the form : 'MACHINE\Login' or 'DOMAIN\Login'. It is also not necessary to specify the login and the password*/ +@job_login = @login, +@job_password = @password, +@publisher_security_mode = 1; +go +Listing 9-32. Adding the publication, articles, and Log Reader Agent for the mysales2 database +/*Execute this on the mysales2 database */ +use mysales2 +go + +DECLARE @publication AS sysname; +DECLARE @article1 AS sysname; +DECLARE @article2 AS sysname; +DECLARE @login AS sysname; +DECLARE @password AS nvarchar(512); +SET @publication = 'bidirectional_mysalespub2'; +SET @article1 = 'Item'; +SET @article2 = 'Item2'; +---SET @login = 'BIO-V7V30JTZLS\SujoyPaul'; +---SET @password = 'sujoy'; + + +--- Add the publication ----- + +EXEC sp_addpublication @publication = @publication, +@restricted = 'false', +@sync_method = 'native', +@repl_freq = 'continuous', +@description = 'pub2', +@status = 'active', +@allow_push = 'true', +@allow_pull = 'true', +@allow_anonymous = 'false', +@enabled_for_internet = 'false', +@independent_agent = 'false', +@immediate_sync = 'false', +@allow_sync_tran = 'false', +@autogen_sync_procs = 'false', +@retention = 60; + + +--- Add the articles --- + +EXEC sp_addarticle @publication = @publication, +@article = @article2, +@source_owner = 'myinventory', +@source_object = @article2, +@destination_table = @article1, +@type = 'logbased', +@creation_script = null, +@description = null, +@pre_creation_cmd = 'drop', +@schema_option = 0x00000000000000F1, +@status = 16, +@vertical_partition = 'false', +@ins_cmd = 'CALL sp_MSins_myinventoryItem2', +@del_cmd = 'XCALL sp_MSdel_myinventoryItem2', +@upd_cmd = 'XCALL sp_MSupd_myinventoryItem2', +@filter = null, +@sync_object = null; + + +--- Add the Log Reader Agent +EXEC sp_addlogreader_agent +/* the login name should be valid Windows Login in the form : 'MACHINE\Login' or 'DOMAIN\Login'. It is also not necessary to specify the login and the password*/ +@job_login = @login, +@job_password = @password, +@publisher_security_mode = 1; +go +Listing 9-33. Add subscriptions for both databases +:setvar logintimeout 120 +:setvar server "BIO-V7V30JTZLZS\BIOREPL" +:setvar user "BIO-V7V30JTZLZS\SujoyPaul" +:setvar pwd "sujoy" +:connect $(server) -l $(logintimeout) -U $(user) -P $(pwd) + +--Add the transactional subscription in mysales and mysales2 + +USE $(db) ----mysales and mysales2 +GO + +DECLARE @publication AS sysname; +DECLARE @subscriber AS sysname; +DECLARE @subscription_db AS sysname; + +SET @publication = '$(pubname)'; +SET @subscriber = @@SERVERNAME; + +/* for mysales the subdbname should be mysales2 and vice versa */ +SET @subscription_db = '$(subdbname)'; + +EXEC sp_addsubscription @publication = @publication, +@article = 'all', +@subscriber = @subscriber, +@destination_db = @subscription_db, +@sync_type = 'none', +@status = 'active', +@update_mode = '$(value)', --set to read-only by default +@loopback_detection = '$(boolean)'; --- must be true for bidirectional + +EXEC sp_addpushsubscription_agent +@publication = @publication, +@subscriber = @subscriber, +@subscriber_db = @subscription_db, +/* the login name should be valid Windows Login in the form : 'MACHINE\Login' or 'DOMAIN\Login'. It is also not necessary to specify the login and the password*/ +@job_login = $(user), +@job_password = $(pwd); +GO +Listing 9-34. Creating insert stored procedures on both publication databases, mysales and mysales2 +--- Insert procedure, [sp_MSins_myinventoryItem] +/* give different names for mysales and mysales2 database as specified in listings 9-31 and 9-32 */ +create procedure [dbo]. [sp_MSins_myinventoryItem] +@c1 int,@c2 varchar(30),@c3 int,@c4 varchar(20),@c5 varchar(10),@c6 char(4) +as + +insert into "myinventory"."Item"( + "ItemID" +,"Description" +,"Vendor" +,"Category" +,"Color" +,"Unit" + ) +values ( + @c1 +,@c2 +,@c3 +,@c4 +,@c5 +,@c6 + ) +Listing 9-35. Creating delete stored procedures on both publication databases, mysales and mysales2 +---Delete stored procedure +/* give different names for mysales and mysales2 database as specified in listings 9-31 and 9-32 */ +create procedure [dbo].[sp_MSdel_myinventoryItem] +@pkc1 int +as +delete "myinventory"."Item" +where "ItemID" = @pkc1 +go +Listing 9-36. Creating update stored procedures on both publication databases, mysales and mysales2 +-- Update procedure +/* give different names for mysales and mysales2 database as specified in listings 9-31 and 9-32 */ +create procedure [dbo].[sp_MSupd_myinventoryItem] + --Primary key is @c1 +@old_c1 int, +@old_c2 varchar(30), +@old_c3 int, +@old_c4 varchar(20), +@old_c5 varchar(10), +@old_c6 char(4), +@c1 int, +@c2 varchar(30), +@c3 int, +@c4 varchar(20), +@c5 varchar(10), +@c6 char(4) +as +DECLARE @curr_c1 int, @curr_c3 int,@curr_c2 varchar(30), +@curr_c4 varchar(20),@curr_c5 varchar(10),@curr_c6 char(4); + +select @curr_c3=Vendor,@curr_c2=Description, + @curr_c4=Category,@curr_c5=Color,@curr_c6=Unit +from myinventory.Item where ItemID=@c1; + +--Add values for conflicts on int columns; don't add for primary key columns + +IF @curr_c3 != @old_c3 +SELECT @c3 = @curr_c3 + +(@c3 - @old_c3); + +-- Concatenate values for conflicts on varchar columns + +IF @curr_c2 != @old_c2 +SELECT @c2 = rtrim(@curr_c2) + +'_' + rtrim(@c2); +IF @curr_c4 != @old_c4 +SELECT @c4 = rtrim(@curr_c4) + +'_' + rtrim(@c4); +IF @curr_c5 != @old_c5 +SELECT @c5 = rtrim(@curr_c5) + +'_' + rtrim(@c5); +IF @curr_c6 != @old_c6 +SELECT @c6 = rtrim(@curr_c6) + +'_' + rtrim(@c6); +--Update item table + +UPDATE myinventory.Item SET Vendor = @c3, +Description = @c2, +Category =@c4, +Color =@c5, +Unit =@c6 +WHERE ItemId = @old_c1; + diff --git a/Codes/Chapter10/Chapter10codes.txt b/Codes/Chapter10/Chapter10codes.txt new file mode 100644 index 0000000..b0cc5a2 --- /dev/null +++ b/Codes/Chapter10/Chapter10codes.txt @@ -0,0 +1,424 @@ +Listing 10-1. Executing the DBCC command +/* Execute this on the database whose information you want. */ + +/* First turn the trace on using dbcc traceon.*/ + +DBCC traceon(3604) + +/* Now declare the variable. */ +declare @dbid int; + +/* Select the db id and place the value in the variable. */ +set @dbid=(select db_id('purchaseorder_repl')); + +/* Then call the dbcc log command. */ + +dbcc log(@dbid,2) +/* Now turn the traceoff using dbcc traceoff.*/ + +DBCC traceoff(3604) + +Listing 10-2. Returning all information using the fn_dblog command +/* Execute this on the publication database, purchaseorder_repl, +on the Publisher server, BIOREPL_PEER. */ +/* You can use other database as well, here I am using the purchaseorder_repl database */ + +Use purchaseorder_repl +Go + +select * from fn_dblog(null,null) + +Listing 10-3. Retrieving all the inserted rows in the publication database, purchaseorder_repl +/*Execute this on the publication database, purchaseorder_repl, +on the Publisher server, BIOREPL_PEER. */ + +select [AllocUnitId], +[AllocUnitName], +count([Current LSN])as TotalLSN, +command,description +from fn_dblog(null, null) +where Operation ='LOP_INSERT_ROWS' +group by [AllocUnitId],[AllocUnitName],[command],[description] +go + +Listing 10-4. Updating a row of the table vendor in the purchaseorder_repl database +/* Update a row in the publication database, purchaseorder_repl, +in the Publisher server, BIOREPL_PEER.*/ + +update vendor +set whse_postal_code='30033' +where vendorid=105 + +Listing 10-5. Retrieving transactions held in the MSrepl_commands table +/* Execute this on the distribution database. */ +use distribution +go + +select * from msrepl_commands where +publisher_database_id= +(select database_id from sys.databases where name +like 'mysales') +go + +Listing 10-6. Inserting data in the subscription database +/* Insert the records in the queued updating subscription database. */ +Use mysales_remote_queueupd +go + +Insert into myorder.Customer(CustID, BillTo, Name, WhseAddress1, +Whse_City, Whse_postal_code, Phone, Country,msrepl_tran_version) + values(8,160,'GauriMitra', '21 Laketown Ave.','Oakville', +'L6H 4A5','1-800-123-4567','Canada',newid()) +Go +Insert into myorder.Customer(CustID, BillTo, Name, WhseAddress1, + Whse_City, Whse_postal_code, Phone, Country,msrepl_tran_version) + values(8,160,'GauriMitra', '21 Laketown Ave.','Oakville', +'L6H 4A5','1-800-123-4567','Canada',newid()) +go + +Listing 10-7. Retrieving the number of commands for a transaction waiting to be picked up by the Queue Reader Agent +/* Execute this on the subscription database.*/ +Use mysales_remote_queueupd +Go + +select a.commandcount, +b.publication +from MSrepl_queuedtraninfo a, +Msreplication_queue b +where a.tranid=b.tranid +go +Listing 10-8. Updating the phone number in both the Subscribing database and the publication database +/* Execute the update on the queued updating subscription database. */ + +Use mysales_remote_queueupd +go +update myorder.Customer +set Phone='1-866-234-5432' +where country='Nepal' +go + +/* Now execute the update on the publication database for the + queued updating subscription. */ + +use mysales +go +update myorder.Customer +set Phone='1-866-234-6789' +where country='Nepal' +go + +Listing 10-9. Viewing the marker for peer-to-peer replication +/* Execute this on the distribution database. */ +use distribution +go +set nocount on +go + +/* Find the not null values for the originator_lsn, + the publication_id, and the dbversion. */ + +select b.id, +a.publisher_database_id, +a.originator_lsn, + +a.xact_seqno,b.publication_id, +b.srvname, + +b.dbname, +b.dbversion +from MSrepl_commands a,MSrepl_originators b +where a.publisher_database_id = b.publisher_database_id and +a.originator_lsn is not null and +b.dbversion is not null and +b.publication_id is not null +order by a.publisher_database_id +go +Listing 10-10. Viewing the marker stored in the MScached_peer_lsns table +/* Execute on the distribution database. */ +Use distribution +go + +select agent_id,originator,originator_db, +originator_lsn, originator_db_version +from MScached_peer_lsns +go + +Listing 10-11. Finding the last transaction sequence number +/* Execute this on the distribution database. */ +use distribution +go + +/* Declare a variable to store the Publisher database id */ + +declare @publisherdbid int + +/* Get the Publisher database id from the MSdistribution_agents +table. */ + +set @publisherdbid= +(select publisher_database_id +from msdistribution_agents + +/* The name of the Publisher and the Subscriber database is +the same. */ + +where publisher_db=subscriber_db) + +/* The maximum transaction sequence number is the +last sequence number. */ + +select max(xact_seqno) as lastseqno +from msrepl_commands +where publisher_database_id=@publisherdbid and command_id=1 +go + +Listing 10-12. Tracking the status of the transactions for the peer node, BIOREPL_PEER +/*Execute this on purchaseorder_repl on the BIOREPL_PEER node. */ +use purchaseorder_repl +go + +/* First check whether the stored procedure exists. */ + +IF OBJECT_ID ( 'usp_GetPeertoPeerList', 'P' ) IS NOT NULL + DROP PROCEDURE usp_GetPeertoPeerList; +go +set nocount on +go + +/*Create the stored procedure */ + +create procedure usp_GetPeertoPeerResponseList +as +select a.originator, +a.originator_db, +a.originator_db_version, +a.originator_lsn, +b.publication, +c.publisher, +c.publisher_db, +c.subscription_type, +c.update_mode, +c.failover_mode +from MSpeer_lsns as a, +MSpeer_request as b, +MSsubscription_agents as c +where a.id=b.id and a.id=c.id +order by originator_lsn +go + +Listing 10-13. Getting the names of subscribing databases for the standard publication +/*Execute this on the mysales_copy publication database on the BIOREPL_PEER node*/ +use mysales_copy +go + +/* First check whether the stored procedure exists. */ + +IF OBJECT_ID ( 'usp_GetSubForStdPublication', 'P' ) IS NOT NULL + DROP PROCEDURE usp_GetSubForStdPublication; +go +set nocount on +go + +/*Create the stored procedure. */ + +create procedure usp_GetSubForStdPublication +as +select a.artid,b.dest_db, +b.subscription_type,b.timestamp, +b.srvname,c.pubid, +c.name,c.replicate_ddl +from syspublications c, +syssubscriptions b, +sysarticles a +where b.dest_db<>'virtual'and b.subscription_type=0 +and a.artid=b.artid +and a.del_cmd <>'vcall%'and a.upd_cmd<>'vcall%' and +a.ins_cmd <>'vcall%' +and c.name='pub_mysales_copy_myinventory' +go + + + + +Listing 10-14. Articles in horizontal partitioning +/* Execute this on the publication database. */ +use mysales_copy +go + +/* First check whether the stored procedure exists. */ + +IF OBJECT_ID ( 'usp_GetArticleUsedHorizontalPartition', 'P' ) IS NOT NULL + DROP PROCEDURE usp_GetArticleUsedHorizontalPartition; +go +set nocount on +go + +/*Create the stored procedure. */ + +create procedure usp_GetArticleUsedHorizontalPartition +as + +select a.artid, +b.dest_db, +b.subscription_type, + +b.timestamp, +b.srvname,c.pubid, +c.name,c.replicate_ddl + +into dbo.syspubsubart +from syspublications c, +syssubscriptions b, sysarticles a +where b.dest_db<>'virtual'and b.subscription_type=0 +and a.artid=b.artid +and a.del_cmd<>'vcall%'and a.upd_cmd<>'vcall%' +and a.ins_cmd<>'vcall%' +and c.name='pub_mysales_copy_myinventory' +go + +/*Now select from the syspubsubart table */ + +select * from dbo.syspubsubart +go +/* Find the articles involved in horizontal partitioning */ +select a.artid, +a.del_cmd, +a.ins_cmd, +a.upd_cmd, +a.dest_table, +a.filter_clause, +a.dest_owner,a.type, +b.dest_db,b.name +from sysarticles a, dbo.syspubsubart b +where a.artid=b.artid and +a.pubid=b.pubid and +a.filter<>0 +go +Listing 10-15. Inserting data into the myorder.Stock table in the publication database +/* Execute this on the mysales_copy publication database + on the BIOREPL_PEER instance. */ + +Use mysales_copy +Go + +/* Insert the values. */ + +insert into +myorder.Stock(StockId,Whse,QtyOnHand,QtyOnOrd,QtyAvail,ItemNum) +values(1026,31,25,5000,25,1026) +insert into + myorder.Stock(StockId,Whse,QtyOnHand,QtyOnOrd,QtyAvail,ItemNum) +values(1027,31,1000,1700,100,1030) +insert into + myorder.Stock(StockId,Whse,QtyOnHand,QtyOnOrd,QtyAvail,ItemNum) +values(1028,31,400,6000,150,1031) +insert into +myorder.Stock(StockId,Whse,QtyOnHand,QtyOnOrd,QtyAvail,ItemNum) +values(1029,21,1000,4000,3000,1032) + +go + +/*Now check to see that the data has been replicated +in the mysalescopy_std_remotepush subscription database */ + +use mysalescopy_std_remotepush +go + +select stockid, Whse,QtyOnHand,QtyOnOrd,QtyAvail,ItemNum +from myorder.Stock +go +Listing 10-16. Replicating rows from the publication database +/* Execute this on the distribution database. */ + +Use distribution +Go + +/* Select the id of the row, the push subscription values. */ +/* Ensure that the sync_method is used for transactional replication */ + +select a.id, +b.allow_push, +b.publisher_db, + +b.sync_method, +b.description +from MSpublications b,MSpublisher_databases a + +where a.publisher_id=b.publisher_id +and b.publication_type=0 +and b.publication ='pub_mysales_copy_myinventory' +order by a.id +go + +Listing 10-17. Retrieving the transaction sequence number and the date of entry in the distribution database +/*Execute this on the distribution database. */ + +Use distribution +Go + +/* Create a table variable to hold the data. */ + +declare @transactionentry table +(xactseqno varbinary(16), +entrytime datetime, +command varbinary(1024) +) + +/* Insert the data into the table variable. */ + +insert into @transactionentry +/* Select transaction sequence numbers for the same publisher_database_id. For the MSrepl_commands and MSrepl_transactions system tables */ + +select b.xact_seqno, +b.entry_time, +a.command +from MSrepl_commands a, MSrepl_transactions b +where a.publisher_database_id=b.publisher_database_id + +/* Now check the data. */ +select * from @transactionentry + +/*Now check the last transaction number. */ + +select max(xactseqno) as lastseqno from @transactionentry +go + +Listing 10-18. Finding out the number of undelivered transactions +/*Execute this on the distribution database. */ + +Use distribution +Go + +/* Count the distinct number of transactions */ + +select count(distinct xact_seqno) as undeliveredtransactions +from MSrepl_commands a WITH (NOLOCK) +JOIN dbo.MSsubscriptions b +ON (a.article_id = b.article_id +AND a.publisher_database_id=b.publisher_database_id ) + +/* Want to know only for the 'mysalescopy_stpub_remotepush' subscribing database and for push subscription.*/ + +where b.subscriber_db like 'mysalescopy_stpub_remotepush' + +/* Now get the agent_id from the MSdistribution_agents table. */ + +and b.subscription_type=0 and b.agent_id=4 +go + +Listing 10-19. Retrieving a list of publications and their corresponding subscriptions in transactional replication +/* Execute this on the distribution database. */ + +Use distribution +Go + +Select * from MSsubscriptions a +Join MSpublications p +On ( a.publisher_id = p.publisher_id and + a.publisher_db = p.publisher_db and + a.publication_id = p.publication_id ) +where + (p.sync_method = 3 or p.sync_method = 4) + and subscriber_db<>'virtual' + go + diff --git a/Codes/Chapter13/Chapter13codes.txt b/Codes/Chapter13/Chapter13codes.txt new file mode 100644 index 0000000..26fc6dd --- /dev/null +++ b/Codes/Chapter13/Chapter13codes.txt @@ -0,0 +1,1811 @@ +Listing 13-1. Setting up the database for merge replication and creating a publication +/* Use the Publisher server to enable merge replication */ + +use master +go +sp_replicationdboption @dbname = 'mysales_merge1', +@optname = 'merge publish', +@value = 'true' +go + +/* Create the merge publication on the mysales_merge1 database */ + +use [mysales_merge1] +go + +/*Add the publication 'pub_download_mysalesmerge' */ + +sp_addmergepublication @publication = 'pub_downloadonly_mysalesmerge', +@sync_mode = 'native', +@retention = 14, +@allow_push = 'true', +@allow_pull = 'true', +@allow_anonymous = 'true', +@enabled_for_internet = 'false', +@snapshot_in_defaultfolder = 'true', +@allow_subscription_copy = 'false', +@dynamic_filters = 'false', +@conflict_retention = 14, +@keep_partition_changes = 'false', +@max_concurrent_merge = 0, +@max_concurrent_dynamic_snapshots = 0, +@use_partition_groups = 'false', +@publication_compatibility_level = '90RTM', +@replicate_ddl = 1, +@allow_subscriber_initiated_snapshot = 'false', +@allow_web_synchronization = 'false', +@allow_partition_realignment = 'true', +@retention_period_unit = 'days', +@conflict_logging = 'both', +@automatic_reinitialization_policy = 0 +go + +Listing 13-2. Creating the Snapshot Agent and access to the publication +/* Execute this on the publication database */ + +use [mysales_merge1] +go + +/* Create the Snapshot Agent */ + +sp_addpublication_snapshot @publication = 'pub_downloadonly_mysalesmerge', +@frequency_type = 4, +@frequency_interval = 14, +@frequency_relative_interval = 1, +@frequency_recurrence_factor = 0, +@frequency_subday = 1, +@frequency_subday_interval = 5, +@active_start_time_of_day = 500, +@active_end_time_of_day = 235959, +@active_start_date = 0, +@active_end_date = 0, +@job_login = 'BIO-V7V30JTZLZS\Sujoy Paul', +@job_password = null, +@publisher_security_mode = 0, +@publisher_login = 'sa', @publisher_password = '' + +/*Grant publication access */ + +exec sp_grant_publication_access @publication = 'pub_downloadonly_mysalesmerge', +@login = 'sa' +go + +Listing 13-3. Adding download-only articles for merge publication +/* Execute this on the publication database */ + +Use mysales_merge1 +Go + +/* Add the merge article, Item, to the publication */ + +sp_addmergearticle @publication = 'pub_downloadonly_mysalesmerge', +@article = 'Item', +@source_owner = 'myinventory', +@source_object = 'Item', +@type = 'table', +@pre_creation_cmd = 'drop', +@identityrangemanagementoption = 'none', +@destination_owner = 'myinventory', +@force_reinit_subscription = 1, +@column_tracking = 'false', +@subset_filterclause = '', +@vertical_partition = 'false', +@verify_resolver_signature = 0, +@allow_interactive_resolver = 'false', +@check_permissions = 0, +@subscriber_upload_options = 2, +@delete_tracking = 'true', +@compensate_for_errors = 'false', +@stream_blob_columns = 'false', +@partition_options = 0 +Go + +use [mysales_merge1] +go + +/* Add the merge article, SalesPerson, to the publication */ + +sp_addmergearticle @publication = 'pub_downloadonly_mysalesmerge', +@article = 'SalesPerson', +@source_owner = 'myorder', +@source_object = 'SalesPerson', +@type = 'table', +@pre_creation_cmd = 'drop', +@identityrangemanagementoption = 'none', +@destination_owner = 'myorder', +@force_reinit_subscription = 1, +@column_tracking = 'false', +@subset_filterclause = '', +@vertical_partition = 'false', +@verify_resolver_signature = 0, +@allow_interactive_resolver = 'false', +@check_permissions = 0, +@subscriber_upload_options = 2, +@delete_tracking = 'true', +@compensate_for_errors = 'false', +@stream_blob_columns = 'false', +@partition_options = 0 +Go + +use [mysales_merge1] +go + +/* Add the merge article, Warehouse, to the publication */ + +sp_addmergearticle @publication = 'pub_downloadonly_mysalesmerge', +@article = 'Warehouse', +@source_owner = 'myinventory', +@source_object = 'Warehouse', +@type = 'table', +@pre_creation_cmd = 'drop', +@identityrangemanagementoption = 'none', +@destination_owner = 'myinventory', +@force_reinit_subscription = 1, +@column_tracking = 'false', +@subset_filterclause = '', +@vertical_partition = 'false', +@verify_resolver_signature = 0, +@allow_interactive_resolver = 'false', +@check_permissions = 0, +@subscriber_upload_options = 2, +@delete_tracking = 'true', +@compensate_for_errors = 'false', +@stream_blob_columns = 'false', +@partition_options = 0 +Go + +use [mysales_merge1] +go + +/* Add the merge article, PriceList, to the publication */ + +sp_addmergearticle @publication = 'pub_downloadonly_mysalesmerge', +@article = 'PriceList', +@source_owner = 'myinventory', +@source_object = 'PriceList', +@type = 'table', +@pre_creation_cmd = 'drop', +@identityrangemanagementoption = 'none', +@destination_owner = 'myinventory', +@force_reinit_subscription = 1, +@column_tracking = 'false', +@subset_filterclause = '', +@vertical_partition = 'false', +@verify_resolver_signature = 0, +@allow_interactive_resolver = 'false', +@check_permissions = 0, +@subscriber_upload_options = 2, +@delete_tracking = 'true', +@compensate_for_errors = 'false', +@stream_blob_columns = 'false', +@partition_options = 0 +go + +Listing 13-4. Starting the Snapshot Agent job +/* Execute this stored procedure on the publication database */ + +Use [mysales_merge1] +Go + +/* Start the Snapshot Agent job to generate the initial +snapshot for the publication */ + +Exec sp_startpublication_snapshot 'pub_downloadonly_mysalesmerge' +Go +Listing 13-5. Setting up the publication for standard articles +/* Enable the database for replication by executing this on the +master database.*/ + +use master +exec sp_replicationdboption @dbname = 'mysales_merge2', +@optname = 'merge publish', +@value = 'true' +go + +/*Add the merge publication for standard articles using the default +agent schedule.*/ +/* Execute this on the publication database. */ + +use [mysales_merge2] +go + +sp_addmergepublication @publication = 'pub_stdpub_mysalesmerge2', + +/* Need to add @publication_compatibility_level='90RTM' +when @conflict_logging is set to 'both' */ + +@publication_compatibility_level='90RTM', +@sync_mode = 'native', +@retention = 14, +@allow_push = 'true', +@allow_pull = 'true', +@allow_anonymous = 'true', +@snapshot_in_defaultfolder = 'true', +@allow_subscription_copy = 'false', +@dynamic_filters = 'true', +@conflict_retention = 14, +@keep_partition_changes = 'false', +@allow_synctoalternate = 'false', +@validate_subscriber_info = 'SUSER_SNAME()', +@max_concurrent_merge = 0, +@max_concurrent_dynamic_snapshots = 0, +@use_partition_groups = 'true', +@replicate_ddl = 1, +@allow_subscriber_initiated_snapshot = 'true', +@allow_web_synchronization = 'false', +@allow_partition_realignment = 'true', +@retention_period_unit = 'days', +@conflict_logging = 'both', +@automatic_reinitialization_policy = 0 +GO + +/* Now add the publication snapshot */ + +exec sp_addpublication_snapshot @publication + = 'pub_stdpub_mysalesmerge2', @frequency_type = 4, +@frequency_interval = 14, +@frequency_relative_interval = 1, +@frequency_recurrence_factor = 0, +@frequency_subday = 1, +@frequency_subday_interval = 5, +@active_start_time_of_day = 500, +@active_end_time_of_day = 235959, +@active_start_date = 0, +@active_end_date = 0, +@job_login = null, +@job_password = null, +@publisher_security_mode = 0, +@publisher_login = 'sa', +@publisher_password = '' + +/* Grant access to the publication. */ + +exec sp_grant_publication_access +@publication = 'pub_stdpub_mysalesmerge2', +@login = 'sa' +GO +exec sp_grant_publication_access + @publication = 'pub_stdpub_mysalesmerge2', +@login = 'NT AUTHORITY\SYSTEM' +GO +exec sp_grant_publication_access + @publication = 'pub_stdpub_mysalesmerge2', +@login = 'BUILTIN\Administrators' +GO +exec sp_grant_publication_access +@publication = 'pub_stdpub_mysalesmerge2', +@login = 'BIO-V7V30JTZLZS\SQLServer2005SQLAgentUser$BIO-V7V30JTZLZS$BIOREPL' +GO +exec sp_grant_publication_access +@publication = 'pub_stdpub_mysalesmerge2', +@login = 'BIO-V7V30JTZLZS\SQLServer2005MSSQLUser$BIO-V7V30JTZLZS$BIOREPL' +GO +exec sp_grant_publication_access +@publication = 'pub_stdpub_mysalesmerge2', +@login = 'BIO-V7V30JTZLZS\Sujoy Paul' +GO +exec sp_grant_publication_access +@publication = 'pub_stdpub_mysalesmerge2', +@login = 'distributor_admin' +GO +exec sp_grant_publication_access +@publication = 'pub_stdpub_mysalesmerge2', +@login = 'LexasSmith' +GO +exec sp_grant_publication_access +@publication = 'pub_stdpub_mysalesmerge2', +@login = 'BensMarcedez' +GO +Listing 13-6. Adding standard articles to the publication +/* Execute this on the publication database. */ +use [mysales_merge2] +go + +/* Add the merge article, Customer, to the publication */ + +exec sp_addmergearticle @publication = 'pub_stdpub_mysalesmerge2', +@article = 'Customer', +@source_owner = 'myorder', +@source_object = 'Customer', +@type = 'table', +@creation_script = '', +@pre_creation_cmd = 'drop', +@identityrangemanagementoption = 'none', +@destination_owner = 'myorder', +@force_reinit_subscription = 1, +@column_tracking = 'false', +@subset_filterclause = '', +@vertical_partition ='false', +@verify_resolver_signature = 1, +@allow_interactive_resolver = 'true', +@check_permissions = 0, +@subscriber_upload_options = 0, +@delete_tracking = 'true', +@compensate_for_errors = 'false', +@stream_blob_columns = 'false', +@partition_options = 0 +Go + +use [mysales_merge2] +go + +/* Add the merge article, Stock, to the publication */ + +exec sp_addmergearticle +@publication = 'pub_stdpub_mysalesmerge2', +@article = 'Stock', +@source_owner ='myorder', +@source_object = 'Stock', +@type = 'table', +@creation_script = '', +@pre_creation_cmd = 'drop', +@identityrangemanagementoption = 'none', +@destination_owner = 'myorder', +@force_reinit_subscription = 1, +@column_tracking = 'false', +@subset_filterclause = '', +@vertical_partition = 'false', +@verify_resolver_signature = 1, +@allow_interactive_resolver = 'true', +@check_permissions = 0, +@subscriber_upload_options = 0, +@delete_tracking = 'true', +@compensate_for_errors = 'false', +@stream_blob_columns = 'false', +@partition_options = 0 +go + +use [mysales_merge2] +go + +/* Add the merge article, Item, to the publication */ + +exec sp_addmergearticle +@publication = 'pub_stdpub_mysalesmerge2', +@article = 'Item', +@source_owner = 'myinventory', +@source_object = 'Item', +@type = 'table', +@creation_script = '', +@pre_creation_cmd = 'drop', +@identityrangemanagementoption = 'none', +@destination_owner = 'myinventory', +@force_reinit_subscription = 1, +@column_tracking = 'false', +@subset_filterclause = '', +@vertical_partition ='false', +@verify_resolver_signature = 1, +@allow_interactive_resolver = 'true', +@check_permissions = 0, +@subscriber_upload_options = 0, +@delete_tracking = 'true', +@compensate_for_errors = 'false', +@stream_blob_columns = 'false', +@partition_options = 0 +go + +use [mysales_merge2] +go + +/* Add the merge article, SalesPerson, to the publication */ +/* Add the merge article, SalesPerson, to the publication */ + +exec sp_addmergearticle +@publication = 'pub_stdpub_mysalesmerge2', +@article = 'SalesPerson', +@source_owner = 'myorder', +@source_object = 'SalesPerson', +@type = 'table', +@creation_script = '', +@pre_creation_cmd = 'drop', +@identityrangemanagementoption = 'none', +@destination_owner = 'myorder', +@force_reinit_subscription = 1, +@column_tracking = 'false', +@subset_filterclause = 'cast([SalesID] as char(10))= SUSER_SNAME()', +@vertical_partition = 'false', +@verify_resolver_signature = 1, +@allow_interactive_resolver = 'true', +@check_permissions = 0, +@subscriber_upload_options = 0, +@delete_tracking = 'true', +@compensate_for_errors = 'false', +@stream_blob_columns = 'false', +@partition_options = 0 +go + +use [mysales_merge2] +go + +/* Add the merge article, AccountsReceivable, to the publication */ + +exec sp_addmergearticle +@publication = 'pub_stdpub_mysalesmerge2', +@article = 'AccountsReceivable', +@source_owner = 'myfinance', +@source_object = 'AccountsReceivable', +@type = 'table', +@creation_script = '', +@pre_creation_cmd = 'drop', +@identityrangemanagementoption = 'none', +@destination_owner = 'myfinance', +@force_reinit_subscription = 1, +@column_tracking = 'false', +@subset_filterclause = '', +@vertical_partition = 'false', +@verify_resolver_signature = 1, +@allow_interactive_resolver = 'true', +@check_permissions = 0, +@subscriber_upload_options = 0, +@delete_tracking = 'true', +@compensate_for_errors = 'false', +@stream_blob_columns = 'false', +@partition_options = 0 +Go +use [mysales_merge2] +go + +/* Add the merge article, OrderHeader, to the publication */ + +exec sp_addmergearticle +@publication = 'pub_stdpub_mysalesmerge2', +@article = 'OrderHeader', +@source_owner ='myorder', +@source_object = 'OrderHeader', +@type = 'table', +@creation_script = '', +@pre_creation_cmd = 'drop', +@identityrangemanagementoption = 'none', +@destination_owner = 'myorder', +@force_reinit_subscription = 1, +@column_tracking = 'false', + +/*@article_resolver = 'Microsoft SQL Server DATETIME (Earlier Wins) +Conflict Resolver',*/ + +@subset_filterclause = '', +/*@resolver_info = 'Ship_date',*/ +@vertical_partition = 'false', +@verify_resolver_signature = 0, +@allow_interactive_resolver = 'true', +@check_permissions = 0, +@subscriber_upload_options = 0, +@delete_tracking = 'true', +@compensate_for_errors = 'false', +@stream_blob_columns = 'false', +@partition_options = 0 +Go + +use [mysales_merge2] +go + +/* Add the merge article, PriceList, to the publication */ + +exec sp_addmergearticle +@publication = 'pub_stdpub_mysalesmerge2', +@article = 'PriceList', +@source_owner = 'myinventory', +@source_object = 'PriceList', +@type = 'table', +@creation_script = '', +@pre_creation_cmd = 'drop', +@identityrangemanagementoption = 'none', +@destination_owner = 'myinventory', +@force_reinit_subscription = 1, +@column_tracking = 'false', +@article_resolver = 'Microsoft SQL Server Maximum Conflict Resolver', +@subset_filterclause = '', +@resolver_info = 'Price', +@vertical_partition ='false', +@verify_resolver_signature = 1, +@allow_interactive_resolver = 'true', +@check_permissions = 0, +@subscriber_upload_options = 0, +@delete_tracking = 'true', +@compensate_for_errors = 'false', +@stream_blob_columns = 'false', +@partition_options = 0 +Go +use [mysales_merge2] +go + +/* Add the merge article, StockItem, to the publication */ + +exec sp_addmergearticle +@publication = 'pub_stdpub_mysalesmerge2', +@article = 'StockItem', +@source_owner = 'myinventory', +@source_object = 'StockItem', +@type = 'table', +@creation_script = '', +@pre_creation_cmd = 'drop', +@identityrangemanagementoption = 'none', + +@destination_owner = 'myinventory', +@force_reinit_subscription = 1, +@column_tracking = 'false', +@subset_filterclause = '', +@vertical_partition ='false', +@verify_resolver_signature = 1, +@allow_interactive_resolver = 'true', +@check_permissions = 0, +@subscriber_upload_options = 0, +@delete_tracking = 'true', +@compensate_for_errors = 'false', +@stream_blob_columns = 'false', +@partition_options = 0 +Go + +use [mysales_merge2] +go + +/* Add the merge article, CustSales, to the publication */ + +exec sp_addmergearticle +@publication = 'pub_stdpub_mysalesmerge2', +@article = 'CustSales', +@source_owner ='myorder', +@source_object = 'CustSales', +@type = 'table', +@creation_script = '', +@pre_creation_cmd = 'drop', +@identityrangemanagementoption = 'none', +@destination_owner = 'myorder', +@force_reinit_subscription = 1, +@column_tracking = 'false', +@subset_filterclause = '', +@vertical_partition ='false', +@verify_resolver_signature = 1, +@allow_interactive_resolver = 'true', +@check_permissions = 0, +@subscriber_upload_options = 0, +@delete_tracking = 'true', +@compensate_for_errors = 'false', +@stream_blob_columns = 'false', +@partition_options = 0 +Go + +use [mysales_merge2] +go + +/* Add the merge article, OrderDetail, to the publication */ + +exec sp_addmergearticle +@publication = 'pub_stdpub_mysalesmerge2', +@article = 'OrderDetail', +@source_owner = 'myorder', +@source_object = 'OrderDetail', +@type = 'table', +@creation_script = '', +@pre_creation_cmd = 'drop', +@identityrangemanagementoption = 'none', +@destination_owner = 'myorder', +@force_reinit_subscription = 1, +@column_tracking = 'false', +@subset_filterclause = '', +@vertical_partition ='false', +@verify_resolver_signature = 1, +@allow_interactive_resolver = 'true', +@check_permissions = 0, +@subscriber_upload_options = 0, +@delete_tracking = 'true', +@compensate_for_errors = 'false', +@stream_blob_columns = 'false', +@partition_options = 0 +Go + +use [mysales_merge2] +go + +/* Add the merge article, usp_GetCustomerInvoicePaymentDue, to the publication */ + +exec sp_addmergearticle +@publication = 'pub_stdpub_mysalesmerge2', +@article ='usp_GetCustomerInvoicePaymentDue', +@source_owner = 'myorder', +@source_object = 'usp_GetCustomerInvoicePaymentDue', +@type = 'proc schema only', +@pre_creation_cmd = 'drop', +@destination_owner = 'myorder', +@destination_object = 'usp_GetCustomerInvoicePaymentDue', +@force_reinit_subscription = 1 +Go + +use [mysales_merge2] +go + +/* Add the merge article, vw_CustomerInvoiceStatus, to +the publication */ + +exec sp_addmergearticle +@publication = 'pub_stdpub_mysalesmerge2', +@article = 'vw_CustomerInvoiceStatus', +@source_owner = 'myorder', +@source_object = 'vw_CustomerInvoiceStatus', +@type = 'view schema only', +@pre_creation_cmd = 'drop', +@destination_owner = 'myorder', +@destination_object = 'vw_CustomerInvoiceStatus', +@force_reinit_subscription = 1 +Go + +use [mysales_merge2] +go + +/* Add the merge article, vw_ItemEnquiry, to the publication */ + +exec sp_addmergearticle +@publication = 'pub_stdpub_mysalesmerge2', +@article = 'vw_ItemEnquiry', +@source_owner= 'myorder', +@source_object = 'vw_ItemEnquiry', +@type = 'view schema only', +@pre_creation_cmd = 'drop', +@destination_owner = 'myorder', +@destination_object = 'vw_ItemEnquiry', +@force_reinit_subscription = 1 +Go +use [mysales_merge2] +go + +/* Add the merge article, vw_OrderStatus, to the publication */ + +exec sp_addmergearticle +@publication = 'pub_stdpub_mysalesmerge2', +@article = 'vw_OrderStatus', +@source_owner = 'myorder', +@source_object = 'vw_OrderStatus', +@type = 'view schema only', +@pre_creation_cmd = 'drop', +@destination_owner = 'myorder', +@destination_object ='vw_OrderStatus', +@force_reinit_subscription = 1 +go + +Listing 13-7. Adding the parameterized and join filters and starting the Snapshot Agent +/*Add the merge article join filters on the publication database*/ + +use [mysales_merge2] +go + +/*Add the join filter to the article AccountsReceivable */ + +exec sp_addmergefilter +@publication = 'pub_stdpub_mysalesmerge2', +@article = 'AccountsReceivable', +@filtername= 'AccountsReceivable_Customer', +@join_articlename = 'Customer', +@join_filterclause = '[Customer].[CustID] = [AccountsReceivable].[CustID]', +@join_unique_key = 1, +@filter_type = 1, +@force_invalidate_snapshot = 1, +@force_reinit_subscription = 1 +Go + +use [mysales_merge2] +go + +/*Add the join filter to the article OrderHeader */ + +exec sp_addmergefilter +@publication = 'pub_stdpub_mysalesmerge2', +@article = 'OrderHeader', +@filtername ='OrderHeader_Customer', +@join_articlename = 'Customer', +@join_filterclause = '[Customer].[CustID] =[OrderHeader].[CustID]', +@join_unique_key = 1, +@filter_type = 1, +@force_invalidate_snapshot = 1, +@force_reinit_subscription = 1 +Go + +use [mysales_merge2] +go + +/*Add the join filter to the article Customer */ + +exec sp_addmergefilter +@publication = 'pub_stdpub_mysalesmerge2', +@article = 'Customer', +@filtername ='Customer_CustSales', +@join_articlename = 'CustSales', +@join_filterclause = '[CustSales].[CustID] =[Customer].[CustID]', +@join_unique_key = 1, +@filter_type = 1, +@force_invalidate_snapshot = 1, +@force_reinit_subscription = 1 +Go + +use [mysales_merge2] +go + +/*Add the join filter to the article OrderDetail */ + +exec sp_addmergefilter +@publication = 'pub_stdpub_mysalesmerge2', +@article = 'OrderDetail', +@filtername = 'OrderDetail_OrderHeader', +@join_articlename = 'OrderHeader', +@join_filterclause = '[OrderHeader].[OrderID] =[OrderDetail].[OrderID]', +@join_unique_key = 1, +@filter_type = 3, +@force_invalidate_snapshot = 1, +@force_reinit_subscription = 1 +Go +use [mysales_merge2] +go + +/*Add the join filter to the article CustSales */ + +exec sp_addmergefilter +@publication = 'pub_stdpub_mysalesmerge2', +@article = 'CustSales', +@filtername ='CustSales_SalesPerson', +@join_articlename = 'SalesPerson', +@join_filterclause = '[SalesPerson].[SalesID] =[CustSales].[SalesID]', +@join_unique_key = 1, +@filter_type = 1, +@force_invalidate_snapshot = 1, +@force_reinit_subscription = 1 +Go + +/* Start the Snapshot Agent on the Publisher server .*/ + +exec sp_startpublication_snapshot +@publication = 'pub_stdpub_mysalesmerge2' +go +Listing 13-8. Using the HOST_NAME() dynamic function to set up the publication for standard articles +/* Enable the database for replication on the master database */ + +use master +go +exec sp_replicationdboption @dbname = 'mysales_merge_replpeer', +@optname = 'merge publish', +@value = 'true' +go + +/* Now add the merge publication on the mysales_merge_replpeer + database on the BIOREPL_PEER instance */ + +use [mysales_merge_replpeer] +go + +exec sp_addmergepublication +@publication = 'pub_mysales_mergereplpeer_hostname', +@sync_mode = 'native', +@retention = 14, +@allow_push = 'true', +@allow_pull = 'true', +@allow_anonymous = 'true', +@enabled_for_internet = 'false', +@snapshot_in_defaultfolder = 'true', +@dynamic_filters = 'true', +@conflict_retention = 14, +@keep_partition_changes = 'false', +@allow_synctoalternate = 'false', +@validate_subscriber_info = 'HOST_NAME()', +@max_concurrent_merge = 1, +@max_concurrent_dynamic_snapshots = 0, +@use_partition_groups = 'true', +@publication_compatibility_level = '90RTM', +@replicate_ddl = 1, +@allow_subscriber_initiated_snapshot = 'false', +@allow_web_synchronization = 'false', +@allow_partition_realignment = 'true', +@retention_period_unit = 'days', +@conflict_logging = 'both', +@automatic_reinitialization_policy = 0 +go + +/* Create the Snapshot Agent */ + +exec sp_addpublication_snapshot +@publication = 'pub_mysales_mergereplpeer_hostname', +@frequency_type = 4, +@frequency_interval = 14, +@frequency_relative_interval = 1, +@frequency_recurrence_factor = 0, +@frequency_subday = 1, +@frequency_subday_interval = 5, +@active_start_time_of_day = 500, +@active_end_time_of_day = 235959, +@active_start_date = 0, +@active_end_date = 0, +@job_login = null, +@job_password = null, +@publisher_security_mode = 1 + +/*Grant access to the publication */ + +exec sp_grant_publication_access +@publication = 'pub_mysales_mergereplpeer_hostname', +@login = 'sa' +go +sp_grant_publication_access +@publication = 'pub_mysales_mergereplpeer_hostname', +@login = 'distributor_admin' +go + +/* Now add the merge articles */ + +use [mysales_merge_replpeer] +go +exec sp_addmergearticle +@publication = 'pub_mysales_mergereplpeer_hostname', +@article = 'Customer', +@source_owner = 'myorder', +@source_object = 'Customer', +@type = 'table', +@pre_creation_cmd = 'drop', +@identityrangemanagementoption = 'none', +@destination_owner = 'myorder', +@force_reinit_subscription = 1, +@column_tracking = 'false', +@subset_filterclause = '', +@vertical_partition = 'false', +@verify_resolver_signature = 1, +@allow_interactive_resolver = 'false', +@fast_multicol_updateproc = 'true', +@check_permissions = 0, +@subscriber_upload_options = 0, +@delete_tracking = 'true', +@compensate_for_errors = 'false', +@stream_blob_columns = 'false', +@partition_options = 0 +Go +use [mysales_merge_replpeer] +go + +/*Add the article, Item, to the publication */ + +exec sp_addmergearticle +@publication = 'pub_mysales_mergereplpeer_hostname', +@article = 'Item', +@source_owner = 'myinventory', +@source_object = 'Item', +@type = 'table', +@pre_creation_cmd = 'drop', +@identityrangemanagementoption = 'none', +@destination_owner = 'myinventory', +@force_reinit_subscription = 1, +@column_tracking = 'false', +@subset_filterclause = '', +@vertical_partition = 'false', +@verify_resolver_signature = 1, +@allow_interactive_resolver = 'false', +@fast_multicol_updateproc = 'true', +@check_permissions = 0, +@subscriber_upload_options = 0, +@delete_tracking = 'true', +@compensate_for_errors = 'false', +@stream_blob_columns = 'false', +@partition_options = 0 +Go + +use [mysales_merge_replpeer] +go + +/*Add the article, OrderHeader, to the publication */ + +exec sp_addmergearticle +@publication = 'pub_mysales_mergereplpeer_hostname', +@article = 'OrderHeader', +@source_owner = 'myorder', +@source_object = 'OrderHeader', +@type = 'table', +@pre_creation_cmd = 'drop', +@identityrangemanagementoption = 'none', +@destination_owner = 'myorder', +@force_reinit_subscription = 1, +@column_tracking = 'false', +@subset_filterclause = '', +@vertical_partition = 'false', +@verify_resolver_signature = 1, +@allow_interactive_resolver = 'false', +@fast_multicol_updateproc = 'true', +@check_permissions = 0, +@subscriber_upload_options = 0, +@delete_tracking = 'true', +@compensate_for_errors = 'false', +@stream_blob_columns = 'false', +@partition_options = 0 +Go +use [mysales_merge_replpeer] +go + +/*Add the article, SalesPerson, to the publication */ + +exec sp_addmergearticle +@publication = 'pub_mysales_mergereplpeer_hostname', +@article = 'SalesPerson', +@source_owner = 'myorder', +@source_object = 'SalesPerson', +@type = 'table', +@pre_creation_cmd = 'drop', +@identityrangemanagementoption = 'none', +@destination_owner = 'myorder', +@force_reinit_subscription = 1, +@column_tracking = 'false', +@subset_filterclause = 'convert(char,[SalesID])HOST_NAME()', +@vertical_partition = 'false', +@verify_resolver_signature = 1, +@allow_interactive_resolver = 'false', +@fast_multicol_updateproc = 'true', +@check_permissions = 0x10, +@subscriber_upload_options = 0, +@delete_tracking = 'true', +@compensate_for_errors = 'false', +@stream_blob_columns = 'false', +@partition_options = 0 +go + +use [mysales_merge_replpeer] +go + +/*Add the article, Stock, to the publication */ + +exec sp_addmergearticle +@publication = 'pub_mysales_mergereplpeer_hostname', +@article = 'Stock', +@source_owner = 'myorder', +@source_object = 'Stock', +@type = 'table', +@pre_creation_cmd = 'drop', +@identityrangemanagementoption = 'none', +@destination_owner = 'myorder', +@force_reinit_subscription = 1, +@column_tracking = 'false', +@subset_filterclause = '', +@vertical_partition = 'false', +@verify_resolver_signature = 1, +@allow_interactive_resolver = 'false', +@fast_multicol_updateproc = 'true', +@check_permissions = 0, +@subscriber_upload_options = 0, +@delete_tracking = 'true', +@compensate_for_errors = 'false', +@stream_blob_columns = 'false', +@partition_options = 0 +Go + +use [mysales_merge_replpeer] +go + +/*Add the article, AccountsReceivable, to the publication */ + +exec sp_addmergearticle +@publication = 'pub_mysales_mergereplpeer_hostname', +@article = 'AccountsReceivable', +@source_owner = 'myfinance', +@source_object = 'AccountsReceivable', +@type = 'table', +@pre_creation_cmd = 'drop', +@identityrangemanagementoption = 'none', +@destination_owner = 'myfinance', +@force_reinit_subscription = 1, +@column_tracking = 'false', +@subset_filterclause = '', +@vertical_partition = 'false', +@verify_resolver_signature = 1, +@allow_interactive_resolver = 'false', +@fast_multicol_updateproc = 'true', +@check_permissions = 0, +@subscriber_upload_options = 0, +@delete_tracking = 'true', +@compensate_for_errors = 'false', +@stream_blob_columns = 'false', +@partition_options = 0 +Go + +use [mysales_merge_replpeer] +go + +/*Add the article, OrderDetail, to the publication */ + +exec sp_addmergearticle +@publication = 'pub_mysales_mergereplpeer_hostname', +@article = 'OrderDetail', +@source_owner = 'myorder', +@source_object = 'OrderDetail', +@type = 'table', +@pre_creation_cmd = 'drop', +@identityrangemanagementoption = 'none', +@destination_owner = 'myorder', +@force_reinit_subscription = 1, +@column_tracking = 'false', +@subset_filterclause = '', +@vertical_partition = 'false', +@verify_resolver_signature = 1, +@allow_interactive_resolver = 'false', +@fast_multicol_updateproc = 'true', +@check_permissions = 0, +@subscriber_upload_options = 0, +@delete_tracking = 'true', +@compensate_for_errors = 'false', +@stream_blob_columns = 'false', +@partition_options = 0 +Go + +use [mysales_merge_replpeer] +go + +/*Add the article, PriceList, to the publication */ + +exec sp_addmergearticle +@publication = 'pub_mysales_mergereplpeer_hostname', +@article = 'PriceList', +@source_owner = 'myinventory', +@source_object = 'PriceList', +@type = 'table', +@pre_creation_cmd = 'drop', +@identityrangemanagementoption = 'none', +@destination_owner = 'myinventory', +@force_reinit_subscription = 1, +@column_tracking = 'false', +@article_resolver = 'Microsoft SQL Server Averaging +Conflict Resolver', @subset_filterclause = '', +@resolver_info = 'Price', +@vertical_partition = 'false', +@verify_resolver_signature = 0, +@allow_interactive_resolver = 'false', +@fast_multicol_updateproc = 'true', +@check_permissions = 0, +@subscriber_upload_options = 0, +@delete_tracking = 'true', +@compensate_for_errors = 'false', +@stream_blob_columns = 'false', +@partition_options = 0 +Go +use [mysales_merge_replpeer] +go + +/*Add the article, AccountInvoice, to the publication */ + +exec sp_addmergearticle +@publication = 'pub_mysales_mergereplpeer_hostname', +@article = 'AccountInvoice', +@source_owner = 'myfinance', +@source_object = 'AccountInvoice', +@type = 'table', +@pre_creation_cmd = 'drop', +@identityrangemanagementoption = 'none', +@destination_owner = 'myfinance', +@force_reinit_subscription = 1, +@column_tracking = 'false', +@subset_filterclause = '', +@vertical_partition = 'false', +@verify_resolver_signature = 1, +@allow_interactive_resolver = 'false', +@fast_multicol_updateproc = 'true', +@check_permissions = 0, +@subscriber_upload_options = 0, +@delete_tracking = 'true', +@compensate_for_errors = 'false', +@stream_blob_columns = 'false', +@partition_options = 0 +Go + +use [mysales_merge_replpeer] +go + +/*Add the article, CustSales, to the publication */ + +exec sp_addmergearticle +@publication = 'pub_mysales_mergereplpeer_hostname', +@article = 'CustSales', +@source_owner = 'myorder', +@source_object = 'CustSales', +@type = 'table', +@pre_creation_cmd = 'drop', +@identityrangemanagementoption = 'none', +@destination_owner = 'myorder', +@force_reinit_subscription = 1, +@column_tracking = 'false', +@subset_filterclause = '', +@vertical_partition = 'false', +@verify_resolver_signature = 1, +@allow_interactive_resolver = 'false', +@fast_multicol_updateproc = 'true', +@check_permissions = 0, +@subscriber_upload_options = 0, +@delete_tracking = 'true', +@compensate_for_errors = 'false', +@stream_blob_columns = 'false', +@partition_options = 0 +Go + +use [mysales_merge_replpeer] +go + +/*Add the article, StockItem, to the publication */ + +exec sp_addmergearticle +@publication = 'pub_mysales_mergereplpeer_hostname', +@article = 'StockItem', +@source_owner = 'myinventory', +@source_object = 'StockItem', +@type = 'table', +@pre_creation_cmd = 'drop', +@identityrangemanagementoption = 'none', +@destination_owner = 'myinventory', +@force_reinit_subscription = 1, +@column_tracking = 'false', +@subset_filterclause = '', +@vertical_partition = 'false', +@verify_resolver_signature = 1, +@allow_interactive_resolver = 'false', +@fast_multicol_updateproc = 'true', +@check_permissions = 0, +@subscriber_upload_options = 0, +@delete_tracking = 'true', +@compensate_for_errors = 'false', +@stream_blob_columns = 'false', +@partition_options = 0 +Go + +use [mysales_merge_replpeer] +go + +/*If the snapshot was already generated, use @force_invalidate_snapshot=1*/ + +/*Add the article, usp_GetCustomerInvoicePaymentDue, to +the publication */ + +exec sp_addmergearticle +@publication = 'pub_mysales_mergereplpeer_hostname', +@article = 'usp_GetCustomerInvoicePaymentDue', +@source_owner = 'myorder', +@source_object = 'usp_GetCustomerInvoicePaymentDue', +@type = 'proc schema only', +@pre_creation_cmd = 'drop', +@destination_owner = 'myorder', +@destination_object = 'usp_GetCustomerInvoicePaymentDue', +@force_reinit_subscription = 1 +Go + +use [mysales_merge_replpeer] +go + +/*Add the article, usp_GetItemAbovePremiumPrice, to the publication */ + +exec sp_addmergearticle +@publication = 'pub_mysales_mergereplpeer_hostname', +@article = 'usp_GetItemAbovePremiumPrice', +@source_owner = 'myinventory', +@source_object = 'usp_GetItemAbovePremiumPrice', +@type = 'proc schema only', +@pre_creation_cmd = 'drop', +@destination_owner = 'myinventory', +@destination_object = 'usp_GetItemAbovePremiumPrice', +@force_reinit_subscription = 1 +Go + +use [mysales_merge_replpeer] +go +exec sp_addmergearticle + +/*Add the article, usp_ InsertCustomerInvoice, to the publication */ + +@publication = 'pub_mysales_mergereplpeer_hostname', +@article = 'usp_InsertCustomerInvoice', +@source_owner = 'myorder', +@source_object = 'usp_InsertCustomerInvoice', +@type = 'proc schema only', +@pre_creation_cmd = 'drop', +@destination_owner = 'myorder', +@destination_object = 'usp_InsertCustomerInvoice', +@force_reinit_subscription = 1 +Go + +use [mysales_merge_replpeer] + +/*Add the article, vw_CustomerInvoiceStatus, to the publication */ + +sp_addmergearticle +@publication = 'pub_mysales_mergereplpeer_hostname', +@article = 'vw_CustomerInvoiceStatus', +@source_owner = 'myorder', +@source_object = 'vw_CustomerInvoiceStatus', +@type = 'view schema only', +@pre_creation_cmd = 'drop', +@destination_owner = 'myorder', +@destination_object = 'vw_CustomerInvoiceStatus', +@force_reinit_subscription = 1 +Go + +use [mysales_merge_replpeer] +go + +/*Add the article, vw_ItemEnquiry, to the publication */ + +exec sp_addmergearticle +@publication = 'pub_mysales_mergereplpeer_hostname', +@article = 'vw_ItemEnquiry', +@source_owner = 'myorder', +@source_object = 'vw_ItemEnquiry', +@type = 'view schema only', +@pre_creation_cmd = 'drop', +@destination_owner = 'myorder', +@destination_object = 'vw_ItemEnquiry', +@force_reinit_subscription = 1 +Go + +use [mysales_merge_replpeer] +go + +/*Add the article, vw_OrderStatus, to the publication */ + +exec sp_addmergearticle +@publication = 'pub_mysales_mergereplpeer_hostname', +@article = 'vw_OrderStatus', +@source_owner = 'myorder', +@source_object = 'vw_OrderStatus', +@type = 'view schema only', +@pre_creation_cmd = 'drop', +@destination_owner = 'myorder', +@destination_object = 'vw_OrderStatus', +@force_reinit_subscription = 1 +go + +/* Now add the merge article join filters. */ + +use [mysales_merge_replpeer] +go + +/* Add the join filter to AccountsReceivable */ + +exec sp_addmergefilter +@publication = 'pub_mysales_mergereplpeer_hostname', +@article = 'AccountsReceivable', +@filtername = 'AccountsReceivable_Customer', +@join_articlename = 'Customer', +@join_filterclause = '[Customer].[CustID] = [AccountsReceivable].[CustID]', +@join_unique_key = 1, +@filter_type = 1, +@force_invalidate_snapshot = 1, +@force_reinit_subscription = 1 +Go + +use [mysales_merge_replpeer] +go + +/* Add the join filter to OrderHeader */ + +exec sp_addmergefilter +@publication = 'pub_mysales_mergereplpeer_hostname', +@article = 'OrderHeader', + +@filtername = 'OrderHeader_Customer', +@join_articlename = 'Customer', +@join_filterclause = '[Customer].[CustID] = [OrderHeader].[CustID]', +@join_unique_key = 1, +@filter_type = 1, +@force_invalidate_snapshot = 1, +@force_reinit_subscription = 1 +Go + +use [mysales_merge_replpeer] +go + +/* Add the join filter to Customer */ + +exec sp_addmergefilter +@publication = 'pub_mysales_mergereplpeer_hostname', +@article = 'Customer', +@filtername = 'Customer_CustSales', +@join_articlename = 'CustSales', +@join_filterclause = '[CustSales].[CustID] = [Customer].[CustID]', +@join_unique_key = 1, +@filter_type = 1, +@force_invalidate_snapshot = 1, +@force_reinit_subscription = 1 +Go + +use [mysales_merge_replpeer] +go + +/* Add the join filter to OrderDetail */ + +exec sp_addmergefilter +@publication = 'pub_mysales_mergereplpeer_hostname', +@article = 'OrderDetail', +@filtername = 'OrderDetail_OrderHeader', +@join_articlename = 'OrderHeader', +@join_filterclause = '[OrderHeader].[OrderID] = [OrderDetail].[OrderID]', +@join_unique_key = 1, +@filter_type = 1, +@force_invalidate_snapshot = 1, +@force_reinit_subscription = 1 +Go + +use [mysales_merge_replpeer] +go + +/* Add the join filter to CustSales */ + +exec sp_addmergefilter +@publication = 'pub_mysales_mergereplpeer_hostname', +@article = 'CustSales', +@filtername = 'CustSales_SalesPerson', +@join_articlename = 'SalesPerson', +@join_filterclause = '[SalesPerson].[SalesID] = [CustSales].[SalesID]', +@join_unique_key = 1, +@filter_type = 1, +@force_invalidate_snapshot = 1, +@force_reinit_subscription = 1 +Go + +/*Generate the publication snapshot */ + +exec sp_startpublication_snapshot +@publication = 'pub_mysales_mergereplpeer_hostname' +go +Listing 13-9. Generating a dynamic snapshot for publications with parameterized row filters +/*Execute this on the publication database. */ + +use [mysales_merge_replpeer] +go + +/*Create a table variable. */ + +declare @dynamicsnapshot table +(id int, + job_name sysname, + job_id uniqueidentifier, + dynamic_filter_login sysname NULL, + dynamic_filter_hostname sysname NULL, + dynamic_snapshot_location nvarchar(255), + frequency_type int, + frequency_interval int, + frequency_subday_type int, + frequency_subday_interval int, + frequency_relative_interval int, + frequency_recurrence_factor int, + active_start_date int, + active_end_date int, + active_start_time int, + active_end_time int +) +/* Declare variables and assign values to publication and HOSTNAME. */ + +declare @publication AS sysname; +declare @jobname AS sysname +declare @hostname AS sysname +set @publication = 'pub_mysales_mergereplpeer_hostname'; +set @hostname = 'BIO-V7V30JTZLZS-SALES'; + +/* Add a data partition. */ + +sp_addmergepartition +@publication = @publication, +@host_name = @hostname; + +/* Add the filtered data snapshot job. */ + +sp_adddynamicsnapshot_job +@publication = @publication, +@host_name = @hostname; + +/* Insert into the table variable the data from the sp_helpdynamicsnapshot_job. */ + +insert into @dynamicsnapshot exec sp_helpdynamicsnapshot_job + +/*Test to see that the values are successfully inserted. */ + +select * from @dynamicsnapshot + +/* Find the name of the job for the dynamic snapshot, and then start the job. */ + +select @jobname = (select distinct job_name from +@dynamicsnapshot where dynamic_filter_hostname = @hostname); + +/* Start the job in the msdb database. */ + +exec msdb..sp_start_job @job_name = @jobname; +go +Listing 13-10. Setting up a push subscription for merge publication with download-only articles +/* Execute this on the publication database. */ + +Use mysales_merge1 +Go + +/* Create a temporary table to hold the values of merge +publication. */ + +create table #mergepublication ( +id int, +name sysname, +description varchar(255), +status tinyint, +retention int, +syncmode tinyint, +allowpush int, +allowpull int, +allowanon int, +centralizedconflicts int, +priority float(8), +snapshotready tinyint, +publicationtype int, +pubid uniqueidentifier, +snapshotjobid binary(16), +enabledforinternet int, +dynamicfilter int, +hassubscription int, +snapshotdefaultfolder bit, +altsnapshotdefaultfolder nvarchar(255), +presnapshotscript nvarchar(255), +postsnapshotscript nvarchar(255), +compresssnapshot bit, +ftpaddress nvarchar(255), +ftpport int, +ftpsubdirectory nvarchar(255), +ftplogin sysname, +conflictretention int, +keeppartitionchanges int, +allowsubscriptioncopy int, +allowsynctoalternate int, +validatesubscriberinfo nvarchar(500), +bkwdcomplevel int, +publishactivedir bit, +maxconcurrentmerge int, +maxconcurrentdynamicsnapshots int, +usepartitiongr int, +numarticles int, +replicateddl int, +pubnumber smallint, +allowsubintsnapshot bit, +allowwebsync bit, +websynchurl nvarchar(500), +allowpartrealign bit, +retentionperiodunit tinyint, +hasdownloadonlyarticles bit, +decentralizedconflicts int, +generationlevelthreshold int, +automaticreinitialpolicy bit) + +/* Insert into the temp table the values of the merge publication. */ + +insert into #mergepublication exec sp_helpmergepublication; + +/* Check to see that the insert worked. */ + +select * from #mergepublication; + +/* Declare the variable. */ + +declare @allowpush int, + +/*Assign the allowpush variable. */ +set @allowpush=(select allowpush from #mergepublication) + +/* If push subscription is not supported then use sp_changemergepublication and set the value to true. */ + +if @allowpush <>1 +begin +exec sp_changemergepublication +'pub_downloadonly_mysalesmerge','allow_push','true' +end +exec sp_addmergesubscription +@publication = 'pub_downloadonly_mysalesmerge', +@subscriber = 'BIO-V7V30JTZLZS\BIOREPL', +@subscriber_db = 'mysales_remotedown_merge1', +@subscription_type = 'Push', +@sync_type = 'Automatic', +@subscriber_type = 'Local', +@subscription_priority = 0, +@use_interactive_resolver = 'False' + +/* Add the merge push subscription agent on the +publication database. */ + +exec sp_addmergepushsubscription_agent +@publication = 'pub_downloadonly_mysalesmerge', +@subscriber ='BIO-V7V30JTZLZS\BIOREPL', +@subscriber_db = 'mysales_remotedown_merge1', +@job_login = 'BIO-V7V30JTZLZS\SujoyPaul', + +/*Note you can only specify @job_password to null +if the @job_login is null. If the password is set +to null, the Merge Agent will be created and will +run under the SQL Server Agent Service account*/ + +@job_password = *****, +@subscriber_security_mode = 0, +@subscriber_login = 'sa', +@subscriber_password = null, +@publisher_security_mode = 1, +@frequency_type = 64, +@frequency_interval = 0, +@frequency_relative_interval = 0, +@frequency_recurrence_factor = 0, +@frequency_subday = 0, +@frequency_subday_interval = 0, +@active_start_time_of_day = 0, +@active_end_time_of_day = 235959, +@active_start_date = 0, +@active_end_date = 0 + +/* Finally drop the temp table. */ + +drop table #mergepublication +go +Listing 13-11. Registering the subscription on the publication database +/* Execute this on the publication database. */ + +use [mysales_merge2] +go + +sp_addmergesubscription +@publication = 'pub_stdpub_mysalesmerge2', +@subscriber ='BIO-V7V30JTZLZS\BIOREPL_PEER', +@subscriber_db = 'mysales_remotestd_merge_peer', +@subscription_type = 'Pull', +@sync_type = 'Automatic', +@subscriber_type = 'Global', +@subscription_priority = 75, +@use_interactive_resolver = 'False' +Go +Listing 13-12. Creating a pull subscription and adding the pull subscription agent +/* Execute this on the subscription database. */ + +use [mysales_remotestd_merge_peer] +go + +/* Create the pull subscription. */ + +sp_addmergepullsubscription +@publisher = 'BIO-V7V30JTZLZS\BIOREPL', +@publication = 'pub_stdpub_mysalesmerge2', +@publisher_db = 'mysales_merge2', +@subscriber_type = 'Global', +@subscription_priority = 75, +@sync_type = 'Automatic' +Go + +/* Add the pull subscription agent. */ + +sp_addmergepullsubscription_agent +@publisher = 'BIO-V7V30JTZLZS\BIOREPL', +@publisher_db = 'mysales_merge2', +@publication = 'pub_stdpub_mysalesmerge2', +@distributor = 'BIO-V7V30JTZLZS\BIOREPL', +@distributor_security_mode = 1, +@distributor_login = '', +@distributor_password = '', +@enabled_for_syncmgr = 'False', +@job_login = null, +@job_password = null, +@publisher_security_mode = 1, +@publisher_login = '', +@publisher_password = '', +@use_interactive_resolver = 'False', +@use_web_sync = 0 +Go +Listing 13-13. Setting up a pull subscription for client type subscription +/* Execute this on the publication database. */ + +use [mysales_merge_replpeer] +go + +/* Enable the pull subscription on the publication database. */ + +sp_addmergesubscription +@publication = 'pub_mysales_mergereplpeer_hostname', +@subscriber = 'BIO-V7V30JTZLZS\BIOREPL_PEER', +@subscriber_db = 'mysales_mergehost_sub', +@subscription_type = 'pull', +@subscriber_type = 'local', +@subscription_priority = 0, +@sync_type = 'Automatic' +go + +/* Add the pull subscription on the subscription database. */ + +use [mysales_mergehost_sub] + +sp_addmergepullsubscription +@publisher = 'BIO-V7V30JTZLZS\BIOREPL_PEER', +@publication = 'pub_mysales_mergereplpeer_hostname', +@publisher_db = 'mysales_merge_replpeer', +@subscriber_type = 'Local', +@subscription_priority = 0, +@sync_type = 'Automatic' + +/* Add the pull subscription agent on the Subscriber server. */ + +sp_addmergepullsubscription_agent +@publisher = 'BIO-V7V30JTZLZS\BIOREPL_PEER', +@publisher_db = 'mysales_merge_replpeer', +@publication = 'pub_mysales_mergereplpeer_hostname', +@distributor = 'BIO-V7V30JTZLZS\BIOREPL_PEER', +@distributor_security_mode = 1, +@distributor_login = '', +@distributor_password = null, +@enabled_for_syncmgr = 'False', +@job_login = null, +@job_password = null, +@publisher_security_mode = 1, +@publisher_login = null, +@publisher_password = null, +@use_interactive_resolver = 'False', +@dynamic_snapshot_location = null, +@use_web_sync = 0, +@hostname = 'BIO-V7V30JTZLZS-SALES' +Go +Listing 13-14. Assigning the identity property to the WhseID column +Use mysales_pub_identity +Go +create table [myinventory].[Warehouse] +( + WhseID int identity(1,1) not for replication not null, + WhseName varchar(20) null , + WhseAddress1 varchar(30) null , + Whse_City varchar(20) null , + Whse_Postal_Code varchar(7) null , + constraint PK_WAREHOUSE primary key (WhseID) +) + +Listing 13-15. Setting up merge publication with identity range management +/* Enable the replication database */ + +use master +exec sp_replicationdboption @dbname = 'mysales_pub_identity', +@optname = 'merge publish', +@value = 'true' +GO + +/* Adding the merge publication */ + +use [mysales_pub_identity] +exec sp_addmergepublication @publication = 'pub_mysales_identity', +@sync_mode = 'native', +@retention = 14, + +@allow_push = 'true', +@allow_pull = 'true', +@allow_anonymous = 'true', + +@enabled_for_internet = 'false', +@snapshot_in_defaultfolder = 'true', +@compress_snapshot = 'false', +@allow_subscription_copy = 'false', +@add_to_active_directory = 'false', +@dynamic_filters = 'false', + +@conflict_retention = 14, +@keep_partition_changes = 'false', +@allow_synctoalternate = 'false', + +@max_concurrent_merge = 0, +@max_concurrent_dynamic_snapshots = 0, +@use_partition_groups = 'false', + +@publication_compatibility_level = '90RTM', +@replicate_ddl = 1, +@allow_subscriber_initiated_snapshot = 'false', + +@allow_web_synchronization = 'false', +@allow_partition_realignment = 'true', +@retention_period_unit = 'days', + +@conflict_logging = 'both', +@automatic_reinitialization_policy = 0 +GO + +/* Add the publication snapshot */ + +exec sp_addpublication_snapshot +@publication = 'pub_mysales_identity', +@frequency_type = 4, +@frequency_interval = 14, +@frequency_relative_interval = 1, +@frequency_recurrence_factor = 0, + +@frequency_subday = 1, +@frequency_subday_interval = 5, +@active_start_time_of_day = 500, + +@active_end_time_of_day = 235959, +@active_start_date = 0, +@active_end_date = 0, + +@job_login = null, +@job_password = null, +@publisher_security_mode = 1 + +/* Grant publication access */ + +exec sp_grant_publication_access +@publication = 'pub_mysales_identity', +@login = 'sa' +GO + +GO +exec sp_grant_publication_access +@publication = 'pub_mysales_identity', +@login = 'distributor_admin' +GO + +/* Add the merge articles */ + +use [mysales_pub_identity] +go + +exec sp_addmergearticle +@publication = 'pub_mysales_identity', +@article = 'Warehouse', +@source_owner = 'myinventory', + +@source_object = 'Warehouse', + @type = 'table', +@creation_script = '', + +@pre_creation_cmd = 'drop', +@schema_option = 0x000000000C034FD1, + +@identityrangemanagementoption = 'auto', +@pub_identity_range = 10000, +@identity_range = 1000, +@threshold = 80, + +@destination_owner = 'myinventory', +@force_reinit_subscription = 1, +@column_tracking = 'false', + +@subset_filterclause = '', +@vertical_partition = 'false', +@verify_resolver_signature = 1, + +@allow_interactive_resolver = 'false', +@fast_multicol_updateproc = 'true', +@check_permissions = 0, + +@subscriber_upload_options = 0, +@delete_tracking = 'true', +@compensate_for_errors = 'false', + +@stream_blob_columns ='false', +@partition_options = 0 +GO + +use [mysales_pub_identity] +exec sp_changemergepublication 'pub_mysales_identity', 'status', 'active' +GO + +Listing 13-16. Setting up a push subscription +use [mysales_pub_identity] +exec sp_addmergesubscription @publication = 'pub_mysales_identity', +@subscriber = 'BIO-V7V30JTZLS\BIOREPL', +@subscriber_db = 'mysales_sub_identity', + +@subscription_type = 'Push', +@sync_type = 'Automatic', +@subscriber_type = 'Global', +@subscription_priority = 75, +@description = null, +@use_interactive_resolver = 'False' + +exec sp_addmergepushsubscription_agent +@publication = 'pub_mysales_identity', +@subscriber = 'BIO-V7V30JTZLS\BIOREPL', + +@subscriber_db = 'mysales_sub_identity', +@job_login = null, +@job_password = null, + +@subscriber_security_mode = 1, +@publisher_security_mode = 1, +@frequency_type = 64, + +@frequency_interval = 0, +@frequency_relative_interval = 0, +@frequency_recurrence_factor = 0, +@frequency_subday = 0, + +@frequency_subday_interval = 0, +@active_start_time_of_day = 0, +@active_end_time_of_day = 235959, +@active_start_date = 20060822, +@active_end_date = 99991231, +@enabled_for_syncmgr = 'False' +GO diff --git a/Codes/Chapter14/Chapter14codes.txt b/Codes/Chapter14/Chapter14codes.txt new file mode 100644 index 0000000..114db2d --- /dev/null +++ b/Codes/Chapter14/Chapter14codes.txt @@ -0,0 +1,205 @@ +Listing 14-1. Listing the subsystems in SQL Server +:setvar logintimeout 120 +:setvar server "BIO-V7V30JTZLZS\BIOREPL" +:setvar user "sa" +:setvar pwd "sujoy" +:connect $(server) -l $(logintimeout) -U $(user) -P $(pwd) +USE msdb +go + +sp_enum_sqlagent_subsystems +go +Listing 14-2. Listing the proxies and corresponding credentials for the Replication Merge subsystem +/*Set the SQLCMD variables and the connection settings first*/ + +:setvar logintimeout 120 +:setvar server "BIO-V7V30JTZLZS\BIOREPL" +:setvar user "sa" +:setvar pwd "sujoy" +:connect $(server) -l $(logintimeout) -U $(user) -P $(pwd) + +set nocount on + +/* Need to run this on the msdb database */ +use msdb +go + +select a.subsystem_id, +a.subsystem, +a.description_id, +a.subsystem_dll, +a.agent_exe, +a.max_worker_threads, +c.flags, +d.proxy_id, +d.name as proxyname, +d.enabled, +d.description, +d.user_sid, +e.credential_id, +e.name as credentialname, +e.credential_identity, +e.create_date as credentialcreatedate, e.modify_date as credentialmodifydate, +f.sid, +f.status, +f.createdate as logincreatedate, +f.name as loginname, +f.sysadmin, +f.isntuser + +into #proxies + +from syssubsystems a, +sysproxysubsystem b, +sysproxylogin c, +sysproxies d, +sys.credentials e, +sys.syslogins f + +where a.subsystem_id=b.subsystem_id and + b.proxy_id=c.proxy_id and + c.proxy_id=d.proxy_id and + d.credential_id=e.credential_id and + c.sid=f.sid + +/* Count to see that proxies exist */ + +declare @countmerge int +set @countmerge= +(select subsystem_id from #proxies +where subsystem like 'merge' +group by subsystem_id +having count(0)>1) + +/* If the number of counts is 1 or more then find those proxies that belong to the merge subsystem */ + +if (@countmerge >0) +begin +select * from #proxies where subsystem like 'merge'; +end + +/*Finally drop the temp table #proxies */ + +drop table #proxies +go + +From the sidebar on Database Triggers + +create trigger ddlmysales_merge +on database +for drop_table, drop_view, drop_procedure, +alter_table, alter_view, alter_procedure, +create_table, create_view, create_procedure +as +declare @eventdata xml + +set @eventdata=eventdata() + +select +@eventdata.value('(/EVENT_INSTANCE/EventType)[1]','varchar(100)') as [EventType], +@eventdata.value('(/EVENT_INSTANCE/PostTime)[1]','varchar(100)') as [PostTime], +@eventdata.value('(/EVENT_INSTANCE/SPID)[1]','varchar(25)') as [SPID], +@eventdata.value('(/EVENT_INSTANCE/ServerName)[1]','varchar(30)') as [Servername], +@eventdata.value('(/EVENT_INSTANCE/LoginName)[1]','varchar(30)') as [Loginname], +@eventdata.value('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]','varchar(2000)') as [CommandText] + + +raiserror('Create, drop and alter statements for tables, +views and procedures not allowed',16,1) +rollback +go +Listing 14-3. Viewing the code for the sp_MSinitdynamicsubscriber stored procedure +/*Execute this on the publication database */ + +Use mysales_mergevwusp +go +sp_helptext 'sp_MSinitidynamicsubscriber' +go + +Listing 14-4. Checking the stored procedures in view_sel_proc for associated dynamic filters +/* Execute this on the publication database */ + +Use mysales_mergevwusp +Go + +select a.filtername, +a.join_articlename, +a.join_unique_key, +a.expand_proc, +a.join_filterclause, +a.filter_type, +b.column_tracking, +b.status, +b.insert_proc, +b.update_proc, +b.select_proc, +b.metadata_select_proc, +b.resolver_info, +b.view_sel_proc +from sysmergesubsetfilters a,sysmergearticles b +where a.art_nickname=b.nickname +go + +Listing 14-5. The objects on which the MSmerge_sel_2FECAB1A04FA41911A6BFA3A3EA14622 stored procedure depends +/*Execute this on the publication database */ +Use mysales_mergevwusp +Go +Sp_depends 'MSmerge_sel_2FECAB1A04FA41911A6BFA3A3EA14622' +go + +Listing 14-6. Determining the total number of changes for a generation that is already closed +/*Execute this on the publication database */ +Use mysales_mergevwusp +Go + +select a.generation, +count(*) as changecount, +b.nickname +from MSmerge_genhistory a, +MSmerge_contents c, +sysmergearticles b +where c.generation = a.generation +and b.nickname=c.tablenick +and c.generation = a.generation +and a.genstatus<>0 +group by a.generation, b.nickname +go +Listing 14-7. Finding the generation that has been deleted +/*Execute this on the publication database */ + +Use mysales_mergevwusp +Go +select a.generation, +count(*) as changecount, +b.nickname +from MSmerge_genhistory a, +MSmerge_tombstone t, +sysmergearticles b +where t.generation = a.generation +and b.nickname=t.tablenick +and a.genstatus<>0 +group by a.generation, b.nickname +go +Listing 14-8. Determining the location of the dynamic snapshot and the dynamic login name +/* Execute this on the publication database used for parameterized filters */ +Use mysales_mergevwusp +Go + +select a.name, +a.pubid, +a.job_id, +a.agent_id, +a.dynamic_filter_login, +a.dynamic_snapshot_location, +b.partition_id, +b.last_started +from MSdynamicsnapshotjobs a +left outer join MSmerge_dynamic_snapshots b on +a.partition_id=b.partition_id +go +From the sidebar Conflict Resolvers + +/*execute this on the publication database */ +Use merge_mysalesvwusp +Go +Exec sp_enumcustomresolvers diff --git a/Codes/Chapter15/Chapter15codes.txt b/Codes/Chapter15/Chapter15codes.txt new file mode 100644 index 0000000..94c5c50 --- /dev/null +++ b/Codes/Chapter15/Chapter15codes.txt @@ -0,0 +1,402 @@ +Listing 15-1. Generic backup script for use with other databases involved in snapshot replication +/* Execute this using the SQLCMD utility */ +/* Declare the SQLCMD variables */ + +:setvar logintimeout 120 +:setvar server "BIO-V7V30JTZLZS\BIOREPL" +:setvar user "sa" +:setvar pwd "sujoy" +:connect $(server) -l $(logintimeout) -U $(user) -P $(pwd) + +/*Back up the database */ + +BACKUP DATABASE $(db) TO +DISK = '$(path)\$(db).bak' +WITH NOFORMAT, INIT, +NAME = '$(db)Database Backup', +SKIP, +NOREWIND, +NOUNLOAD, +STATS = 10, +CHECKSUM +Go + +declare @backupSetId as int +select @backupSetId = position from msdb..backupset +where +database_name='$(db)' and backup_set_id= +(select max(backup_set_id) from msdb..backupset where database_name='$(db)' ) + +/* If backup does not exist, raise the error */ + +if @backupSetId is null +begin +raiserror('Verify failed. Backup information for database ''$(db)'' + not found.', 16, 1) +end + +RESTORE VERIFYONLY +FROM DISK = '$(path)\$(db).bak' +WITH FILE = @backupSetId, +NOUNLOAD, +NOREWIND +go +Listing 15-2. Checking to find out which databases have the checksum option enabled +/*Execute this on the msdb database */ + +Use msdb +Go + +select backup_size, +database_name, +first_lsn,last_lsn, +checkpoint_lsn, +name, +user_name, +server_name, +is_damaged, +has_backup_checksums +from backupset +order by has_backup_checksums desc +go + +Listing 15-3. Finding tasks waiting to be run for the CPU_id associated with the scheduler +/* Execute this on the database that is being used for backup +with checksum enabled */ + +Use mysales_snapshot +go + +select +scheduler_id, +current_tasks_count, +runnable_tasks_count, +is_online, +cpu_id, +current_workers_count, +active_workers_count, +work_queue_count, +pending_disk_io_count +from +sys.dm_os_schedulers +order by scheduler_id +go + +Listing 15-4. Determining the average CPU time for the batch of SQL statements +/* Execute this on the publication database*/ +Use mysales_snapshot +go + +select top 20 +(total_worker_time/execution_count) AS AvgCPUTime, +total_worker_time, +execution_count, +statement_start_offset, +statement_end_offset, +(select text from sys.dm_exec_sql_text(sql_handle)) AS querytext +from +sys.dm_exec_query_stats +order by AvgCPUTime desc +go + +Listing 15-5. Generic restoration script for use with other databases involved in snapshot replication +/* Execute this using the SQLCMD utility */ + +/* Declare the SQLCMD variables */ +:setvar logintimeout 120 +:setvar server "BIO-V7V30JTZLZS\BIOREPL" +:setvar user "sa" +:setvar pwd "sujoy" +:connect $(server) -l $(logintimeout) -U $(user) -P $(pwd) + +/*Restore the database */ + +RESTORE DATABASE $(db1) FROM +DISK = '$(path)\$(db).bak' +WITH FILE = 1, +MOVE '$(db)' TO +'$(path1)\$(db1).mdf', +MOVE '$(log)' TO '$(path1)\$(log1).ldf', +KEEP_REPLICATION, +NOUNLOAD, +STATS = 10 +GO + +Listing 15-6. Backup script running on a Windows-authenticated SQL Server instance +/*Execute using SQLCMD utility on the BIO-V7V30JTZLZS\BIOREPL_PEER instance*/ + +/*Declare the variables to be used for Windows Authentication; the username and password are not specified */ + +:setvar logintimeout 120 +:setvar server "BIO-V7V30JTZLZS\BIOREPL_PEER" +:connect $(server) -l $(logintimeout) + +/*Back up the database */ + +BACKUP DATABASE $(db) TO DISK = N'$(path)\$(db).bak' +WITH NOFORMAT, INIT, +NAME = N'$(db)Database Backup', +SKIP, +NOREWIND, +NOUNLOAD, +STATS = 10, +CHECKSUM +GO + +/* Locate the appropriate backup set and files */ + +declare @backupSetId as int +select @backupSetId = position from msdb..backupset where + database_name='$(db)' and backup_set_id= +(select max(backup_set_id) from msdb..backupset where database_name='$(db)' ) + +/*Verify that the backup is available */ + +if @backupSetId is null +begin +raiserror +(N'Verify failed. Backup information for database ''$(db)'' not found.', 16, 1) +end + +/*Restore the database */ + +RESTORE VERIFYONLY FROM DISK = N'$(path)\$(db).bak' +WITH FILE = @backupSetId, NOUNLOAD, NOREWIND +GO +Listing 15-7. Check for the "sync with backup" option. +/* Can be executed either on the publication or the distribution database*/ +/*In this case, check it on the publication database */ + +Use mysales_copy_restore +Go + +SELECT DATABASEPROPERTYEX +('mysales_copy_restore','IsSyncWithBackup') +Go +Listing 15-8. Finding the number of undelivered commands +/* Execute this on the distribution database */ + +Use distribution +Go + +select a.agent_id, +a.UndelivCmdsInDistDB, +a.DelivCmdsInDistDB, +b.name, +b.publisher_db, +b.publication +from MSdistribution_status a,MSdistribution_agents b +where a.agent_id=b.id and +b.publication='pub_mysales_copy_myinventory' and +b.name= +'BIO-V7V30JTZLZS\BIORE-mysales_copy-pub_mysales_copy_myin-BIO-V7V30JTZLZS\BIORE-17' +go + +Listing 15-9. Checking for nonconvergence between the publication and subscription databases +/* Run from the command prompt */ + +tablediff -sourceserver BIO-V7V30JTZLZS\BIOREPL_PEER -sourcedatabase + mysales_copy -sourcetable Item -sourceschema myinventory - +destinationserver BIO-V7V30JTZLZS\BIOREPL_PEER -destinationdatabase +mysalescopy_stpub_remotepush -destinationtable Item - +destinationschema myinventory +-f C:\files\tabledifferencepeer.sql -o C:\files\tablediffoutput.txt + +Listing 15-10. Enabling the sync with backup option +/* Use the sqlcmd utility to execute the script */ + +/*Declare the variables */ +:setvar logintimeout 120 +:setvar server "BIO-V7V30JTZLZS\BIOREPL" +:setvar user "sa" +:setvar pwd "sujoy" +:connect $(server) -l $(logintimeout) -U $(user) -P $(pwd) + +/*Enable the sync with backup option */ + +Use $(db) +Go +if DATABASEPROPERTYEX +('$(db)','$(property)')=0 +exec sp_replicationdboption '$(db)','sync with backup','true' +else +print "'$(db)' is already enabled for sync with backup" +Go + +Listing 15-11. Backup script for a publication database that has the sync with backup option enabled +/*Execute this with the SQLCMD utility */ + +/*Declare the variables */ + +:setvar logintimeout 120 +:setvar server "BIO-V7V30JTZLZS\BIOREPL" +:setvar user "sa" +:setvar pwd "sujoy" +:connect $(server) -l $(logintimeout) -U $(user) -P $(pwd) + +Use $(db) +Go + +/*Check the property of the database and then run a DBCC Checkdb */ + +IF DATABASEPROPERTYEX +('$(db)','$(property)')='FULL' +and +DATABASEPROPERTYEX +('$(db)','$(property1)')='Online' +begin +dbcc checkdb('$(db)') with physical_only +end +go + +/*Back up the database */ + +BACKUP DATABASE $(db) +TO DISK = N'$(path)\$(db).bak' WITH NOFORMAT, INIT, +NAME = +N'$(db)Database Backup', +SKIP, +NOREWIND, +NOUNLOAD, +STATS = 10, +CHECKSUM +GO + +declare @backupSetId as int +select @backupSetId = position from +msdb..backupset where database_name='$(db)' and +backup_set_id=(select max(backup_set_id) from msdb..backupset +where database_name='$(db)' ) + +/*Verify the backup information for the database */ + +if @backupSetId is null +begin +raiserror(N'Verify failed. Backup information for database ''$(db)'' +not found.', 16, 1) +end + +/*Restore the database */ + +RESTORE VERIFYONLY FROM +DISK = N'$(path)\$(db).bak' +WITH FILE = @backupSetId, +NOUNLOAD, +NOREWIND +GO +Listing 15-12. Deleting rows from MSreplication_queue +/*Execute this on the subscription database that subscribes to + queued subscriptions*/ + +use mysales_remote_queueupd +go +if ((select count(*) from MSreplication_queue) >0) +delete from MSreplication_queue +go +Listing 15-13. Finding out how many articles are present in the publication +/*Execute this on the publication database */ +/*Declare the variables */ + +:setvar logintimeout 120 +:setvar server "BIO-V7V30JTZLZS\BIOREPL" +:setvar user "sa" +:setvar password "sujoy" +:connect $(server) -l $(logintimeout) -U $(user) -P $(password) + +use $(db) +go + +select a.artid, +a.dest_table, +a.name as sourcetable, +a.dest_owner as destinationowner, +b.name as publicationname, +c.dest_db as subscriptiondatabase +from sysarticles a, syspublications b, +syssubscriptions c +where a.pubid=b.pubid and a.artid=c.artid +and c.dest_db='$(subname)' +and b.name='$(pubname)' +go + +Listing 15-14. Dropping the metadata from the distribution database +/*Execute this on the distribution database on the node that failed */ + +Use distribution +Go + +/*Specify the name of the publication database and the name of the publication */ + +sp_removedistpublisherdbreplication 'pub_purchaseorderrepl_peer', +'purchaseorder_repl' +Go + +Listing 15-15. Dropping a subscription from the publication for peer-to-peer replication +/*Execute this on the distribution database on the +publishing server that is working */ + +/*Declare the variables */ + +:setvar logintimeout 120 +:setvar server "BIO-V7V30JTZLZS\BIOREPL" +:setvar user "sa" +:setvar password "sujoy" +:connect $(server) -l $(logintimeout) -U $(user) -P $(password) +:setvar subtype 0 + +/*For pull subscriptions, set the subtype variable to 1.*/ + +:setvar statusnum 2 + +use $(db) +go + +/*Declare a table variable */ + +declare @subscription_push table +(publisher_id smallint, +publisher_db sysname, +subscriber_db sysname, +subscription_type int, +sync_type tinyint, +status tinyint); + +/* Insert data into the table variable from the MSsubscriptions table in the distribution database*/ + +insert into @subscription_push +select +publisher_id, +publisher_db, +subscriber_db, +subscription_type, +sync_type, +status from $(db)..MSsubscriptions +where subscription_type=$(subtype) and status=$(statusnum) + +/* Check the data of the @subscription_push table variable */ + +select * from @subscription_push + +/* Declare table variable that will store the Publisher and the Subscriber information from the MSSubscriber_info table */ + +declare @subscriberinfo table +(publisher sysname, +subscriber sysname); + +/* Insert the data into the @subscriberinfo table variable */ + +insert into @subscriberinfo +select publisher,subscriber from $(db)..MSsubscriber_info + +/* Check the data for the @subscriberinfo table variable */ +select * from @subscriberinfo + +/* Finally on the Publisher server on the publication +database, remove the subscription for the Publisher*/ + +use $(pubdb) +go + +exec sp_dropsubscription '$(pubname)','$(article)','$(subserver)' +go + diff --git a/Codes/Chapter16/Chapter16codes.txt b/Codes/Chapter16/Chapter16codes.txt new file mode 100644 index 0000000..ed441ee --- /dev/null +++ b/Codes/Chapter16/Chapter16codes.txt @@ -0,0 +1,470 @@ +Listing 16-1. Validating all subscriptions for a merge publication +/*Execute this on the publication database */ + +:setvar logintimeout 120 +:setvar server "BIO-V7V30JTZLZS\BIOREPL" +:setvar user "sa" +:setvar pwd "sujoy" +:connect $(server) -l $(logintimeout) -U $(user) -P $(pwd) + +/*Specification of the level --- rowcount and binary checksum */ + +:setvar level 3 + +/*Execute this on the publication database */ + +use $(db) +go + +/*Need the publication name and the level */ + +sp_validatemergepublication '$(mergepublication)',$(level) +go +Listing 16-2. Checking whether the database is set for merge publication +/*Execute this on the publication database */ +Use mysales_merge +Go + +/*Find the name of the database and the category */ +select name,category from sys.sysdatabases +/*category=4 means that it is set for merge publication*/ +where category=4 +go + +Listing 16-3. Checking the validation of the database +/* execute this on the publication database */ +Use mysales_merge +Go + +select b.name as [publication name], a.schematype, +b.publisher, +b.publisher_db +from sysmergeschemachange a, +sysmergepublications b +where a.pubid=b.pubid and +a.schematype=66 +go +Listing 16-4. Executing the Merge Agent +/* Can be used as a batch file */ +/*Step 1: Declare the variables first */ + +declare @cmd varchar(4000), +@publisher varchar(100), +@publicationDB varchar(100), +@publication varchar(100), +@subscriptionDB varchar(100), +/* assign your login and password values */ +@login varchar(3), +@password varchar(6) + +/*Step 2: Assign values to the variables */ + +set @publisher='BIO-V7V30JTZLZS\BIOREPL' +set @publicationDB='mysales_merge' +set @publication='pub_download_mysalesmerge' +set @subscriptionDB='mysalesmerge_remote_exportpulldownload1' +/* assign your login and password values */ +set @login='xxxx' +set @password='xxxx' + +/*Step 3: Assign the parameters to the Merge Agent and +store them in the @cmd variable */ +/* There should not be any space for after the Merge Agent +and the parameters. I have done this for demonstration purposes. */ + +set @cmd='"C:\Program Files\Microsoft SQL Server\90\COM\REPLMERG.EXE" + -Publication @publication +-Publisher @publisher +-Subscriber @publisher +-Distributor @publisher +-PublisherDB @publicationDB +-SubscriberDB @subscriptionDB +-PublisherSecurityMode 0 +-PublisherLogin @login +-PublisherPassword @password +-OutputVerboseLevel 2 +-SubscriberSecurityMode 0 +-SubscriberLogin @login +-SubscriberPassword @password +-SubscriptionType 1 +-DistributorSecurityMode 0 +-DistributorLogin @login +-DistributorPassword @password + +-Validate 3 + -ParallelUploadDownload 0' + +/*execute the @cmd variable with the xp_cmdshell*/ +exec xp_cmdshell '@cmd' +go +Listing 16-5. Adding a merge subscription for use with SQLCMD +:setvar logintimeout 120 +:setvar server "BIO-V7V30JTZLZS\BIOREPL" +:setvar user "sa" +:setvar pwd "sujoy" +:connect $(server) -l $(logintimeout) -U $(user) -P $(pwd) +/* Execute this on the Publisher server */ + +use $(pubdb) +go +exec sp_addmergesubscription @publication ='$(pubname)', +@subscriber='$(server)', +@subscriber_db='$(subdb)', +@subscription_type ='$(subtype)', +@sync_type ='$(synctype)', +@subscriber_type ='$(subscribertype)', +@subscription_priority=0, +@description = null, +@use_interactive_resolver='$(boolean)' +Go +Listing 16-6. Adding the job for the push merge subscription agent +/*Execute this on the publication database */ +sp_addmergepushsubscription_agent @publication='$(pubname)', +@subscriber = '$(server)', @subscriber_db ='$(subdb)', +@subscriber_security_mode = 0, +@subscriber_login = '$(user)', @subscriber_password = +'$(pwd)', @publisher_security_mode = 1, +@enabled_for_syncmgr = '$(boolean)' +go +Listing 16-7. Calling one file from within another file +:setvar logintimeout 120 +:setvar server "BIO-V7V30JTZLZS\BIOREPL" +:setvar user "sa" +:setvar pwd "sujoy" +:connect $(server) -l $(logintimeout) -U $(user) -P $(pwd) + +/* Execute this on the publisher server */ + +use $(pubdb) +go +exec sp_addmergesubscription @publication ='$(pubname)', +@subscriber='$(server)', +@subscriber_db='$(subdb)', +@subscription_type ='$(subtype)', +@sync_type ='$(synctype)', +@subscriber_type ='$(subscribertype)', +@subscription_priority=0, +@description = null, +@use_interactive_resolver='$(boolean)' +Go + +WAITFOR DELAY '00:00:05' + +declare @filelist table +( fileexist int, +filedir int, +parentdir int +) + +insert @filelist +exec master..xp_fileexist 'C:\files\addmergepushsub.sql' +end +declare @fileexist int +set @fileexist=(select fileexist from @filelist) +if @fileexist=1 +begin +:r C:\files\addmergepushsub.sql +end +else +:Exit +Go +Listing 16-8. Enabling the replication alerts and sending out the notifications +/*Execute this on the msdb database */ +Use msdb +Go +/*Create a table variable to store the information from sp_help_alert */ +declare @alertlist table +( id int, +name sysname, +event_source varchar(100), +event_category_id int, +event_id int, +message_id int, +severity int, +enabled tinyint, +delay_between_responses int, +last_occurrence_date int, +last_occurrence_time int, +last_response_date int, +last_response_time int, +notification_message varchar(512), +include_event_description tinyint, +database_name sysname null, +event_description_keyword varchar(100), +occurrence_count int, +count_reset_date int, +count_reset_time int, +job_id uniqueidentifier, +job_name sysname null, +has_notification int, +flags int, +performance_condition varchar(512), +category_name sysname null, +wmi_namespace sysname null, +wmi_query varchar(512), +type int +) +insert @alertlist exec +sp_help_alert + +/*Declare a variable for the cursor */ +declare @alertname sysname + +/*Declare the cursor name updatealertnotification */ + +declare updatealertnotification cursor for + +/* Do not want to enable any other replication alerts other than the ones that will be used for validation */ + +/* There is a space between Replication: and S. Otherwise the + engine will not return the right result set. */ + +select name from @alertlist +where enabled=0 and name like 'Replication: S%' +/*Open the cursor */ + +open updatealertnotification + +/*Fetch the first result and store it in the variable */ + +fetch next from updatealertnotification +into @alertname + +/*Check to see if there are any rows to fetch */ + +while @@fetch_status=0 +begin + +/*Use sp_update_alert to enable the alerts used for validation +for the database 'mysales_merge' */ + +exec sp_update_alert @name=@alertname,@database_name='mysales_merge',@enabled=1, +@include_event_description_in=4; + +/* The alerts are then notified using the sp_update_notification*/ +exec sp_update_notification @alert_name=@alertname, +@operator_name='BIO-V7V30JTZLZS\Sujoy Paul',@notification_method=4 + +/* Then fetch the next record */ + +fetch next from updatealertnotification +into @alertname +end + +/*Close and deallocate the cursor */ + +close updatealertnotification +deallocate updatealertnotification + +/*Finally check whether the alerts have been enabled*/ + +select * from @alertlist +go + +Listing 16-9. Configuration of log shipping in the primary server + /* Run this script on the Primary server +The monitor server is also located on the Primary server */ + +:setvar logintimeout 120 +:setvar server "SHW-TOR-WS039-A\BIOREPL_PEER" +---:setvar user "sa" +---:setvar password "sujoy" +:connect $(server) -l $(logintimeout) +--- -U $(user) -P $(password) + +/*Execute this from msdb database */ + +use msdb +go + +DECLARE @LS_BackupJobId AS uniqueidentifier +DECLARE @LS_PrimaryId AS uniqueidentifier +DECLARE @SP_Add_RetCode As int + + +EXEC @SP_Add_RetCode = master.dbo.sp_add_log_shipping_primary_database + @database ='$(primarydb)' -----'mysales_snapshot' + ,@backup_directory ='$(backupfilepath)' -----'D:\files' + ,@backup_share ='$(sharename)' -----'\\SHW-TOR-WS039-A\BIOREPL_PEER' + ,@backup_job_name ='$(backupjobname)' -----'LSBackup_mysales_snapshot' ,@backup_retention_period = 4320 + , +/* change the variable name if the monitor server is located +other than the primary server */ + +@monitor_server ='$(server)' -----'SHW-TOR-WS039-A\BIOREPL_PEER' + ,@monitor_server_security_mode = $(securitymode) + ,@backup_threshold = 60 + ,@threshold_alert_enabled = 1 + ,@history_retention_period = 5760 + ,@backup_job_id = @LS_BackupJobId OUTPUT + ,@primary_id = @LS_PrimaryId OUTPUT + ,@overwrite = 1 + + +IF (@@ERROR = 0 AND @SP_Add_RetCode = 0) +BEGIN + +DECLARE @LS_BackUpScheduleUID As uniqueidentifier +DECLARE @LS_BackUpScheduleID AS int + + +EXEC msdb.dbo.sp_add_schedule + @schedule_name ='$(schedulename)' + ---'LSBackupSchedule_SHW-TOR-WS039-A\BIOREPL_PEER1' + ,@enabled = $(enabled) + ,@freq_type = 4 + ,@freq_interval = 1 + ,@freq_subday_type = 4 + ,@freq_subday_interval = 15 + ,@freq_recurrence_factor = 0 + ,@active_start_date = 20060910 + ,@active_end_date = 99991231 + ,@active_start_time = 0 + ,@active_end_time = 235900 + ,@schedule_uid = @LS_BackUpScheduleUID OUTPUT + ,@schedule_id = @LS_BackUpScheduleID OUTPUT + +EXEC msdb.dbo.sp_attach_schedule + @job_id = @LS_BackupJobId + ,@schedule_id = @LS_BackUpScheduleID + +END + +/* EXEC msdb.dbo.sp_update_job + @job_id = @LS_BackupJobId + ,@enabled = 0 */ + +Listing 16-10. Configuring log shipping on the secondary server + +:setvar logintimeout 240 +:setvar server "SHW-TOR-WS039-A\BIOREPL" +---:setvar user "sa" +---:setvar password "sujoy" +:connect $(server) -l $(logintimeout) +--- -U $(user) -P $(password) + + +use msdb +go + +DECLARE @LS_Secondary__CopyJobId AS uniqueidentifier +DECLARE @LS_Secondary__RestoreJobId AS uniqueidentifier +DECLARE @LS_Secondary__SecondaryId AS uniqueidentifier +DECLARE @LS_Add_RetCode As int + + +EXEC @LS_Add_RetCode = master.dbo.sp_add_log_shipping_secondary_primary + @primary_server = '$(primaryserver)' + ,@primary_database = '$(primarydb)' + ,@backup_source_directory = '$(sharename)' + ,@backup_destination_directory = '$(backupfilepath)' + ,@copy_job_name = '$(copyjobname)' + ,@restore_job_name = '$(restorejobname)' + ,@file_retention_period = 4320 + ,@monitor_server = '$(primaryserver)' + ,@monitor_server_security_mode =$(securitymode) + ,@overwrite = 1 + ,@copy_job_id = @LS_Secondary__CopyJobId OUTPUT + ,@restore_job_id = @LS_Secondary__RestoreJobId OUTPUT + ,@secondary_id = @LS_Secondary__SecondaryId OUTPUT + +IF (@@ERROR = 0 AND @LS_Add_RetCode = 0) +BEGIN + +DECLARE @LS_SecondaryCopyJobScheduleUID As uniqueidentifier +DECLARE @LS_SecondaryCopyJobScheduleID AS int + +/*create the copy schedule */ +EXEC msdb.dbo.sp_add_schedule + @schedule_name ='DefaultCopyJobSchedule' + ,@enabled = 1 + ,@freq_type = 4 + ,@freq_interval = 1 + ,@freq_subday_type = 4 + ,@freq_subday_interval = 15 + ,@freq_recurrence_factor = 0 + ,@active_start_date = 20060910 + ,@active_end_date = 99991231 + ,@active_start_time = 0 + ,@active_end_time = 235900 + ,@schedule_uid = @LS_SecondaryCopyJobScheduleUID OUTPUT + ,@schedule_id = @LS_SecondaryCopyJobScheduleID OUTPUT + +/*attach the schedule to the job */ + +EXEC msdb.dbo.sp_attach_schedule + @job_id = @LS_Secondary__CopyJobId + ,@schedule_id = @LS_SecondaryCopyJobScheduleID + +DECLARE @LS_SecondaryRestoreJobScheduleUID As uniqueidentifier +DECLARE @LS_SecondaryRestoreJobScheduleID AS int + +/*create the restore schedule */ +EXEC msdb.dbo.sp_add_schedule + @schedule_name ='DefaultRestoreJobSchedule' + ,@enabled = 1 + ,@freq_type = 4 + ,@freq_interval = 1 + ,@freq_subday_type = 4 + ,@freq_subday_interval = 15 + ,@freq_recurrence_factor = 0 + ,@active_start_date = 20060910 + ,@active_end_date = 99991231 + ,@active_start_time = 0 + ,@active_end_time = 235900 + ,@schedule_uid = @LS_SecondaryRestoreJobScheduleUID OUTPUT + ,@schedule_id = @LS_SecondaryRestoreJobScheduleID OUTPUT + +/* Attach the restore schedule to the job */ + +EXEC msdb.dbo.sp_attach_schedule + @job_id = @LS_Secondary__RestoreJobId + ,@schedule_id = @LS_SecondaryRestoreJobScheduleID + + +END + + +DECLARE @LS_Add_RetCode2 As int + + +IF (@@ERROR = 0 AND @LS_Add_RetCode = 0) +BEGIN + +/*Add the secondary database to the secondary server */ + +EXEC @LS_Add_RetCode2 = master.dbo.sp_add_log_shipping_secondary_database + @secondary_database = '$(secondarydb)' + ,@primary_server = '$(primaryserver)' + ,@primary_database = '$(primarydb)' + ,@restore_delay = 0 + ,@restore_mode = 1 + ,@disconnect_users = 1 + ,@restore_threshold = 45 + ,@threshold_alert_enabled = 1 + ,@history_retention_period = 5760 + ,@overwrite = 1 + +END + +Listing 16-11. Adding the secondary database information to the primary server +/* Run this script on the Primary server +The monitor server is also located on the Primary server */ +:setvar logintimeout 120 +:setvar server "SHW-TOR-WS039-A\BIOREPL_PEER" +---:setvar user "sa" +---:setvar password "sujoy" +:connect $(server) -l $(logintimeout) +--- -U $(user) -P $(password) + + +use msdb +go + + +EXEC master.dbo.sp_add_log_shipping_primary_secondary + @primary_database = '$(primarydb)' ----N'mysales_snapshot' + ,@secondary_server = '$(secondaryserver)' ----N'SHW-TOR-WS039-A\BIOREPL' + ,@secondary_database = '$(secondarydb)' ----N'mysales_snapshot' + ,@overwrite = 1 +go diff --git a/Codes/Chapter17/Chapter17codes.txt b/Codes/Chapter17/Chapter17codes.txt new file mode 100644 index 0000000..caddb71 --- /dev/null +++ b/Codes/Chapter17/Chapter17codes.txt @@ -0,0 +1,58 @@ +From the sidebar Performance Counters +Use master +go +select * from sys.dm_os_performance_counters +where object_name like 'SQLServer:Replication%' + +Listing 17-1. Listing locks held by the different databases +/*Execute this on the publication database */ + +use mysales_snapshot_pub +go + +SELECT a.resource_type, +a.resource_associated_entity_id, +a.request_status, +a.request_mode, +a.request_session_id as spid, +a.request_owner_type as [OwnerType], +a.resource_description, +b.dbid, +b.name +FROM sys.dm_tran_locks a, +sys.sysdatabases b +WHERE a.resource_database_id >=1 +Go + +Listing 17-2. Relating event classes to event categories +/*Execute this on the snapshotreplication_perftrace database */ +use snapshotreplication_perftrace +go + +select a.name as [EventClassName], +a.trace_event_id as [EventTrace], +b.category_id, +b.name as [Category], +b.type, +c.subclass_name +from sys.trace_events a, +sys.trace_categories b, +sys.trace_subclass_values c +where b.category_id=a.category_id and +a.trace_event_id=c.trace_event_id and +b.name in ('TSQL','locks','stored procedures') +go +Listing 17-3. Finding CPU-intensive stored procedures and their duration of execution +/*Execute this on the trace database */ +use snapshotreplication_perftrace +go +select eventclass, +textdata, +applicationname, +spid, +duration, +cpu +from snapshotreplication_perftrace +/* eventclass=35 corresponds to SP:Completed */ +where eventclass=35 +go diff --git a/Codes/Chapter18/Chapter18codes.txt b/Codes/Chapter18/Chapter18codes.txt new file mode 100644 index 0000000..c039a74 --- /dev/null +++ b/Codes/Chapter18/Chapter18codes.txt @@ -0,0 +1,521 @@ +Listing 18-1. Setting the tracer token for a transactional publication +:setvar logintimeout 120 +:setvar server "BIO-V7V30JTZLS\BIOREPL " +:connect $(server) -l $(logintimeout) + +/*Execute this on the publication database */ +use $(pubdb) +go + +declare @tokenidoutput int; +exec sys.sp_posttracertoken @publication='$(pubname)', + +/* If you are using heterogeneous publisher then only you need @publisher= '$(server)',*/ + +@tracer_token_id= @tokenidoutput OUTPUT +go +Listing 18-2. Determining the latency of the Distributor server +/*Execute this on the distribution database */ +Use distribution +Go + +/* The time difference between the publisher_commit and the distributor_commit is the distributor_latency */ + +Select a.tracer_id, +a.publication_id, +a.publisher_commit, +a.distributor_commit, +datediff(ms,a.publisher_commit,a.distributor_commit) as distributor_latency, +b.publisher_db, +b.publication_type, +b.publication, +b.allow_push, +b.allow_pull +from MStracer_tokens a, MSpublications b +where a.publication_id=b.publication_id +go +Listing 18-3. Determining the latency for the Subscriber server +/* Execute this on the distribution database */ +use distribution +go + +/* The time difference between the distributor_commit in the MStracer_tokens table and the subscriber_commit column in the MStracer_history table is the subscriber_latency */ + +select a.publication_id, +a.publisher_db, +a.publication, +a.publication_type, +b.subscriber_db, +b.subscription_type, +d.distributor_commit, +c.subscriber_commit, +datediff(ms,d.distributor_commit, c.subscriber_commit) as subscriber_latency +from MSpublications a, +MSdistribution_agents b, +MStracer_history c, +MStracer_tokens d +Where a.publication=b.publication +And b.id=c.agent_id +And c.parent_tracer_id=d.tracer_id +Go +Listing 18-4. Locating the default trace file +/*Execute this on the master database */ +use master +go +select traceid, +property, +value +from +::fn_trace_getinfo(default) +go +Listing 18-5. Reading the trace file +/*Execute this on the master database */ +use master +go + +/*Retrieve rows only for the mysales databases and where the +textdata column is not null */ + +select * from fn_trace_gettable +('C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\LOG\log_31.trc', +default) +where textdata is not null +and databasename like 'mysales%' +go + +Listing 18-6. Scheduling the job for the trace +BEGIN TRANSACTION +DECLARE @ReturnCode INT +SELECT @ReturnCode = 0 + +IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories +WHERE name='Database Maintenance' AND category_class=1) +BEGIN +EXEC @ReturnCode = msdb.dbo.sp_add_category @class='JOB', +@type='LOCAL', +@name='Database Maintenance' +IF (@@ERROR <> 0 OR @ReturnCode <> 0) +GOTO QuitWithRollback + +END +DECLARE @jobId BINARY(16) +EXEC @ReturnCode = msdb.dbo.sp_add_job +@job_name='mysales_perftrace1', +@enabled=1, +@notify_level_eventlog=2, +@notify_level_email=0, +@notify_level_netsend=0, +@notify_level_page=0, +@delete_level=0, +@description='schedules the trace for transactional +replication of mysales database', +@category_name='Database Maintenance', +@owner_login_name=N'sa', +@job_id = @jobId OUTPUT + +IF (@@ERROR <> 0 OR @ReturnCode <> 0) +GOTO QuitWithRollback + +/* Step 1: Add the job step and start the trace: + START THE TRACE */ + +EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, +@step_name='Start the trace ---tranperftrace', +@step_id=1, +@cmdexec_success_code=0, +@on_success_action=3, +@on_success_step_id=0, +@on_fail_action=2, +@on_fail_step_id=0, +@retry_attempts=0, +@retry_interval=0, +@os_run_priority=0, +@subsystem='TSQL', +@command=N'create procedure usp_mysalestranperf +as + +/* Create a Queue */ +declare @rc int +declare @TraceID int +declare @maxfilesize bigint +set @maxfilesize = 5 +-- Please replace the text InsertFileNameHere, with an appropriate +-- filename prefixed by a path, e.g., c:\MyFolder\MyTrace. The .trc extension +-- will be appended to the filename automatically. If you are writing from +-- remote server to local drive, please use UNC path and make sure server has +-- write access to your network share + +exec @rc = sp_trace_create @TraceID output, 0, +N''C:\files\mysales_tranperf1.trc'', @maxfilesize, NULL +if (@rc != 0) goto error + +-- Client side File and Table cannot be scripted + +-- Set the events +declare @on bit +set @on = 1 +exec sp_trace_setevent @TraceID, 148, 11, @on +exec sp_trace_setevent @TraceID, 148, 51, @on +exec sp_trace_setevent @TraceID, 148, 4, @on +exec sp_trace_setevent @TraceID, 148, 12, @on +exec sp_trace_setevent @TraceID, 148, 14, @on +exec sp_trace_setevent @TraceID, 148, 26, @on +exec sp_trace_setevent @TraceID, 148, 60, @on +exec sp_trace_setevent @TraceID, 148, 64, @on +exec sp_trace_setevent @TraceID, 148, 1, @on +exec sp_trace_setevent @TraceID, 148, 41, @on +exec sp_trace_setevent @TraceID, 10, 7, @on +exec sp_trace_setevent @TraceID, 10, 15, @on +exec sp_trace_setevent @TraceID, 10, 31, @on +exec sp_trace_setevent @TraceID, 10, 8, @on +exec sp_trace_setevent @TraceID, 10, 16, @on +exec sp_trace_setevent @TraceID, 10, 48, @on +exec sp_trace_setevent @TraceID, 10, 64, @on +exec sp_trace_setevent @TraceID, 10, 1, @on +exec sp_trace_setevent @TraceID, 10, 9, @on +exec sp_trace_setevent @TraceID, 10, 17, @on +exec sp_trace_setevent @TraceID, 10, 41, @on +exec sp_trace_setevent @TraceID, 10, 49, @on +exec sp_trace_setevent @TraceID, 10, 10, @on +exec sp_trace_setevent @TraceID, 10, 18, @on +exec sp_trace_setevent @TraceID, 10, 26, @on +exec sp_trace_setevent @TraceID, 10, 34, @on +exec sp_trace_setevent @TraceID, 10, 50, @on +exec sp_trace_setevent @TraceID, 10, 3, @on +exec sp_trace_setevent @TraceID, 10, 11, @on +exec sp_trace_setevent @TraceID, 10, 35, @on +exec sp_trace_setevent @TraceID, 10, 51, @on +exec sp_trace_setevent @TraceID, 10, 4, @on +exec sp_trace_setevent @TraceID, 10, 12, @on +exec sp_trace_setevent @TraceID, 10, 60, @on +exec sp_trace_setevent @TraceID, 10, 13, @on +exec sp_trace_setevent @TraceID, 10, 6, @on +exec sp_trace_setevent @TraceID, 10, 14, @on +exec sp_trace_setevent @TraceID, 45, 7, @on +exec sp_trace_setevent @TraceID, 45, 55, @on +exec sp_trace_setevent @TraceID, 45, 8, @on +exec sp_trace_setevent @TraceID, 45, 16, @on +exec sp_trace_setevent @TraceID, 45, 48, @on +exec sp_trace_setevent @TraceID, 45, 64, @on +exec sp_trace_setevent @TraceID, 45, 1, @on +exec sp_trace_setevent @TraceID, 45, 9, @on +exec sp_trace_setevent @TraceID, 45, 17, @on +exec sp_trace_setevent @TraceID, 45, 25, @on +exec sp_trace_setevent @TraceID, 45, 41, @on +exec sp_trace_setevent @TraceID, 45, 49, @on +exec sp_trace_setevent @TraceID, 45, 10, @on +exec sp_trace_setevent @TraceID, 45, 18, @on +exec sp_trace_setevent @TraceID, 45, 26, @on +exec sp_trace_setevent @TraceID, 45, 34, @on +exec sp_trace_setevent @TraceID, 45, 50, @on +exec sp_trace_setevent @TraceID, 45, 3, @on +exec sp_trace_setevent @TraceID, 45, 11, @on +exec sp_trace_setevent @TraceID, 45, 35, @on +exec sp_trace_setevent @TraceID, 45, 51, @on +exec sp_trace_setevent @TraceID, 45, 4, @on +exec sp_trace_setevent @TraceID, 45, 12, @on +exec sp_trace_setevent @TraceID, 45, 28, @on +exec sp_trace_setevent @TraceID, 45, 60, @on +exec sp_trace_setevent @TraceID, 45, 5, @on +exec sp_trace_setevent @TraceID, 45, 13, @on +exec sp_trace_setevent @TraceID, 45, 29, @on +exec sp_trace_setevent @TraceID, 45, 61, @on +exec sp_trace_setevent @TraceID, 45, 6, @on +exec sp_trace_setevent @TraceID, 45, 14, @on +exec sp_trace_setevent @TraceID, 45, 22, @on +exec sp_trace_setevent @TraceID, 45, 62, @on +exec sp_trace_setevent @TraceID, 45, 15, @on +exec sp_trace_setevent @TraceID, 12, 7, @on +exec sp_trace_setevent @TraceID, 12, 15, @on +exec sp_trace_setevent @TraceID, 12, 31, @on +exec sp_trace_setevent @TraceID, 12, 8, @on +exec sp_trace_setevent @TraceID, 12, 16, @on +exec sp_trace_setevent @TraceID, 12, 48, @on +exec sp_trace_setevent @TraceID, 12, 64, @on +exec sp_trace_setevent @TraceID, 12, 1, @on +exec sp_trace_setevent @TraceID, 12, 9, @on +exec sp_trace_setevent @TraceID, 12, 17, @on +exec sp_trace_setevent @TraceID, 12, 41, @on +exec sp_trace_setevent @TraceID, 12, 49, @on +exec sp_trace_setevent @TraceID, 12, 6, @on +exec sp_trace_setevent @TraceID, 12, 10, @on +exec sp_trace_setevent @TraceID, 12, 14, @on +exec sp_trace_setevent @TraceID, 12, 18, @on +exec sp_trace_setevent @TraceID, 12, 26, @on +exec sp_trace_setevent @TraceID, 12, 50, @on +exec sp_trace_setevent @TraceID, 12, 3, @on +exec sp_trace_setevent @TraceID, 12, 11, @on +exec sp_trace_setevent @TraceID, 12, 35, @on +exec sp_trace_setevent @TraceID, 12, 51, @on +exec sp_trace_setevent @TraceID, 12, 4, @on +exec sp_trace_setevent @TraceID, 12, 12, @on +exec sp_trace_setevent @TraceID, 12, 60, @on +exec sp_trace_setevent @TraceID, 12, 13, @on +exec sp_trace_setevent @TraceID, 54, 7, @on +exec sp_trace_setevent @TraceID, 54, 8, @on +exec sp_trace_setevent @TraceID, 54, 64, @on +exec sp_trace_setevent @TraceID, 54, 9, @on +exec sp_trace_setevent @TraceID, 54, 25, @on +exec sp_trace_setevent @TraceID, 54, 41, @on +exec sp_trace_setevent @TraceID, 54, 49, @on +exec sp_trace_setevent @TraceID, 54, 6, @on +exec sp_trace_setevent @TraceID, 54, 10, @on +exec sp_trace_setevent @TraceID, 54, 14, @on +exec sp_trace_setevent @TraceID, 54, 22, @on +exec sp_trace_setevent @TraceID, 54, 26, @on +exec sp_trace_setevent @TraceID, 54, 3, @on +exec sp_trace_setevent @TraceID, 54, 11, @on +exec sp_trace_setevent @TraceID, 54, 35, @on +exec sp_trace_setevent @TraceID, 54, 51, @on +exec sp_trace_setevent @TraceID, 54, 4, @on +exec sp_trace_setevent @TraceID, 54, 12, @on +exec sp_trace_setevent @TraceID, 54, 60, @on + + +-- Set the Filters +declare @intfilter int +declare @bigintfilter bigint + +exec sp_trace_setfilter @TraceID, 10, 0, 7,''SQLProfiler'' +exec sp_trace_setfilter @TraceID, 10, 0, 7,''SQLAgent'' +exec sp_trace_setfilter @TraceID, 10, 0, 7,''SQLServerManagementStudio'' +exec sp_trace_setfilter @TraceID, 10, 0, 1,'''' +exec sp_trace_setfilter @TraceID, 35, 1, 6,''msdb'' +exec sp_trace_setfilter @TraceID, 35, 1, 6, ''mysales_remote4'' +exec sp_trace_setfilter @TraceID, 35, 1, 6, ''distribution'' +exec sp_trace_setfilter @TraceID, 35, 1, 6, ''mysales_remote5'' +exec sp_trace_setfilter @TraceID, 35, 1, 6, ''mysales_tranperf'' +exec sp_trace_setfilter @TraceID, 35, 1, 6, ''mysales_tranperf1'' + +-- Set the trace status to start +exec sp_trace_setstatus @TraceID, 1 + +-- display trace id for future references +select TraceID=@TraceID +goto finish + +error: +select ErrorCode=@rc + +finish: +go +', +@database_name='master', +@flags=0 +IF (@@ERROR <> 0 OR @ReturnCode <> 0) +GOTO QuitWithRollback + +/* Step 2: STOP AND CLOSE THE TRACE */ + +EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, +@step_name='Stop and close the trace', +@step_id=2, +@cmdexec_success_code=0, +@on_success_action=1, +@on_success_step_id=0, +@on_fail_action=2, +@on_fail_step_id=0, +@retry_attempts=0, +@retry_interval=0, +@os_run_priority=0, +@subsystem='TSQL', +@command='exec sp_trace_setstatus @TraceID, 0 +go +exec sp_trace_setstatus @TraceID,2 +', +@database_name='master', +@flags=0 + +IF (@@ERROR <> 0 OR @ReturnCode <> 0) +GOTO QuitWithRollback + +EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, +@start_step_id = 1 + +IF (@@ERROR <> 0 OR @ReturnCode <> 0) +GOTO QuitWithRollback + +/* Schedule the job */ +EXEC @ReturnCode = msdb.dbo.sp_add_jobschedule +@job_id=@jobId, @name='mysales_tranperf1_schedule', +@enabled=1, +@freq_type=8, +@freq_interval=4, +@freq_subday_type=8, +@freq_subday_interval=1, +@freq_relative_interval=0, +@freq_recurrence_factor=1, +@active_start_date=20060627, +@active_end_date=99991231, +@active_start_time=0, +@active_end_time=235959 + +IF (@@ERROR <> 0 OR @ReturnCode <> 0) +GOTO QuitWithRollback + +EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, +@server_name ='(Local)' + +IF (@@ERROR <> 0 OR @ReturnCode <> 0) +GOTO QuitWithRollback + +COMMIT TRANSACTION + +GOTO EndSave + +QuitWithRollback: + IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION +EndSave: +Listing 18-7. Find what stored procedures are consuming high CPUs trace +/*Execute this on the database where the trace data is stored */ +use performance +go + +select spid, +CPU, +(Duration/1000) as duration, +textdata, +reads, +writes, +objectname, +databasename +from mysales_tranperf1_trace +where CPU>(5000) and +textdata like '%sp%' and +order by CPU +Listing 18-8. Retrieving event names and the corresponding subclass names +/* Execute this on the database where the trace data is stored */ + +use performance +go + +select a.CPU, +a.duration, +a.textdata, +a.eventclass, +a.databasename, +a.reads, +c.name, +b.subclass_name +from mysales_tranperf1_trace as a, +sys.trace_subclass_values as b, +sys.trace_events as c +where eventclass in (10,12,45) +and CPU>15000 +and c.trace_event_id=b.trace_event_id +and a.textdata like '%sp_addsubscription%' +order by CPU desc +go +Listing 18-9. Determining the CPU utilization of other replicated databases +/* Execute this on the database where the trace data is stored */ +use performance + +go + +select spid, +CPU, +(duration/1000)as duration, +textdata, +reads, +writes, +objectname, +databasename +from mysales_tranperf1_trace +where CPU>(4000) and +databasename not like 'mysales%' +order by CPU desc +Listing 18-10. Transactions where the CPU utilization is greater than duration of eventclass +/* Execute this on the database where the trace data is stored */ +use performance + +go +select spid, +CPU, +duration, +eventclass, +textdata, +reads, +writes, +objectname, +databasename +from mysales_tranperf1_trace +where CPU>(duration/1000) +and eventclass in (10,12,45) +order by CPU desc +go +Listing 18-11. Finding out whether the CPU utilization of insert statements exceeded the duration +/* Execute this on the database where the trace data is stored */ +use performance + +go + +select spid, +CPU, +duration, +eventclass, +textdata, +reads, +writes, +objectname, +databasename +from mysales_tranperf1_trace +where CPU>(duration/1000) +and databasename not like 'distribution%' +and eventclass in (10,12,45) +and textdata like '%sp_MSins%' +order by CPU desc +go +Listing 18-12. Finding out what kind of workload was used +/*Execute this on the msdb database *. + +select sessionid, +sessionname, +tuningoptions, +logtablename +from msdb.dbo.DTA_input +go +Listing 18-13. Determining the recommended and current costs of executing different statements +/*Execute this on the msdb database */ +use msdb +go + +select a.schemaname, +a.tablename, +d.DatabaseName, +d.isdatabaseselectedtotune, +b.isclustered, +b.numrows, +b.recommendedstorage, +c.statementstring, +c.currentcost, +c.recommendedcost, +c.weight, +c.eventstring +from msdb.dbo.DTA_reports_table as a, +msdb.dbo.DTA_reports_index as b, +msdb.dbo.DTA_reports_query as c, +msdb.dbo.DTA_reports_database as d +where a.schemaname not like 'dbo' and +a.tableid=b.tableid and +c.sessionid=d.sessionid and +d.databasename like 'mysales%' +go +Listing 18-14. Finding statements that have not been tuned +/* Execute this on the msdb database */ + +use msdb +go + +select b.categoryid, +b.event, +b.statement, +b.frequency, +b.reason +from dbo.DTA_input as a, +dbo.DTA_tuninglog as b +where statement not like ' ' +and a.sessionid=b.sessionid +and a.sessionname like 'mysales_transactionalperformance' +go + + diff --git a/Codes/Chapter19/Chapter19codes.txt b/Codes/Chapter19/Chapter19codes.txt new file mode 100644 index 0000000..62ad573 --- /dev/null +++ b/Codes/Chapter19/Chapter19codes.txt @@ -0,0 +1,304 @@ +Listing 19-1. Capturing the Showplan trace and analyzing it +/*Execute this on the trace database, performance */ +use performance +go + +/*Step 1: Load the data from the trace file for the Showplan XML event */ +select textdata, +spid, +cpu, +duration, +databasename, +objectname, +linenumber, +objecttype, +reads, +writes +into showplanmerge_down +from fn_trace_gettable('c:\files\mysales_merge_downloadpub.trc', default) +where eventclass=122 +go + +/*Step 2: Query the showplanmerge_down table */ + +select spid, +textdata, +databasename, +objectname, +objecttype +from showplanmerge_down +where textdata like '%item%' and objectname not like 'dynamic%' +order by spid +go +Listing 19-2. Determining the performance cost for executing merge triggers +/*Execute this on the performance database */ +use performance +go + +select spid, +cpu, +duration, +textdata, +databasename, +objectname, +objecttype, +reads, +writes +from mysales_tranperf_mergetrace +where textdata like '%trigger%' +and objecttype in (8272,21076) +order by cpu desc +go +Listing 19-3. Using SQLCMD to generate separate tables for trigger trace data +/* Use the SQLCMD utility to execute this script */ +:setvar logintimeout 120 +:setvar server "BIO-V7V30JTZLS\BIOREPL" +:setvar user "sa" +:setvar pwd "sujoy" +:connect $(server) -l $(logintimeout) -U $(user) -P $(pwd) + +/* Use the database that holds the performance data */ + +Use $(db) +select $(col1), --textdata +$(col2), --spid +$(col3), -- cpu, +$(col4), ---duration +$(col5), --- databasename +$(col6), ---objectname +$(col7), ---linenumber +$(col8), ---objecttype +$(col9),---reads +$(col10) ---writes + /* Name of the table in the performance database showplanmerge_down */ +into $(tablename) +/*Name of the file''c:\files\mysales_merge_downloadpub.t'c', default) */ +/* Just change the file extension if the trace file you are +using is of file type XML(*.xml) or SQLPlan (*.SQLPlan) */ +from fn_trace_gettable('$(path).trc',default) +/* SP:StmtCompleted =45 */ + +where eventclass=$(eventclass) +go +select $(col2), +$(col1), +$(col5), +$(col6), +$(col8) +from $(tablename) +---showplanmerge_down +where textdata like '$(stringvar1)' +---'%item%' +and objectname not like '$(stringvar2)' +---'dynamic%' +order by $(col2) +go +Listing 19-4. XML schema definition for the exploratory analysis using the DTA command-line utility + + + + BIO-V7V30JTZLS\BIOREPL + + mysales_downloadpushsub + + myinventory + + Item +
+ + PriceList +
+ + Warehouse +
+
+ + myorder + + +SalesPerson +
+
+
+ + mysales_remote1 + + myfinance + + AcccountsReceivable +
+ +AccountInvoice +
+ + CashReceipt +
+
+ + myinventory + + Item +
+ + PriceList +
+ + PurchaseOrderDetail +
+ + PurchaseOrderHeader +
+ +StockItem +
+ + Vendor +
+ + Warehouse +
+
+ + myorder + + BillTO +
+ + Customer +
+ + CustSales +
+ + OrderHeader +
+ + SalesPerson +
+ + ShipTO +
+ + Stock +
+ + ZONE +
+
+
+ + mysales_tranperf1 + + myfinance + + AccountInvoice +
+ + AccountsReceivable +
+ + CashReceipt +
+
+ + myinventory + + Item +
+ + PriceList +
+ + PurchaseOrderDetail +
+ + PurchaseOrderHeader +
+ + StockItem +
+ + Vendor +
+ + Warehouse +
+
+ + myorder + + BillTO +
+ + Customer +
+ + CustSales +
+ + OrderDetail +
+ + OrderHeader +
+ + SalesPerson +
+ + ShipTO +
+ + Stock +
+ + ZONE +
+
+
+
+ + + + + C:\files\mysales_merge_downloadpub.trc + + + + + + 52 + 30 + 1023 + + NONE + MIXED + performance + + + + + + + BIO-V7V30JTZLS\BIOREPL + +mysales_merge + +myinventory + + Item + + + + PK_Item + + + +
+
+
+
+
+
+ + diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..30e4776 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,27 @@ +Freeware License, some rights reserved + +Copyright (c) 2006 Sujoy Paul + +Permission is hereby granted, free of charge, to anyone obtaining a copy +of this software and associated documentation files (the "Software"), +to work with the Software within the limits of freeware distribution and fair use. +This includes the rights to use, copy, and modify the Software for personal use. +Users are also allowed and encouraged to submit corrections and modifications +to the Software for the benefit of other users. + +It is not allowed to reuse, modify, or redistribute the Software for +commercial use in any way, or for a user’s educational materials such as books +or blog articles without prior permission from the copyright holder. + +The above copyright notice and this permission notice need to be included +in all copies or substantial portions of the software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS OR APRESS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + diff --git a/README.md b/README.md new file mode 100644 index 0000000..01f026d --- /dev/null +++ b/README.md @@ -0,0 +1,15 @@ +#Apress Source Code + +This repository accompanies [*Pro SQL Server 2005 Replication*](http://www.apress.com/9781590596500) by Sujoy Paul (Apress, 2006). + +![Cover image](9781590596500.jpg) + +Download the files as a zip using the green button, or clone the repository to your machine using Git. + +##Releases + +Release v1.0 corresponds to the code in the published book, without corrections or updates. + +##Contributions + +See the file Contributing.md for more information on how you can contribute to this repository. diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..1d69072 --- /dev/null +++ b/README.txt @@ -0,0 +1,3 @@ +README.TXT + +The zip file contains code listings for Chapters 2,5,6,7,9,10,13,14,15,16,17,18,19, Appendix B and the README.TXT. The code listings are listed under the respective chapter directories in the zip file. There are 168 code listings in the book. The code listings for the Sidebars in the chapters are also included. Chapters 2,5,14 and 17 contain the Sidebar code listings. There are 6 Sidebar code listings in the book. Appendix B contains the code for the mysales database schema used in the book. \ No newline at end of file diff --git a/contributing.md b/contributing.md new file mode 100644 index 0000000..f6005ad --- /dev/null +++ b/contributing.md @@ -0,0 +1,14 @@ +# Contributing to Apress Source Code + +Copyright for Apress source code belongs to the author(s). However, under fair use you are encouraged to fork and contribute minor corrections and updates for the benefit of the author(s) and other readers. + +## How to Contribute + +1. Make sure you have a GitHub account. +2. Fork the repository for the relevant book. +3. Create a new branch on which to make your change, e.g. +`git checkout -b my_code_contribution` +4. Commit your change. Include a commit message describing the correction. Please note that if your commit message is not clear, the correction will not be accepted. +5. Submit a pull request. + +Thank you for your contribution! \ No newline at end of file