SQl触发器,插入限制值

时间:2013-07-08 09:19:20

标签: sql-server tsql triggers

我有两张桌子:

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

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

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

每个值都添加到table2中,值[Numerik]和[MaTune]应报告到table1,其中[DocNo]类似

但是如果我添加具有相同doc号的第二个值,我发现了一个错误。考试结束后,我找到了为什么,当我要求更新日期/时间时,会报告每个docuemnt使用相同的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

1 个答案:

答案 0 :(得分: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