触发后有条件

时间:2013-09-12 02:12:37

标签: sql triggers conditional

我需要创建一个后触发器。 (严格禁止触发后)。我认为我在正确的轨道上,但似乎无法让它正确执行。它似乎始终执行触发器并在所有插入语句上显示错误消息,而不是仅在存在重复时。这就是我的意思;

    CREATE TRIGGER Copies
    ON table
    AFTER INSERT

    AS
    Declare @number int 
    Set @number = (Select Count(*) from inserted)

    If @number >0
       (
       SELECT *
       FROM table O
       JOIN inserted AS i 
       ON t.q_id = i.q_id 

       WHERE O.username = i.username 
        AND t.q_id = i.q_id
       )

    BEGIN
            RAISERROR ('Already answered', 16, 1);
            ROLLBACK TRANSACTION;
            RETURN 
    END;
    GO

聚苯乙烯。 请不要回复触发器。谢谢:))

2 个答案:

答案 0 :(得分:0)

If (NOT EXISTS(..code to test for existance ))
 BEGIN    
            RAISERROR ('Already answered', 16, 1);
            ROLLBACK TRANSACTION;
            RETURN 
 END

答案 1 :(得分:0)

使用count

尝试此新触发器
CREATE TRIGGER Copies
ON table
AFTER INSERT

AS
DECLARE @Counter int
SELECT @Counter = COUNT(*)
FROM table T
JOIN inserted AS i 
    ON T.username = i.username 
    AND t.q_id = i.q_id
GROUP BY T.username, t.q_id 

If (@Counter > 1) 
BEGIN
        RAISERROR ('Already answered', 16, 1);
        ROLLBACK TRANSACTION;
        RETURN 
END;
GO