-1

我正在弄清楚如果表中已经存在两个值,则在触发器执行后执行的 sql 脚本。例如。

该表显示:

╔══════════════════════════════╗
║ User_name Question_ID Answer ║
╠══════════════════════════════╣
║     Tom       Q001        D  ║
║     Sam       Q002        F  ║
╚══════════════════════════════╝

如果我希望用户只能提交一个问题的答案那么如果我插入值('Tom','Q002''A'),它将成功插入。但是,如果我插入值('Tom','Q001''A'),它将执行触发器,因为同一用户试图回答同一问题。

我写道:

    Create Trigger insert_question1
    on [dbo].[Questions]
    After insert
    As
    if 
    Begin
    Print 'You already answered'
    Rollback 
    End

如果请帮助我,我找不到条件:C

4

1 回答 1

1

尝试这样的事情:

CREATE TRIGGER INSERT_QUESTION1 
ON DBO.QUESTIONS 
INSTEAD OF INSERT 
AS 
  BEGIN 
      INSERT INTO [dbo].[QUESTIONS] 
      SELECT I.[USER_NAME], 
             I.QUESTION_ID, 
             I.ANSWER 
      FROM   INSERTED I 
      WHERE  NOT EXISTS (SELECT * 
                         FROM   QUESTIONS Q 
                         WHERE   Q.QUESTION_ID = I.QUESTION_ID 
                                AND Q.USER_NAME = I.USER_NAME) 
  END 

GO 

此触发器将防止将重复项插入到表中。
你真的需要Print 'You already answered'吗?
如果是,只需将其添加到触发器的末尾:

IF @@ROWCOUNT = 0 
  PRINT 'You already answered' 
于 2013-09-02T16:56:36.050 回答