Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am figuring out sql script that after trigger execute if two values are already existing in tables. For example.

The table shows:

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

If I hope that a user can submit only one answer on a question So if I insert values ('Tom', 'Q002' 'A') it will successfully insert. But if I insert values ('Tom', 'Q001' 'A') it will execute trigger as same user tried to answer on same question.

I wrote like:

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

I cannot find the condition after IF plz help me :C

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
129 views
Welcome To Ask or Share your Answers For Others

1 Answer

Try something like this:

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 

This trigger will prevent a duplicate from being inserted into the table.
Do you really need the Print 'You already answered' ?
If yes, just add this to the end of the trigger:

IF @@ROWCOUNT = 0 
  PRINT 'You already answered' 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...