0

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

    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

附言。请不要回复触发器。谢谢 :)

4

2 回答 2

0
If (NOT EXISTS(..code to test for existance ))
 BEGIN    
            RAISERROR ('Already answered', 16, 1);
            ROLLBACK TRANSACTION;
            RETURN 
 END
于 2013-09-12T02:37:47.713 回答
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
于 2013-09-12T03:30:43.460 回答