Skip to content

Instantly share code, notes, and snippets.

@doeringp
Last active June 17, 2022 10:41
Show Gist options
  • Save doeringp/42743add3e7360318407fca5e9bb40a0 to your computer and use it in GitHub Desktop.
Save doeringp/42743add3e7360318407fca5e9bb40a0 to your computer and use it in GitHub Desktop.
Data replication between databases on the same server using triggers (for SQL Server)

Data replication between databases on the same server using triggers (for SQL Server)

This sample shows how to replicate data between two tables in different databases on the same server. I was looking for the most simple pragmatic approach I could think of. Please be aware that triggers have some disadvantages. Please think carefully before following the approach.

How it works

  • If you insert a row in the table in database A
  • a trigger will execute automatically
  • and add the same row to the table in database B.
CREATE DATABASE [ReplicationTestB]
GO
USE [ReplicationTestB]
GO
CREATE TABLE [dbo].[Products](
[Name] [nvarchar](100) NOT NULL
) ON [PRIMARY]
GO
CREATE DATABASE [ReplicationTestA]
GO
USE [ReplicationTestA]
GO
CREATE TABLE [dbo].[Products](
[Name] [nvarchar](100) NOT NULL
) ON [PRIMARY]
GO
CREATE TRIGGER [dbo].[replication_trigger]
ON [dbo].[Products]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO ReplicationTestB.dbo.Products
SELECT * FROM INSERTED
END
GO
ALTER TABLE [dbo].[Products] ENABLE TRIGGER [replication_trigger]
GO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment