A
A
alex995052018-03-03 10:20:51
SQL Server
alex99505, 2018-03-03 10:20:51

MSSQL the trigger on data receipt and their copying in other DB?

How to put a trigger in MSSQL that would work when data arrives and copy this same data to another database after changing it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
d-stream, 2018-03-03
@d-stream

https://msdn.microsoft.com/ru-ru/library/ms189799(...
Unless, of course, the term "incoming" means insert or update,
respectively

create trigger имя_триггера on имя_таблицы after insert, update, delete as
....

You can even have fun and make a trigger instead of and then get lulz from brain explosions trying to figure out why the data is not inserted)

K
Konstantin Tsvetkov, 2018-03-03
@tsklab

But interests how to interpose into other DB.
Put the name of the database before the table name. Naturally, the user must have the necessary rights.
INSERT INTO Gamege.dbo.TestTable (f1)
VALUES ('test')

TRIGGER and CURSOR
CREATE TRIGGER AlbumRoleInsert ON AlbumRole INSTEAD OF INSERT AS 
BEGIN
  DECLARE @ALB INT, @PRF INT, @ROL VARCHAR(500), @mas INT, @pla BIT, @mem BIT, @gue BIT
  DECLARE @ID INT, @RLR VARCHAR(500)
  
  DECLARE LISTROLE CURSOR LOCAL FAST_FORWARD FOR
    SELECT Album, Master, Performer, Play, Member, Role, SpecialGuest
      FROM Inserted
  OPEN LISTROLE
  FETCH LISTROLE INTO @ALB, @mas, @PRF, @pla, @mem, @ROL, @gue
  WHILE @@FETCH_STATUS = 0 BEGIN
    -- Есть запись?
    IF EXISTS( SELECT * FROM AlbumRole WHERE (Album = @ALB) AND (Performer = @PRF)) BEGIN
      SELECT @ID = ID, @RLR = Role FROM AlbumRole WHERE (Album = @ALB) AND (Performer = @PRF)
      -- Есть роль?
      IF ( CHARINDEX( @ROL, @RLR) = 0 ) SET @RLR = @RLR + ', ' + @ROL
      IF ( @RLR IS NULL ) SET @RLR = @ROL
      -- Обновление списка.
      UPDATE AlbumRole SET Role = @RLR WHERE ID = @ID
    END ELSE BEGIN
      -- Добавление: 
      INSERT INTO AlbumRole ( Album, Master, Performer, Play, Member, Role, SpecialGuest ) 
             VALUES( @ALB, @mas, @PRF, @pla, @mem, @ROL, @gue )
    END
    -- Следующее поле
    FETCH LISTROLE INTO @ALB, @mas, @PRF, @pla, @mem, @ROL, @gue
  END
  CLOSE LISTROLE
  DEALLOCATE LISTROLE
           
END
--
GO

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question