1

My goal is to keep 3 separate SQL server instances which have the some table on one of their DBs up to date, meaning every insert I do on one table should be done exactly the some on the other 2. At the moment I am using the below SP (resided on all DBs):

   ---SP for Inserting a row in myTable
    --IF ANY Errors Occur we rollback and return FALSE
    --ELSE WE Return the ID of the row inserted (integer)

    CREATE PROCEDURE [dbo].[sp_InsertWithRollback] @PartnerId [int]
        --the table fields as parameters

    AS
    DECLARE @TransactionName VARCHAR(20) = 'InsertTrans';

    BEGIN TRY
        BEGIN TRAN @TransactionName

        INSERT INTOmy table (
            ---
            ...
            ...
            )
        VALUES (
            ---
            ...
            ---
            )
        COMMIT;
        SELECT SCOPE_IDENTITY();

    END TRY

    BEGIN CATCH
        ROLLBACK TRAN @TransactionName;
        SELECT 'FALSE';
    END CATCH

on a C# program I use a loop (for ever one of 3 instances) where I am calling the SP for each one of the tables. If in any of those calls I get a 'FALSE' return instead of an int, I go over the other instances and delete the rows with given ID.

The problem with the above logic is that I am doing a delete if I get an error - exception. Ideally I would like to rollback and avoid deletes. Is there any good idea how will I replace the commit - delete with something smarter like ---, rollback?

apomene
  • 14,282
  • 9
  • 46
  • 72
  • 1
    You could use TransactionScope in the C# code and remove the explicit transactions in the procs. – Dan Guzman Sep 19 '17 at 15:34
  • Although the question text might be different I feel like the [answer](https://stackoverflow.com/a/22512547/1260204) on `TransactionScope` is exactly what it is you are looking for. Please let me know if that is not the case. – Igor Sep 19 '17 at 15:39
  • Can you use just **one SP for the 3 tables** and it is just one transaction? or in **C# you can use EF and just call the SaveChanges()** – Victor Hugo Terceros Sep 19 '17 at 15:41
  • @VictorHugoTerceros - The way I read it: It is 3 separate sql server instances, 1 database per instance, and the schema (for this logic anyways) is the same. – Igor Sep 19 '17 at 15:42

0 Answers0