用于更新的MSSQL触发器仅工作一次

时间:2017-07-10 10:26:54

标签: sql sql-server tsql sql-server-2012 database-trigger

我要创建一个更新触发器。此触发器的目的是,如果更改 muadurum 列,请使用表fkayitlar中的旧值 mua_tarih 并插入另一个表 mua_tarihleri 。< / p>

我的代码块像;

ALTER TRIGGER [dbo].[trgr_fkayit_update]
ON [dbo].[fkayitlar]
AFTER UPDATE
AS
DECLARE @mua_durum_once NVARCHAR(10)
DECLARE @mua_durum_sonra NVARCHAR(10)
DECLARE @mua_tarih_once DATE
DECLARE @mua_yapan_once NVARCHAR(25)
DECLARE @kisi_id INT

取旧值;

SELECT
@kisi_id=kayitid,
@mua_durum_once=muayenedurum,
@mua_tarih_once=muayenetarih,
@mua_yapan_once=mua_yapan 
FROM deleted

取新值;

SELECT @mua_durum_sonra=muayenedurum FROM inserted

检查值是否改变;如果更改,请使用 @kisi_id @mua_yapan_once

将@mua_tarih插入表 mua_tarihleri
  IF @mua_durum_once='OLDU' 
  AND @mua_durum_sonra='OLMADI' 
   AND @mua_tarih_once IS NOT NULL
   BEGIN
    INSERT INTO mua_tarihleri(kayitid,mua_tarihi,mua_yapan) 
        VALUES(@kisi_id,@mua_tarih_once,@mua_yapan_once)
     END

我的问题是当我更新表fkayitlar中的多行时,Trigger正在工作,但我看到表 mua_tarihleri 中只有一行插入行(仅工作一次)。我需要看多个。(应该多次工作)不是触发器在多个进程上工作吗?如何解决这个问题? < / p>

1 个答案:

答案 0 :(得分:1)

触发器仅在更新表时发生一次,无论更新了多少行。因此,您必须编写触发器主体来操作一组行,而不是像您一样操作。

应该是这样的:

ALTER TRIGGER [dbo].[trgr_fkayit_update]
ON [dbo].[fkayitlar]
AFTER UPDATE
AS
    INSERT INTO mua_tarihleri(kayitid,mua_tarihi,mua_yapan) 
    SELECT deleted.kayitid, deleted.muayenedurum, deleted.muayenetarih, deleted.mua_yapan 
    FROM deleted
    JOIN inserted ON deleted.kayitid = inserted.kayitid
    WHERE deleted.muayenedurum='OLDU'
        AND inserted.muayenedurum='OLMADI'
        AND muayenetarih IS NOT NULL