Search code examples
sql-serversql-server-2008replicationsql-server-agenttransactional-replication

transactional replication using script


I am able to configure transactional replication using SSMS and it works properly. But i want to configure it using script so that i use it from my c#/vb application.

Is there any way to do that?


Solution

  • If you complete all the step of transactional replication using SSMS then it's not complicated to do with the script.

    Just carefully observe that when you configure distribution, publication and subscription SSMS gives you the option to generate script in every step.

    You can use that generated script.

    But only difference is when you add articles to publication. You can use the following code to add article

    declare @name nvarchar(50)
    declare curname cursor for
    select name from sysobjects where type = 'U'
    open curname
    fetch next from curname into @name
    while @@FETCH_STATUS = 0
    begin
    if exists(select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = @name AND TABLE_SCHEMA = 'dbo')
    begin
    exec sp_addarticle
    @publication = N'publication_name', @article = @name, @source_owner = N'dbo',
    @source_object = @name, @type = N'logbased', @description = null, @creation_script = null,
    @pre_creation_cmd = N'drop', @schema_option = 0x000000000803509F,
    @identityrangemanagementoption = N'manual', @destination_table = @name,
    @destination_owner = N'dbo', @vertical_partition = N''
    end
    fetch next from curname into @name
    end
    close curname
    deallocate curname
    

    Or, you can see https://hasibarnab.wordpress.com/category/sql-server/replication/