Should I use SQL Server triggers for migrating a database?

Viewed 177

I need migrate anything from SQL Server to MongoDB.

SQL Server continuously inserts, updates, deletes data, and I want to move that data to MongoDB.

Example trigger:

BEGIN
BEGIN TRY
BEGIN TRAN
    DECLARE @tableName VARCHAR(50) = 'AutoPushData_OK'
    DECLARE @event_type varchar(42)
    IF EXISTS(SELECT * FROM inserted)
        IF EXISTS(SELECT * FROM deleted)
            SELECT @event_type = 'update'
    ELSE
            SELECT @event_type = 'insert'
    ELSE
        IF EXISTS(SELECT * FROM deleted)
            SELECT @event_type = 'delete'
        ELSE
            SELECT @event_type = 'unknown'

    IF @event_type ='insert' or @event_type = 'update'
    BEGIN
        INSERT INTO ReplicationData.dbo.MigrateData (JsonData, TableName, CRUD)
            SELECT
                (SELECT * FROM inserted FOR JSON AUTO), 
                @tableName, @event_type
    END
    ELSE IF @event_type = 'delete'
    BEGIN
        INSERT INTO ReplicationData.dbo.MigrateData (JsonData, TableName, CRUD)
            SELECT 
                (SELECT * FROM deleted FOR JSON AUTO),
                @tableName, @event_type
    END

    COMMIT TRAN
END TRY
BEGIN CATCH
    DECLARE @ErrorMsg VARCHAR(MAX), 
            @ErrorNumber INT, 
            @ErrorProc sysname, 
            @ErrorLine INT 

    SELECT 
        @ErrorMsg = ERROR_MESSAGE(), 
        @ErrorNumber = ERROR_NUMBER(), 
        @ErrorProc = ERROR_PROCEDURE(), 
        @ErrorLine = ERROR_LINE();

    ROLLBACK TRAN;

    INSERT INTO ErrorLog (ErrorMsg,  ErrorNumber,  ErrorProc,  ErrorLine)
    VALUES               (@ErrorMsg, @ErrorNumber, @ErrorProc, @ErrorLine)
END CATCH 
END

I will insert all changes of table AutoPushData_OK to dbo.MigrateData and use a service insert data from dbo.MigrateData into MongoDB.

Question: is there any danger in my way of doing this?

Is there any better way?

Thanks

2 Answers

In general, avoid triggers if you can. Especially in the case of data migration of this type, it will be very inefficient in terms of speed of operation (additional load on the production database).

SQL Server has special tools for maintaining database copies - database mirroring. You can find more information here.

My suggestion is that you migrate your data first to the second SQL Server database (database mirroring) and from there to MongoDB (even with triggers if you want). Thanks to this, you will get something closer to asynchronous data exchange, which will not burden the production database with triggers so much. SQL Server databases will exchange data in their own way without disrupting the main system.

you will not face any issues. but it is always recommended to avoid the same data in multiple tables.

Related