0

我有 2 张桌子:

表 1 : [DocNo],[Numerik],[[MaTune]

表 2:[DocNo]、[RowNo]、[Numerik]、[MaTune]、[DateData]

我想在 Table2 上创建一个触发器:

每个值都添加到表 2 中,值 [Numerik] 和 [MaTune] 应报告到表 1 中,其中 [DocNo] 相似。

但是,如果我添加具有相同文档编号的第二个值,我会发现错误。经过考试,我发现为什么当我要求更新日期/时间时,它会报告每个具有相同 DocNo 和 RowNo 的文档。

我怎样才能只将值修改到我的触发器中?

这是我的代码:

CREATE TRIGGER [dbo].[Tr_MAJ] 
   ON  [dbo].[Table2]
   AFTER INSERT,UPDATE
AS 
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    --Déclaration des variables
    DECLARE @DocNo INT
    DECLARE @RowNo SMALLINT
    DECLARE @Numerik INT
    DECLARE @MaTune DECIMAL(15,2)
    DECLARE @DocNo_TheCat INT



   --Attribution des variables
    SELECT @DocNo = DocNo, @RowNo=RowNo, @Numerik = Numerik, @MaTune = Matune FROM inserted

   --Mise à jour de la date et l'heure dans Table2
    UPDATE Table2 SET Datedata= GETDATE() WHERE RowNo=@RowNo AND DocNo=@DocNo



   IF (SELECT MaTune from Table1 where DocNo=@DocNo) IS NULL
    BEGIN
        UPDATE Table1 SET MaTune = @MaTune, Numerik = @Numerik where DocNo=@DocNo
    END

    IF (SELECT MaTune from Table1 where DocNo=@DocNo) IS NOT NULL
        BEGIN

            --On attribue les nouvelles variables
            SELECT @DocNo_TheCat = DocNo, @RowNo=RowNo, @Numerik = Numerik, @MaTune = Matune FROM TheIxTable178 where DocNo=@DocNo  and RowNo=@RowNo and datedata = (select TOP 1 MAX(datedata) from Table2)

            UPDATE Table1 SET MaTune = @MaTune, Numerik = @Numerik where DocNo=@DocNo_TheCat
    END





END
4

1 回答 1

0

当 table2 主键(OK)在插入的表中时,这意味着这些记录已被修改(插入或更新),因此请尝试使用以下代码:

..... WHERE table2PK in (Select table2PK from inserted)

你需要使用集合操作,

UPDATE t1 SET MaTune = mat
FROM inserted i 
JOIN table2 AS t2 ON i.docNO = t2.docno -- or whatever join conditions you assume that is OK!
JOIN table1 AS t1 ON t1.docNo = i.docno 
于 2013-07-08T09:31:22.073 回答